babylon.no-module.max.js 5.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853
  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. /**
  1242. * Gather the list of keyboard event types as constants.
  1243. */
  1244. var KeyboardEventTypes = /** @class */ (function () {
  1245. function KeyboardEventTypes() {
  1246. }
  1247. /**
  1248. * The keydown event is fired when a key becomes active (pressed).
  1249. */
  1250. KeyboardEventTypes.KEYDOWN = 0x01;
  1251. /**
  1252. * The keyup event is fired when a key has been released.
  1253. */
  1254. KeyboardEventTypes.KEYUP = 0x02;
  1255. return KeyboardEventTypes;
  1256. }());
  1257. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1258. /**
  1259. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1260. */
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. /**
  1263. * Instantiates a new keyboard info.
  1264. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1265. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1266. * @param event Defines the related dom event
  1267. */
  1268. function KeyboardInfo(
  1269. /**
  1270. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1271. */
  1272. type,
  1273. /**
  1274. * Defines the related dom event
  1275. */
  1276. event) {
  1277. this.type = type;
  1278. this.event = event;
  1279. }
  1280. return KeyboardInfo;
  1281. }());
  1282. BABYLON.KeyboardInfo = KeyboardInfo;
  1283. /**
  1284. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1285. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1286. */
  1287. var KeyboardInfoPre = /** @class */ (function (_super) {
  1288. __extends(KeyboardInfoPre, _super);
  1289. /**
  1290. * Instantiates a new keyboard pre info.
  1291. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfoPre(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. var _this = _super.call(this, type, event) || this;
  1305. _this.type = type;
  1306. _this.event = event;
  1307. _this.skipOnPointerObservable = false;
  1308. return _this;
  1309. }
  1310. return KeyboardInfoPre;
  1311. }(KeyboardInfo));
  1312. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1313. })(BABYLON || (BABYLON = {}));
  1314. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1315. var BABYLON;
  1316. (function (BABYLON) {
  1317. /**
  1318. * Gather the list of pointer event types as constants.
  1319. */
  1320. var PointerEventTypes = /** @class */ (function () {
  1321. function PointerEventTypes() {
  1322. }
  1323. /**
  1324. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1325. */
  1326. PointerEventTypes.POINTERDOWN = 0x01;
  1327. /**
  1328. * The pointerup event is fired when a pointer is no longer active.
  1329. */
  1330. PointerEventTypes.POINTERUP = 0x02;
  1331. /**
  1332. * The pointermove event is fired when a pointer changes coordinates.
  1333. */
  1334. PointerEventTypes.POINTERMOVE = 0x04;
  1335. /**
  1336. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1337. */
  1338. PointerEventTypes.POINTERWHEEL = 0x08;
  1339. /**
  1340. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1341. */
  1342. PointerEventTypes.POINTERPICK = 0x10;
  1343. /**
  1344. * The pointertap event is fired when a the object has been touched and released without drag.
  1345. */
  1346. PointerEventTypes.POINTERTAP = 0x20;
  1347. /**
  1348. * The pointertap event is fired when a the object has been touched and released twice without drag.
  1349. */
  1350. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1351. return PointerEventTypes;
  1352. }());
  1353. BABYLON.PointerEventTypes = PointerEventTypes;
  1354. /**
  1355. * Base class of pointer info types.
  1356. */
  1357. var PointerInfoBase = /** @class */ (function () {
  1358. /**
  1359. * Instantiates the base class of pointers info.
  1360. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1361. * @param event Defines the related dom event
  1362. */
  1363. function PointerInfoBase(
  1364. /**
  1365. * Defines the type of event (BABYLON.PointerEventTypes)
  1366. */
  1367. type,
  1368. /**
  1369. * Defines the related dom event
  1370. */
  1371. event) {
  1372. this.type = type;
  1373. this.event = event;
  1374. }
  1375. return PointerInfoBase;
  1376. }());
  1377. BABYLON.PointerInfoBase = PointerInfoBase;
  1378. /**
  1379. * This class is used to store pointer related info for the onPrePointerObservable event.
  1380. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1381. */
  1382. var PointerInfoPre = /** @class */ (function (_super) {
  1383. __extends(PointerInfoPre, _super);
  1384. /**
  1385. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1386. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1387. * @param event Defines the related dom event
  1388. * @param localX Defines the local x coordinates of the pointer when the event occured
  1389. * @param localY Defines the local y coordinates of the pointer when the event occured
  1390. */
  1391. function PointerInfoPre(type, event, localX, localY) {
  1392. var _this = _super.call(this, type, event) || this;
  1393. /**
  1394. * Ray from a pointer if availible (eg. 6dof controller)
  1395. */
  1396. _this.ray = null;
  1397. _this.skipOnPointerObservable = false;
  1398. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1399. return _this;
  1400. }
  1401. return PointerInfoPre;
  1402. }(PointerInfoBase));
  1403. BABYLON.PointerInfoPre = PointerInfoPre;
  1404. /**
  1405. * This type contains all the data related to a pointer event in Babylon.js.
  1406. * 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.
  1407. */
  1408. var PointerInfo = /** @class */ (function (_super) {
  1409. __extends(PointerInfo, _super);
  1410. /**
  1411. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1412. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1413. * @param event Defines the related dom event
  1414. * @param pickInfo Defines the picking info associated to the info (if any)\
  1415. */
  1416. function PointerInfo(type, event,
  1417. /**
  1418. * Defines the picking info associated to the info (if any)\
  1419. */
  1420. pickInfo) {
  1421. var _this = _super.call(this, type, event) || this;
  1422. _this.pickInfo = pickInfo;
  1423. return _this;
  1424. }
  1425. return PointerInfo;
  1426. }(PointerInfoBase));
  1427. BABYLON.PointerInfo = PointerInfo;
  1428. })(BABYLON || (BABYLON = {}));
  1429. //# sourceMappingURL=babylon.pointerEvents.js.map
  1430. var BABYLON;
  1431. (function (BABYLON) {
  1432. /**
  1433. * Constant used to convert a value to gamma space
  1434. * @ignorenaming
  1435. */
  1436. BABYLON.ToGammaSpace = 1 / 2.2;
  1437. /**
  1438. * Constant used to convert a value to linear space
  1439. * @ignorenaming
  1440. */
  1441. BABYLON.ToLinearSpace = 2.2;
  1442. /**
  1443. * Constant used to define the minimal number value in Babylon.js
  1444. * @ignorenaming
  1445. */
  1446. BABYLON.Epsilon = 0.001;
  1447. /**
  1448. * Class used to hold a RBG color
  1449. */
  1450. var Color3 = /** @class */ (function () {
  1451. /**
  1452. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1453. * @param r defines the red component (between 0 and 1, default is 0)
  1454. * @param g defines the green component (between 0 and 1, default is 0)
  1455. * @param b defines the blue component (between 0 and 1, default is 0)
  1456. */
  1457. function Color3(
  1458. /**
  1459. * Defines the red component (between 0 and 1, default is 0)
  1460. */
  1461. r,
  1462. /**
  1463. * Defines the green component (between 0 and 1, default is 0)
  1464. */
  1465. g,
  1466. /**
  1467. * Defines the blue component (between 0 and 1, default is 0)
  1468. */
  1469. b) {
  1470. if (r === void 0) { r = 0; }
  1471. if (g === void 0) { g = 0; }
  1472. if (b === void 0) { b = 0; }
  1473. this.r = r;
  1474. this.g = g;
  1475. this.b = b;
  1476. }
  1477. /**
  1478. * Creates a string with the Color3 current values
  1479. * @returns the string representation of the Color3 object
  1480. */
  1481. Color3.prototype.toString = function () {
  1482. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1483. };
  1484. /**
  1485. * Returns the string "Color3"
  1486. * @returns "Color3"
  1487. */
  1488. Color3.prototype.getClassName = function () {
  1489. return "Color3";
  1490. };
  1491. /**
  1492. * Compute the Color3 hash code
  1493. * @returns an unique number that can be used to hash Color3 objects
  1494. */
  1495. Color3.prototype.getHashCode = function () {
  1496. var hash = this.r || 0;
  1497. hash = (hash * 397) ^ (this.g || 0);
  1498. hash = (hash * 397) ^ (this.b || 0);
  1499. return hash;
  1500. };
  1501. // Operators
  1502. /**
  1503. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1504. * @param array defines the array where to store the r,g,b components
  1505. * @param index defines an optional index in the target array to define where to start storing values
  1506. * @returns the current Color3 object
  1507. */
  1508. Color3.prototype.toArray = function (array, index) {
  1509. if (index === undefined) {
  1510. index = 0;
  1511. }
  1512. array[index] = this.r;
  1513. array[index + 1] = this.g;
  1514. array[index + 2] = this.b;
  1515. return this;
  1516. };
  1517. /**
  1518. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1519. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1520. * @returns a new {BABYLON.Color4} object
  1521. */
  1522. Color3.prototype.toColor4 = function (alpha) {
  1523. if (alpha === void 0) { alpha = 1; }
  1524. return new Color4(this.r, this.g, this.b, alpha);
  1525. };
  1526. /**
  1527. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1528. * @returns the new array
  1529. */
  1530. Color3.prototype.asArray = function () {
  1531. var result = new Array();
  1532. this.toArray(result, 0);
  1533. return result;
  1534. };
  1535. /**
  1536. * Returns the luminance value
  1537. * @returns a float value
  1538. */
  1539. Color3.prototype.toLuminance = function () {
  1540. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1541. };
  1542. /**
  1543. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1544. * @param otherColor defines the second operand
  1545. * @returns the new Color3 object
  1546. */
  1547. Color3.prototype.multiply = function (otherColor) {
  1548. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1549. };
  1550. /**
  1551. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1552. * @param otherColor defines the second operand
  1553. * @param result defines the Color3 object where to store the result
  1554. * @returns the current Color3
  1555. */
  1556. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1557. result.r = this.r * otherColor.r;
  1558. result.g = this.g * otherColor.g;
  1559. result.b = this.b * otherColor.b;
  1560. return this;
  1561. };
  1562. /**
  1563. * Determines equality between Color3 objects
  1564. * @param otherColor defines the second operand
  1565. * @returns true if the rgb values are equal to the given ones
  1566. */
  1567. Color3.prototype.equals = function (otherColor) {
  1568. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1569. };
  1570. /**
  1571. * Determines equality between the current Color3 object and a set of r,b,g values
  1572. * @param r defines the red component to check
  1573. * @param g defines the green component to check
  1574. * @param b defines the blue component to check
  1575. * @returns true if the rgb values are equal to the given ones
  1576. */
  1577. Color3.prototype.equalsFloats = function (r, g, b) {
  1578. return this.r === r && this.g === g && this.b === b;
  1579. };
  1580. /**
  1581. * Multiplies in place each rgb value by scale
  1582. * @param scale defines the scaling factor
  1583. * @returns the updated Color3
  1584. */
  1585. Color3.prototype.scale = function (scale) {
  1586. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1587. };
  1588. /**
  1589. * Multiplies the rgb values by scale and stores the result into "result"
  1590. * @param scale defines the scaling factor
  1591. * @param result defines the Color3 object where to store the result
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.scaleToRef = function (scale, result) {
  1595. result.r = this.r * scale;
  1596. result.g = this.g * scale;
  1597. result.b = this.b * scale;
  1598. return this;
  1599. };
  1600. /**
  1601. * Scale the current Color3 values by a factor and add the result to a given Color3
  1602. * @param scale defines the scale factor
  1603. * @param result defines color to store the result into
  1604. * @returns the unmodified current Color3
  1605. */
  1606. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1607. result.r += this.r * scale;
  1608. result.g += this.g * scale;
  1609. result.b += this.b * scale;
  1610. return this;
  1611. };
  1612. /**
  1613. * Clamps the rgb values by the min and max values and stores the result into "result"
  1614. * @param min defines minimum clamping value (default is 0)
  1615. * @param max defines maximum clamping value (default is 1)
  1616. * @param result defines color to store the result into
  1617. * @returns the original Color3
  1618. */
  1619. Color3.prototype.clampToRef = function (min, max, result) {
  1620. if (min === void 0) { min = 0; }
  1621. if (max === void 0) { max = 1; }
  1622. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1623. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1624. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1625. return this;
  1626. };
  1627. /**
  1628. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1629. * @param otherColor defines the second operand
  1630. * @returns the new Color3
  1631. */
  1632. Color3.prototype.add = function (otherColor) {
  1633. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1634. };
  1635. /**
  1636. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1637. * @param otherColor defines the second operand
  1638. * @param result defines Color3 object to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.addToRef = function (otherColor, result) {
  1642. result.r = this.r + otherColor.r;
  1643. result.g = this.g + otherColor.g;
  1644. result.b = this.b + otherColor.b;
  1645. return this;
  1646. };
  1647. /**
  1648. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1649. * @param otherColor defines the second operand
  1650. * @returns the new Color3
  1651. */
  1652. Color3.prototype.subtract = function (otherColor) {
  1653. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1654. };
  1655. /**
  1656. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1657. * @param otherColor defines the second operand
  1658. * @param result defines Color3 object to store the result into
  1659. * @returns the unmodified current Color3
  1660. */
  1661. Color3.prototype.subtractToRef = function (otherColor, result) {
  1662. result.r = this.r - otherColor.r;
  1663. result.g = this.g - otherColor.g;
  1664. result.b = this.b - otherColor.b;
  1665. return this;
  1666. };
  1667. /**
  1668. * Copy the current object
  1669. * @returns a new Color3 copied the current one
  1670. */
  1671. Color3.prototype.clone = function () {
  1672. return new Color3(this.r, this.g, this.b);
  1673. };
  1674. /**
  1675. * Copies the rgb values from the source in the current Color3
  1676. * @param source defines the source Color3 object
  1677. * @returns the updated Color3 object
  1678. */
  1679. Color3.prototype.copyFrom = function (source) {
  1680. this.r = source.r;
  1681. this.g = source.g;
  1682. this.b = source.b;
  1683. return this;
  1684. };
  1685. /**
  1686. * Updates the Color3 rgb values from the given floats
  1687. * @param r defines the red component to read from
  1688. * @param g defines the green component to read from
  1689. * @param b defines the blue component to read from
  1690. * @returns the current Color3 object
  1691. */
  1692. Color3.prototype.copyFromFloats = function (r, g, b) {
  1693. this.r = r;
  1694. this.g = g;
  1695. this.b = b;
  1696. return this;
  1697. };
  1698. /**
  1699. * Updates the Color3 rgb values from the given floats
  1700. * @param r defines the red component to read from
  1701. * @param g defines the green component to read from
  1702. * @param b defines the blue component to read from
  1703. * @returns the current Color3 object
  1704. */
  1705. Color3.prototype.set = function (r, g, b) {
  1706. return this.copyFromFloats(r, g, b);
  1707. };
  1708. /**
  1709. * Compute the Color3 hexadecimal code as a string
  1710. * @returns a string containing the hexadecimal representation of the Color3 object
  1711. */
  1712. Color3.prototype.toHexString = function () {
  1713. var intR = (this.r * 255) | 0;
  1714. var intG = (this.g * 255) | 0;
  1715. var intB = (this.b * 255) | 0;
  1716. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1717. };
  1718. /**
  1719. * Computes a new Color3 converted from the current one to linear space
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.prototype.toLinearSpace = function () {
  1723. var convertedColor = new Color3();
  1724. this.toLinearSpaceToRef(convertedColor);
  1725. return convertedColor;
  1726. };
  1727. /**
  1728. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1729. * @param convertedColor defines the Color3 object where to store the linear space version
  1730. * @returns the unmodified Color3
  1731. */
  1732. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1733. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1734. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1735. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1736. return this;
  1737. };
  1738. /**
  1739. * Computes a new Color3 converted from the current one to gamma space
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.prototype.toGammaSpace = function () {
  1743. var convertedColor = new Color3();
  1744. this.toGammaSpaceToRef(convertedColor);
  1745. return convertedColor;
  1746. };
  1747. /**
  1748. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1749. * @param convertedColor defines the Color3 object where to store the gamma space version
  1750. * @returns the unmodified Color3
  1751. */
  1752. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1753. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1754. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1755. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1756. return this;
  1757. };
  1758. // Statics
  1759. /**
  1760. * Creates a new Color3 from the string containing valid hexadecimal values
  1761. * @param hex defines a string containing valid hexadecimal values
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.FromHexString = function (hex) {
  1765. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1766. return new Color3(0, 0, 0);
  1767. }
  1768. var r = parseInt(hex.substring(1, 3), 16);
  1769. var g = parseInt(hex.substring(3, 5), 16);
  1770. var b = parseInt(hex.substring(5, 7), 16);
  1771. return Color3.FromInts(r, g, b);
  1772. };
  1773. /**
  1774. * Creates a new Vector3 from the starting index of the given array
  1775. * @param array defines the source array
  1776. * @param offset defines an offset in the source array
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.FromArray = function (array, offset) {
  1780. if (offset === void 0) { offset = 0; }
  1781. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1782. };
  1783. /**
  1784. * Creates a new Color3 from integer values (< 256)
  1785. * @param r defines the red component to read from (value between 0 and 255)
  1786. * @param g defines the green component to read from (value between 0 and 255)
  1787. * @param b defines the blue component to read from (value between 0 and 255)
  1788. * @returns a new Color3 object
  1789. */
  1790. Color3.FromInts = function (r, g, b) {
  1791. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1792. };
  1793. /**
  1794. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1795. * @param start defines the start Color3 value
  1796. * @param end defines the end Color3 value
  1797. * @param amount defines the gradient value between start and end
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Lerp = function (start, end, amount) {
  1801. var result = new Color3(0.0, 0.0, 0.0);
  1802. Color3.LerpToRef(start, end, amount, result);
  1803. return result;
  1804. };
  1805. /**
  1806. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1807. * @param left defines the start value
  1808. * @param right defines the end value
  1809. * @param amount defines the gradient factor
  1810. * @param result defines the Color3 object where to store the result
  1811. */
  1812. Color3.LerpToRef = function (left, right, amount, result) {
  1813. result.r = left.r + ((right.r - left.r) * amount);
  1814. result.g = left.g + ((right.g - left.g) * amount);
  1815. result.b = left.b + ((right.b - left.b) * amount);
  1816. };
  1817. /**
  1818. * Returns a Color3 value containing a red color
  1819. * @returns a new Color3 object
  1820. */
  1821. Color3.Red = function () { return new Color3(1, 0, 0); };
  1822. /**
  1823. * Returns a Color3 value containing a green color
  1824. * @returns a new Color3 object
  1825. */
  1826. Color3.Green = function () { return new Color3(0, 1, 0); };
  1827. /**
  1828. * Returns a Color3 value containing a blue color
  1829. * @returns a new Color3 object
  1830. */
  1831. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1832. /**
  1833. * Returns a Color3 value containing a black color
  1834. * @returns a new Color3 object
  1835. */
  1836. Color3.Black = function () { return new Color3(0, 0, 0); };
  1837. /**
  1838. * Returns a Color3 value containing a white color
  1839. * @returns a new Color3 object
  1840. */
  1841. Color3.White = function () { return new Color3(1, 1, 1); };
  1842. /**
  1843. * Returns a Color3 value containing a purple color
  1844. * @returns a new Color3 object
  1845. */
  1846. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1847. /**
  1848. * Returns a Color3 value containing a magenta color
  1849. * @returns a new Color3 object
  1850. */
  1851. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1852. /**
  1853. * Returns a Color3 value containing a yellow color
  1854. * @returns a new Color3 object
  1855. */
  1856. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1857. /**
  1858. * Returns a Color3 value containing a gray color
  1859. * @returns a new Color3 object
  1860. */
  1861. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1862. /**
  1863. * Returns a Color3 value containing a teal color
  1864. * @returns a new Color3 object
  1865. */
  1866. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1867. /**
  1868. * Returns a Color3 value containing a random color
  1869. * @returns a new Color3 object
  1870. */
  1871. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1872. return Color3;
  1873. }());
  1874. BABYLON.Color3 = Color3;
  1875. /**
  1876. * Class used to hold a RBGA color
  1877. */
  1878. var Color4 = /** @class */ (function () {
  1879. /**
  1880. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1881. * @param r defines the red component (between 0 and 1, default is 0)
  1882. * @param g defines the green component (between 0 and 1, default is 0)
  1883. * @param b defines the blue component (between 0 and 1, default is 0)
  1884. * @param a defines the alpha component (between 0 and 1, default is 1)
  1885. */
  1886. function Color4(
  1887. /**
  1888. * Defines the red component (between 0 and 1, default is 0)
  1889. */
  1890. r,
  1891. /**
  1892. * Defines the green component (between 0 and 1, default is 0)
  1893. */
  1894. g,
  1895. /**
  1896. * Defines the blue component (between 0 and 1, default is 0)
  1897. */
  1898. b,
  1899. /**
  1900. * Defines the alpha component (between 0 and 1, default is 1)
  1901. */
  1902. a) {
  1903. if (r === void 0) { r = 0; }
  1904. if (g === void 0) { g = 0; }
  1905. if (b === void 0) { b = 0; }
  1906. if (a === void 0) { a = 1; }
  1907. this.r = r;
  1908. this.g = g;
  1909. this.b = b;
  1910. this.a = a;
  1911. }
  1912. // Operators
  1913. /**
  1914. * Adds in place the given Color4 values to the current Color4 object
  1915. * @param right defines the second operand
  1916. * @returns the current updated Color4 object
  1917. */
  1918. Color4.prototype.addInPlace = function (right) {
  1919. this.r += right.r;
  1920. this.g += right.g;
  1921. this.b += right.b;
  1922. this.a += right.a;
  1923. return this;
  1924. };
  1925. /**
  1926. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1927. * @returns the new array
  1928. */
  1929. Color4.prototype.asArray = function () {
  1930. var result = new Array();
  1931. this.toArray(result, 0);
  1932. return result;
  1933. };
  1934. /**
  1935. * Stores from the starting index in the given array the Color4 successive values
  1936. * @param array defines the array where to store the r,g,b components
  1937. * @param index defines an optional index in the target array to define where to start storing values
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.toArray = function (array, index) {
  1941. if (index === undefined) {
  1942. index = 0;
  1943. }
  1944. array[index] = this.r;
  1945. array[index + 1] = this.g;
  1946. array[index + 2] = this.b;
  1947. array[index + 3] = this.a;
  1948. return this;
  1949. };
  1950. /**
  1951. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1952. * @param right defines the second operand
  1953. * @returns a new Color4 object
  1954. */
  1955. Color4.prototype.add = function (right) {
  1956. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1957. };
  1958. /**
  1959. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1960. * @param right defines the second operand
  1961. * @returns a new Color4 object
  1962. */
  1963. Color4.prototype.subtract = function (right) {
  1964. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1965. };
  1966. /**
  1967. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1968. * @param right defines the second operand
  1969. * @param result defines the Color4 object where to store the result
  1970. * @returns the current Color4 object
  1971. */
  1972. Color4.prototype.subtractToRef = function (right, result) {
  1973. result.r = this.r - right.r;
  1974. result.g = this.g - right.g;
  1975. result.b = this.b - right.b;
  1976. result.a = this.a - right.a;
  1977. return this;
  1978. };
  1979. /**
  1980. * Creates a new Color4 with the current Color4 values multiplied by scale
  1981. * @param scale defines the scaling factor to apply
  1982. * @returns a new Color4 object
  1983. */
  1984. Color4.prototype.scale = function (scale) {
  1985. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1986. };
  1987. /**
  1988. * Multiplies the current Color4 values by scale and stores the result in "result"
  1989. * @param scale defines the scaling factor to apply
  1990. * @param result defines the Color4 object where to store the result
  1991. * @returns the current unmodified Color4
  1992. */
  1993. Color4.prototype.scaleToRef = function (scale, result) {
  1994. result.r = this.r * scale;
  1995. result.g = this.g * scale;
  1996. result.b = this.b * scale;
  1997. result.a = this.a * scale;
  1998. return this;
  1999. };
  2000. /**
  2001. * Scale the current Color4 values by a factor and add the result to a given Color4
  2002. * @param scale defines the scale factor
  2003. * @param result defines the Color4 object where to store the result
  2004. * @returns the unmodified current Color4
  2005. */
  2006. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2007. result.r += this.r * scale;
  2008. result.g += this.g * scale;
  2009. result.b += this.b * scale;
  2010. result.a += this.a * scale;
  2011. return this;
  2012. };
  2013. /**
  2014. * Clamps the rgb values by the min and max values and stores the result into "result"
  2015. * @param min defines minimum clamping value (default is 0)
  2016. * @param max defines maximum clamping value (default is 1)
  2017. * @param result defines color to store the result into.
  2018. * @returns the cuurent Color4
  2019. */
  2020. Color4.prototype.clampToRef = function (min, max, result) {
  2021. if (min === void 0) { min = 0; }
  2022. if (max === void 0) { max = 1; }
  2023. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2024. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2025. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2026. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2027. return this;
  2028. };
  2029. /**
  2030. * Multipy an Color4 value by another and return a new Color4 object
  2031. * @param color defines the Color4 value to multiply by
  2032. * @returns a new Color4 object
  2033. */
  2034. Color4.prototype.multiply = function (color) {
  2035. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2036. };
  2037. /**
  2038. * Multipy a Color4 value by another and push the result in a reference value
  2039. * @param color defines the Color4 value to multiply by
  2040. * @param result defines the Color4 to fill the result in
  2041. * @returns the result Color4
  2042. */
  2043. Color4.prototype.multiplyToRef = function (color, result) {
  2044. result.r = this.r * color.r;
  2045. result.g = this.g * color.g;
  2046. result.b = this.b * color.b;
  2047. result.a = this.a * color.a;
  2048. return result;
  2049. };
  2050. /**
  2051. * Creates a string with the Color4 current values
  2052. * @returns the string representation of the Color4 object
  2053. */
  2054. Color4.prototype.toString = function () {
  2055. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2056. };
  2057. /**
  2058. * Returns the string "Color4"
  2059. * @returns "Color4"
  2060. */
  2061. Color4.prototype.getClassName = function () {
  2062. return "Color4";
  2063. };
  2064. /**
  2065. * Compute the Color4 hash code
  2066. * @returns an unique number that can be used to hash Color4 objects
  2067. */
  2068. Color4.prototype.getHashCode = function () {
  2069. var hash = this.r || 0;
  2070. hash = (hash * 397) ^ (this.g || 0);
  2071. hash = (hash * 397) ^ (this.b || 0);
  2072. hash = (hash * 397) ^ (this.a || 0);
  2073. return hash;
  2074. };
  2075. /**
  2076. * Creates a new Color4 copied from the current one
  2077. * @returns a new Color4 object
  2078. */
  2079. Color4.prototype.clone = function () {
  2080. return new Color4(this.r, this.g, this.b, this.a);
  2081. };
  2082. /**
  2083. * Copies the given Color4 values into the current one
  2084. * @param source defines the source Color4 object
  2085. * @returns the current updated Color4 object
  2086. */
  2087. Color4.prototype.copyFrom = function (source) {
  2088. this.r = source.r;
  2089. this.g = source.g;
  2090. this.b = source.b;
  2091. this.a = source.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Copies the given float values into the current one
  2096. * @param r defines the red component to read from
  2097. * @param g defines the green component to read from
  2098. * @param b defines the blue component to read from
  2099. * @param a defines the alpha component to read from
  2100. * @returns the current updated Color4 object
  2101. */
  2102. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2103. this.r = r;
  2104. this.g = g;
  2105. this.b = b;
  2106. this.a = a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Copies the given float values into the current one
  2111. * @param r defines the red component to read from
  2112. * @param g defines the green component to read from
  2113. * @param b defines the blue component to read from
  2114. * @param a defines the alpha component to read from
  2115. * @returns the current updated Color4 object
  2116. */
  2117. Color4.prototype.set = function (r, g, b, a) {
  2118. return this.copyFromFloats(r, g, b, a);
  2119. };
  2120. /**
  2121. * Compute the Color4 hexadecimal code as a string
  2122. * @returns a string containing the hexadecimal representation of the Color4 object
  2123. */
  2124. Color4.prototype.toHexString = function () {
  2125. var intR = (this.r * 255) | 0;
  2126. var intG = (this.g * 255) | 0;
  2127. var intB = (this.b * 255) | 0;
  2128. var intA = (this.a * 255) | 0;
  2129. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2130. };
  2131. /**
  2132. * Computes a new Color4 converted from the current one to linear space
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.prototype.toLinearSpace = function () {
  2136. var convertedColor = new Color4();
  2137. this.toLinearSpaceToRef(convertedColor);
  2138. return convertedColor;
  2139. };
  2140. /**
  2141. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2142. * @param convertedColor defines the Color4 object where to store the linear space version
  2143. * @returns the unmodified Color4
  2144. */
  2145. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2146. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2147. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2148. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2149. convertedColor.a = this.a;
  2150. return this;
  2151. };
  2152. /**
  2153. * Computes a new Color4 converted from the current one to gamma space
  2154. * @returns a new Color4 object
  2155. */
  2156. Color4.prototype.toGammaSpace = function () {
  2157. var convertedColor = new Color4();
  2158. this.toGammaSpaceToRef(convertedColor);
  2159. return convertedColor;
  2160. };
  2161. /**
  2162. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2163. * @param convertedColor defines the Color4 object where to store the gamma space version
  2164. * @returns the unmodified Color4
  2165. */
  2166. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2167. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2168. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2169. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2170. convertedColor.a = this.a;
  2171. return this;
  2172. };
  2173. // Statics
  2174. /**
  2175. * Creates a new Color4 from the string containing valid hexadecimal values
  2176. * @param hex defines a string containing valid hexadecimal values
  2177. * @returns a new Color4 object
  2178. */
  2179. Color4.FromHexString = function (hex) {
  2180. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2181. return new Color4(0.0, 0.0, 0.0, 0.0);
  2182. }
  2183. var r = parseInt(hex.substring(1, 3), 16);
  2184. var g = parseInt(hex.substring(3, 5), 16);
  2185. var b = parseInt(hex.substring(5, 7), 16);
  2186. var a = parseInt(hex.substring(7, 9), 16);
  2187. return Color4.FromInts(r, g, b, a);
  2188. };
  2189. /**
  2190. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2191. * @param left defines the start value
  2192. * @param right defines the end value
  2193. * @param amount defines the gradient factor
  2194. * @returns a new Color4 object
  2195. */
  2196. Color4.Lerp = function (left, right, amount) {
  2197. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2198. Color4.LerpToRef(left, right, amount, result);
  2199. return result;
  2200. };
  2201. /**
  2202. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2203. * @param left defines the start value
  2204. * @param right defines the end value
  2205. * @param amount defines the gradient factor
  2206. * @param result defines the Color4 object where to store data
  2207. */
  2208. Color4.LerpToRef = function (left, right, amount, result) {
  2209. result.r = left.r + (right.r - left.r) * amount;
  2210. result.g = left.g + (right.g - left.g) * amount;
  2211. result.b = left.b + (right.b - left.b) * amount;
  2212. result.a = left.a + (right.a - left.a) * amount;
  2213. };
  2214. /**
  2215. * Creates a new Color4 from a Color3 and an alpha value
  2216. * @param color3 defines the source Color3 to read from
  2217. * @param alpha defines the alpha component (1.0 by default)
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.FromColor3 = function (color3, alpha) {
  2221. if (alpha === void 0) { alpha = 1.0; }
  2222. return new Color4(color3.r, color3.g, color3.b, alpha);
  2223. };
  2224. /**
  2225. * Creates a new Color4 from the starting index element of the given array
  2226. * @param array defines the source array to read from
  2227. * @param offset defines the offset in the source array
  2228. * @returns a new Color4 object
  2229. */
  2230. Color4.FromArray = function (array, offset) {
  2231. if (offset === void 0) { offset = 0; }
  2232. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2233. };
  2234. /**
  2235. * Creates a new Color3 from integer values (< 256)
  2236. * @param r defines the red component to read from (value between 0 and 255)
  2237. * @param g defines the green component to read from (value between 0 and 255)
  2238. * @param b defines the blue component to read from (value between 0 and 255)
  2239. * @param a defines the alpha component to read from (value between 0 and 255)
  2240. * @returns a new Color3 object
  2241. */
  2242. Color4.FromInts = function (r, g, b, a) {
  2243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2244. };
  2245. /**
  2246. * Check the content of a given array and convert it to an array containing RGBA data
  2247. * If the original array was already containing count * 4 values then it is returned directly
  2248. * @param colors defines the array to check
  2249. * @param count defines the number of RGBA data to expect
  2250. * @returns an array containing count * 4 values (RGBA)
  2251. */
  2252. Color4.CheckColors4 = function (colors, count) {
  2253. // Check if color3 was used
  2254. if (colors.length === count * 3) {
  2255. var colors4 = [];
  2256. for (var index = 0; index < colors.length; index += 3) {
  2257. var newIndex = (index / 3) * 4;
  2258. colors4[newIndex] = colors[index];
  2259. colors4[newIndex + 1] = colors[index + 1];
  2260. colors4[newIndex + 2] = colors[index + 2];
  2261. colors4[newIndex + 3] = 1.0;
  2262. }
  2263. return colors4;
  2264. }
  2265. return colors;
  2266. };
  2267. return Color4;
  2268. }());
  2269. BABYLON.Color4 = Color4;
  2270. /**
  2271. * Class representing a vector containing 2 coordinates
  2272. */
  2273. var Vector2 = /** @class */ (function () {
  2274. /**
  2275. * Creates a new Vector2 from the given x and y coordinates
  2276. * @param x defines the first coordinate
  2277. * @param y defines the second coordinate
  2278. */
  2279. function Vector2(
  2280. /** defines the first coordinate */
  2281. x,
  2282. /** defines the second coordinate */
  2283. y) {
  2284. if (x === void 0) { x = 0; }
  2285. if (y === void 0) { y = 0; }
  2286. this.x = x;
  2287. this.y = y;
  2288. }
  2289. /**
  2290. * Gets a string with the Vector2 coordinates
  2291. * @returns a string with the Vector2 coordinates
  2292. */
  2293. Vector2.prototype.toString = function () {
  2294. return "{X: " + this.x + " Y:" + this.y + "}";
  2295. };
  2296. /**
  2297. * Gets class name
  2298. * @returns the string "Vector2"
  2299. */
  2300. Vector2.prototype.getClassName = function () {
  2301. return "Vector2";
  2302. };
  2303. /**
  2304. * Gets current vector hash code
  2305. * @returns the Vector2 hash code as a number
  2306. */
  2307. Vector2.prototype.getHashCode = function () {
  2308. var hash = this.x || 0;
  2309. hash = (hash * 397) ^ (this.y || 0);
  2310. return hash;
  2311. };
  2312. // Operators
  2313. /**
  2314. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2315. * @param array defines the source array
  2316. * @param index defines the offset in source array
  2317. * @returns the current Vector2
  2318. */
  2319. Vector2.prototype.toArray = function (array, index) {
  2320. if (index === void 0) { index = 0; }
  2321. array[index] = this.x;
  2322. array[index + 1] = this.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Copy the current vector to an array
  2327. * @returns a new array with 2 elements: the Vector2 coordinates.
  2328. */
  2329. Vector2.prototype.asArray = function () {
  2330. var result = new Array();
  2331. this.toArray(result, 0);
  2332. return result;
  2333. };
  2334. /**
  2335. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2336. * @param source defines the source Vector2
  2337. * @returns the current updated Vector2
  2338. */
  2339. Vector2.prototype.copyFrom = function (source) {
  2340. this.x = source.x;
  2341. this.y = source.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Sets the Vector2 coordinates with the given floats
  2346. * @param x defines the first coordinate
  2347. * @param y defines the second coordinate
  2348. * @returns the current updated Vector2
  2349. */
  2350. Vector2.prototype.copyFromFloats = function (x, y) {
  2351. this.x = x;
  2352. this.y = y;
  2353. return this;
  2354. };
  2355. /**
  2356. * Sets the Vector2 coordinates with the given floats
  2357. * @param x defines the first coordinate
  2358. * @param y defines the second coordinate
  2359. * @returns the current updated Vector2
  2360. */
  2361. Vector2.prototype.set = function (x, y) {
  2362. return this.copyFromFloats(x, y);
  2363. };
  2364. /**
  2365. * Add another vector with the current one
  2366. * @param otherVector defines the other vector
  2367. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2368. */
  2369. Vector2.prototype.add = function (otherVector) {
  2370. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2371. };
  2372. /**
  2373. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @param result defines the target vector
  2376. * @returns the unmodified current Vector2
  2377. */
  2378. Vector2.prototype.addToRef = function (otherVector, result) {
  2379. result.x = this.x + otherVector.x;
  2380. result.y = this.y + otherVector.y;
  2381. return this;
  2382. };
  2383. /**
  2384. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2385. * @param otherVector defines the other vector
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.addInPlace = function (otherVector) {
  2389. this.x += otherVector.x;
  2390. this.y += otherVector.y;
  2391. return this;
  2392. };
  2393. /**
  2394. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2395. * @param otherVector defines the other vector
  2396. * @returns a new Vector2
  2397. */
  2398. Vector2.prototype.addVector3 = function (otherVector) {
  2399. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2400. };
  2401. /**
  2402. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2403. * @param otherVector defines the other vector
  2404. * @returns a new Vector2
  2405. */
  2406. Vector2.prototype.subtract = function (otherVector) {
  2407. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2408. };
  2409. /**
  2410. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2411. * @param otherVector defines the other vector
  2412. * @param result defines the target vector
  2413. * @returns the unmodified current Vector2
  2414. */
  2415. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2416. result.x = this.x - otherVector.x;
  2417. result.y = this.y - otherVector.y;
  2418. return this;
  2419. };
  2420. /**
  2421. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns the current updated Vector2
  2424. */
  2425. Vector2.prototype.subtractInPlace = function (otherVector) {
  2426. this.x -= otherVector.x;
  2427. this.y -= otherVector.y;
  2428. return this;
  2429. };
  2430. /**
  2431. * Multiplies in place the current Vector2 coordinates by the given ones
  2432. * @param otherVector defines the other vector
  2433. * @returns the current updated Vector2
  2434. */
  2435. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2436. this.x *= otherVector.x;
  2437. this.y *= otherVector.y;
  2438. return this;
  2439. };
  2440. /**
  2441. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2442. * @param otherVector defines the other vector
  2443. * @returns a new Vector2
  2444. */
  2445. Vector2.prototype.multiply = function (otherVector) {
  2446. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2447. };
  2448. /**
  2449. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2450. * @param otherVector defines the other vector
  2451. * @param result defines the target vector
  2452. * @returns the unmodified current Vector2
  2453. */
  2454. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2455. result.x = this.x * otherVector.x;
  2456. result.y = this.y * otherVector.y;
  2457. return this;
  2458. };
  2459. /**
  2460. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2461. * @param x defines the first coordinate
  2462. * @param y defines the second coordinate
  2463. * @returns a new Vector2
  2464. */
  2465. Vector2.prototype.multiplyByFloats = function (x, y) {
  2466. return new Vector2(this.x * x, this.y * y);
  2467. };
  2468. /**
  2469. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2470. * @param otherVector defines the other vector
  2471. * @returns a new Vector2
  2472. */
  2473. Vector2.prototype.divide = function (otherVector) {
  2474. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2475. };
  2476. /**
  2477. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2478. * @param otherVector defines the other vector
  2479. * @param result defines the target vector
  2480. * @returns the unmodified current Vector2
  2481. */
  2482. Vector2.prototype.divideToRef = function (otherVector, result) {
  2483. result.x = this.x / otherVector.x;
  2484. result.y = this.y / otherVector.y;
  2485. return this;
  2486. };
  2487. /**
  2488. * Divides the current Vector2 coordinates by the given ones
  2489. * @param otherVector defines the other vector
  2490. * @returns the current updated Vector2
  2491. */
  2492. Vector2.prototype.divideInPlace = function (otherVector) {
  2493. return this.divideToRef(otherVector, this);
  2494. };
  2495. /**
  2496. * Gets a new Vector2 with current Vector2 negated coordinates
  2497. * @returns a new Vector2
  2498. */
  2499. Vector2.prototype.negate = function () {
  2500. return new Vector2(-this.x, -this.y);
  2501. };
  2502. /**
  2503. * Multiply the Vector2 coordinates by scale
  2504. * @param scale defines the scaling factor
  2505. * @returns the current updated Vector2
  2506. */
  2507. Vector2.prototype.scaleInPlace = function (scale) {
  2508. this.x *= scale;
  2509. this.y *= scale;
  2510. return this;
  2511. };
  2512. /**
  2513. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2514. * @param scale defines the scaling factor
  2515. * @returns a new Vector2
  2516. */
  2517. Vector2.prototype.scale = function (scale) {
  2518. var result = new Vector2(0, 0);
  2519. this.scaleToRef(scale, result);
  2520. return result;
  2521. };
  2522. /**
  2523. * Scale the current Vector2 values by a factor to a given Vector2
  2524. * @param scale defines the scale factor
  2525. * @param result defines the Vector2 object where to store the result
  2526. * @returns the unmodified current Vector2
  2527. */
  2528. Vector2.prototype.scaleToRef = function (scale, result) {
  2529. result.x = this.x * scale;
  2530. result.y = this.y * scale;
  2531. return this;
  2532. };
  2533. /**
  2534. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2535. * @param scale defines the scale factor
  2536. * @param result defines the Vector2 object where to store the result
  2537. * @returns the unmodified current Vector2
  2538. */
  2539. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2540. result.x += this.x * scale;
  2541. result.y += this.y * scale;
  2542. return this;
  2543. };
  2544. /**
  2545. * Gets a boolean if two vectors are equals
  2546. * @param otherVector defines the other vector
  2547. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2548. */
  2549. Vector2.prototype.equals = function (otherVector) {
  2550. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2551. };
  2552. /**
  2553. * Gets a boolean if two vectors are equals (using an epsilon value)
  2554. * @param otherVector defines the other vector
  2555. * @param epsilon defines the minimal distance to consider equality
  2556. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2557. */
  2558. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2559. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2560. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2561. };
  2562. /**
  2563. * Gets a new Vector2 from current Vector2 floored values
  2564. * @returns a new Vector2
  2565. */
  2566. Vector2.prototype.floor = function () {
  2567. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2568. };
  2569. /**
  2570. * Gets a new Vector2 from current Vector2 floored values
  2571. * @returns a new Vector2
  2572. */
  2573. Vector2.prototype.fract = function () {
  2574. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2575. };
  2576. // Properties
  2577. /**
  2578. * Gets the length of the vector
  2579. * @returns the vector length (float)
  2580. */
  2581. Vector2.prototype.length = function () {
  2582. return Math.sqrt(this.x * this.x + this.y * this.y);
  2583. };
  2584. /**
  2585. * Gets the vector squared length
  2586. * @returns the vector squared length (float)
  2587. */
  2588. Vector2.prototype.lengthSquared = function () {
  2589. return (this.x * this.x + this.y * this.y);
  2590. };
  2591. // Methods
  2592. /**
  2593. * Normalize the vector
  2594. * @returns the current updated Vector2
  2595. */
  2596. Vector2.prototype.normalize = function () {
  2597. var len = this.length();
  2598. if (len === 0)
  2599. return this;
  2600. var num = 1.0 / len;
  2601. this.x *= num;
  2602. this.y *= num;
  2603. return this;
  2604. };
  2605. /**
  2606. * Gets a new Vector2 copied from the Vector2
  2607. * @returns a new Vector2
  2608. */
  2609. Vector2.prototype.clone = function () {
  2610. return new Vector2(this.x, this.y);
  2611. };
  2612. // Statics
  2613. /**
  2614. * Gets a new Vector2(0, 0)
  2615. * @returns a new Vector2
  2616. */
  2617. Vector2.Zero = function () {
  2618. return new Vector2(0, 0);
  2619. };
  2620. /**
  2621. * Gets a new Vector2(1, 1)
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.One = function () {
  2625. return new Vector2(1, 1);
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set from the given index element of the given array
  2629. * @param array defines the data source
  2630. * @param offset defines the offset in the data source
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.FromArray = function (array, offset) {
  2634. if (offset === void 0) { offset = 0; }
  2635. return new Vector2(array[offset], array[offset + 1]);
  2636. };
  2637. /**
  2638. * Sets "result" from the given index element of the given array
  2639. * @param array defines the data source
  2640. * @param offset defines the offset in the data source
  2641. * @param result defines the target vector
  2642. */
  2643. Vector2.FromArrayToRef = function (array, offset, result) {
  2644. result.x = array[offset];
  2645. result.y = array[offset + 1];
  2646. };
  2647. /**
  2648. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2649. * @param value1 defines 1st point of control
  2650. * @param value2 defines 2nd point of control
  2651. * @param value3 defines 3rd point of control
  2652. * @param value4 defines 4th point of control
  2653. * @param amount defines the interpolation factor
  2654. * @returns a new Vector2
  2655. */
  2656. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2657. var squared = amount * amount;
  2658. var cubed = amount * squared;
  2659. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2660. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2661. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2662. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2663. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2664. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * 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".
  2669. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2670. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2671. * @param value defines the value to clamp
  2672. * @param min defines the lower limit
  2673. * @param max defines the upper limit
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Clamp = function (value, min, max) {
  2677. var x = value.x;
  2678. x = (x > max.x) ? max.x : x;
  2679. x = (x < min.x) ? min.x : x;
  2680. var y = value.y;
  2681. y = (y > max.y) ? max.y : y;
  2682. y = (y < min.y) ? min.y : y;
  2683. return new Vector2(x, y);
  2684. };
  2685. /**
  2686. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2687. * @param value1 defines the 1st control point
  2688. * @param tangent1 defines the outgoing tangent
  2689. * @param value2 defines the 2nd control point
  2690. * @param tangent2 defines the incoming tangent
  2691. * @param amount defines the interpolation factor
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2695. var squared = amount * amount;
  2696. var cubed = amount * squared;
  2697. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2698. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2699. var part3 = (cubed - (2.0 * squared)) + amount;
  2700. var part4 = cubed - squared;
  2701. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2702. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2707. * @param start defines the start vector
  2708. * @param end defines the end vector
  2709. * @param amount defines the interpolation factor
  2710. * @returns a new Vector2
  2711. */
  2712. Vector2.Lerp = function (start, end, amount) {
  2713. var x = start.x + ((end.x - start.x) * amount);
  2714. var y = start.y + ((end.y - start.y) * amount);
  2715. return new Vector2(x, y);
  2716. };
  2717. /**
  2718. * Gets the dot product of the vector "left" and the vector "right"
  2719. * @param left defines first vector
  2720. * @param right defines second vector
  2721. * @returns the dot product (float)
  2722. */
  2723. Vector2.Dot = function (left, right) {
  2724. return left.x * right.x + left.y * right.y;
  2725. };
  2726. /**
  2727. * Returns a new Vector2 equal to the normalized given vector
  2728. * @param vector defines the vector to normalize
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Normalize = function (vector) {
  2732. var newVector = vector.clone();
  2733. newVector.normalize();
  2734. return newVector;
  2735. };
  2736. /**
  2737. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2738. * @param left defines 1st vector
  2739. * @param right defines 2nd vector
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Minimize = function (left, right) {
  2743. var x = (left.x < right.x) ? left.x : right.x;
  2744. var y = (left.y < right.y) ? left.y : right.y;
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2749. * @param left defines 1st vector
  2750. * @param right defines 2nd vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Maximize = function (left, right) {
  2754. var x = (left.x > right.x) ? left.x : right.x;
  2755. var y = (left.y > right.y) ? left.y : right.y;
  2756. return new Vector2(x, y);
  2757. };
  2758. /**
  2759. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2760. * @param vector defines the vector to transform
  2761. * @param transformation defines the matrix to apply
  2762. * @returns a new Vector2
  2763. */
  2764. Vector2.Transform = function (vector, transformation) {
  2765. var r = Vector2.Zero();
  2766. Vector2.TransformToRef(vector, transformation, r);
  2767. return r;
  2768. };
  2769. /**
  2770. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2771. * @param vector defines the vector to transform
  2772. * @param transformation defines the matrix to apply
  2773. * @param result defines the target vector
  2774. */
  2775. Vector2.TransformToRef = function (vector, transformation, result) {
  2776. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2777. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2778. result.x = x;
  2779. result.y = y;
  2780. };
  2781. /**
  2782. * Determines if a given vector is included in a triangle
  2783. * @param p defines the vector to test
  2784. * @param p0 defines 1st triangle point
  2785. * @param p1 defines 2nd triangle point
  2786. * @param p2 defines 3rd triangle point
  2787. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2788. */
  2789. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2790. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2791. var sign = a < 0 ? -1 : 1;
  2792. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2793. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2794. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2795. };
  2796. /**
  2797. * Gets the distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the distance between vectors
  2801. */
  2802. Vector2.Distance = function (value1, value2) {
  2803. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2804. };
  2805. /**
  2806. * Returns the squared distance between the vectors "value1" and "value2"
  2807. * @param value1 defines first vector
  2808. * @param value2 defines second vector
  2809. * @returns the squared distance between vectors
  2810. */
  2811. Vector2.DistanceSquared = function (value1, value2) {
  2812. var x = value1.x - value2.x;
  2813. var y = value1.y - value2.y;
  2814. return (x * x) + (y * y);
  2815. };
  2816. /**
  2817. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2818. * @param value1 defines first vector
  2819. * @param value2 defines second vector
  2820. * @returns a new Vector2
  2821. */
  2822. Vector2.Center = function (value1, value2) {
  2823. var center = value1.add(value2);
  2824. center.scaleInPlace(0.5);
  2825. return center;
  2826. };
  2827. /**
  2828. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2829. * @param p defines the middle point
  2830. * @param segA defines one point of the segment
  2831. * @param segB defines the other point of the segment
  2832. * @returns the shortest distance
  2833. */
  2834. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2835. var l2 = Vector2.DistanceSquared(segA, segB);
  2836. if (l2 === 0.0) {
  2837. return Vector2.Distance(p, segA);
  2838. }
  2839. var v = segB.subtract(segA);
  2840. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2841. var proj = segA.add(v.multiplyByFloats(t, t));
  2842. return Vector2.Distance(p, proj);
  2843. };
  2844. return Vector2;
  2845. }());
  2846. BABYLON.Vector2 = Vector2;
  2847. /**
  2848. * Classed used to store (x,y,z) vector representation
  2849. * A Vector3 is the main object used in 3D geometry
  2850. * It can represent etiher the coordinates of a point the space, either a direction
  2851. * Reminder: Babylon.js uses a left handed forward facing system
  2852. */
  2853. var Vector3 = /** @class */ (function () {
  2854. /**
  2855. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2856. * @param x defines the first coordinates (on X axis)
  2857. * @param y defines the second coordinates (on Y axis)
  2858. * @param z defines the third coordinates (on Z axis)
  2859. */
  2860. function Vector3(
  2861. /**
  2862. * Defines the first coordinates (on X axis)
  2863. */
  2864. x,
  2865. /**
  2866. * Defines the second coordinates (on Y axis)
  2867. */
  2868. y,
  2869. /**
  2870. * Defines the third coordinates (on Z axis)
  2871. */
  2872. z) {
  2873. if (x === void 0) { x = 0; }
  2874. if (y === void 0) { y = 0; }
  2875. if (z === void 0) { z = 0; }
  2876. this.x = x;
  2877. this.y = y;
  2878. this.z = z;
  2879. }
  2880. /**
  2881. * Creates a string representation of the Vector3
  2882. * @returns a string with the Vector3 coordinates.
  2883. */
  2884. Vector3.prototype.toString = function () {
  2885. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2886. };
  2887. /**
  2888. * Gets the class name
  2889. * @returns the string "Vector3"
  2890. */
  2891. Vector3.prototype.getClassName = function () {
  2892. return "Vector3";
  2893. };
  2894. /**
  2895. * Creates the Vector3 hash code
  2896. * @returns a number which tends to be unique between Vector3 instances
  2897. */
  2898. Vector3.prototype.getHashCode = function () {
  2899. var hash = this.x || 0;
  2900. hash = (hash * 397) ^ (this.y || 0);
  2901. hash = (hash * 397) ^ (this.z || 0);
  2902. return hash;
  2903. };
  2904. // Operators
  2905. /**
  2906. * Creates an array containing three elements : the coordinates of the Vector3
  2907. * @returns a new array of numbers
  2908. */
  2909. Vector3.prototype.asArray = function () {
  2910. var result = [];
  2911. this.toArray(result, 0);
  2912. return result;
  2913. };
  2914. /**
  2915. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2916. * @param array defines the destination array
  2917. * @param index defines the offset in the destination array
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.toArray = function (array, index) {
  2921. if (index === void 0) { index = 0; }
  2922. array[index] = this.x;
  2923. array[index + 1] = this.y;
  2924. array[index + 2] = this.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2929. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2930. */
  2931. Vector3.prototype.toQuaternion = function () {
  2932. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2933. };
  2934. /**
  2935. * Adds the given vector to the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.addInPlace = function (otherVector) {
  2940. this.x += otherVector.x;
  2941. this.y += otherVector.y;
  2942. this.z += otherVector.z;
  2943. return this;
  2944. };
  2945. /**
  2946. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2947. * @param otherVector defines the second operand
  2948. * @returns the resulting Vector3
  2949. */
  2950. Vector3.prototype.add = function (otherVector) {
  2951. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2952. };
  2953. /**
  2954. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2955. * @param otherVector defines the second operand
  2956. * @param result defines the Vector3 object where to store the result
  2957. * @returns the current Vector3
  2958. */
  2959. Vector3.prototype.addToRef = function (otherVector, result) {
  2960. result.x = this.x + otherVector.x;
  2961. result.y = this.y + otherVector.y;
  2962. result.z = this.z + otherVector.z;
  2963. return this;
  2964. };
  2965. /**
  2966. * Subtract the given vector from the current Vector3
  2967. * @param otherVector defines the second operand
  2968. * @returns the current updated Vector3
  2969. */
  2970. Vector3.prototype.subtractInPlace = function (otherVector) {
  2971. this.x -= otherVector.x;
  2972. this.y -= otherVector.y;
  2973. this.z -= otherVector.z;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2978. * @param otherVector defines the second operand
  2979. * @returns the resulting Vector3
  2980. */
  2981. Vector3.prototype.subtract = function (otherVector) {
  2982. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2983. };
  2984. /**
  2985. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2986. * @param otherVector defines the second operand
  2987. * @param result defines the Vector3 object where to store the result
  2988. * @returns the current Vector3
  2989. */
  2990. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2991. result.x = this.x - otherVector.x;
  2992. result.y = this.y - otherVector.y;
  2993. result.z = this.z - otherVector.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the resulting Vector3
  3002. */
  3003. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3004. return new Vector3(this.x - x, this.y - y, this.z - z);
  3005. };
  3006. /**
  3007. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3015. result.x = this.x - x;
  3016. result.y = this.y - y;
  3017. result.z = this.z - z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3022. * @returns a new Vector3
  3023. */
  3024. Vector3.prototype.negate = function () {
  3025. return new Vector3(-this.x, -this.y, -this.z);
  3026. };
  3027. /**
  3028. * Multiplies the Vector3 coordinates by the float "scale"
  3029. * @param scale defines the multiplier factor
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.scaleInPlace = function (scale) {
  3033. this.x *= scale;
  3034. this.y *= scale;
  3035. this.z *= scale;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3040. * @param scale defines the multiplier factor
  3041. * @returns a new Vector3
  3042. */
  3043. Vector3.prototype.scale = function (scale) {
  3044. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3045. };
  3046. /**
  3047. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3048. * @param scale defines the multiplier factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the current Vector3
  3051. */
  3052. Vector3.prototype.scaleToRef = function (scale, result) {
  3053. result.x = this.x * scale;
  3054. result.y = this.y * scale;
  3055. result.z = this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3060. * @param scale defines the scale factor
  3061. * @param result defines the Vector3 object where to store the result
  3062. * @returns the unmodified current Vector3
  3063. */
  3064. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3065. result.x += this.x * scale;
  3066. result.y += this.y * scale;
  3067. result.z += this.z * scale;
  3068. return this;
  3069. };
  3070. /**
  3071. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3072. * @param otherVector defines the second operand
  3073. * @returns true if both vectors are equals
  3074. */
  3075. Vector3.prototype.equals = function (otherVector) {
  3076. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3077. };
  3078. /**
  3079. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3080. * @param otherVector defines the second operand
  3081. * @param epsilon defines the minimal distance to define values as equals
  3082. * @returns true if both vectors are distant less than epsilon
  3083. */
  3084. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3085. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3086. 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);
  3087. };
  3088. /**
  3089. * Returns true if the current Vector3 coordinates equals the given floats
  3090. * @param x defines the x coordinate of the operand
  3091. * @param y defines the y coordinate of the operand
  3092. * @param z defines the z coordinate of the operand
  3093. * @returns true if both vectors are equals
  3094. */
  3095. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3096. return this.x === x && this.y === y && this.z === z;
  3097. };
  3098. /**
  3099. * Multiplies the current Vector3 coordinates by the given ones
  3100. * @param otherVector defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3104. this.x *= otherVector.x;
  3105. this.y *= otherVector.y;
  3106. this.z *= otherVector.z;
  3107. return this;
  3108. };
  3109. /**
  3110. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3111. * @param otherVector defines the second operand
  3112. * @returns the new Vector3
  3113. */
  3114. Vector3.prototype.multiply = function (otherVector) {
  3115. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3116. };
  3117. /**
  3118. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3119. * @param otherVector defines the second operand
  3120. * @param result defines the Vector3 object where to store the result
  3121. * @returns the current Vector3
  3122. */
  3123. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3124. result.x = this.x * otherVector.x;
  3125. result.y = this.y * otherVector.y;
  3126. result.z = this.z * otherVector.z;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3131. * @param x defines the x coordinate of the operand
  3132. * @param y defines the y coordinate of the operand
  3133. * @param z defines the z coordinate of the operand
  3134. * @returns the new Vector3
  3135. */
  3136. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3137. return new Vector3(this.x * x, this.y * y, this.z * z);
  3138. };
  3139. /**
  3140. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.divide = function (otherVector) {
  3145. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.divideToRef = function (otherVector, result) {
  3154. result.x = this.x / otherVector.x;
  3155. result.y = this.y / otherVector.y;
  3156. result.z = this.z / otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Divides the current Vector3 coordinates by the given ones.
  3161. * @param otherVector defines the second operand
  3162. * @returns the current updated Vector3
  3163. */
  3164. Vector3.prototype.divideInPlace = function (otherVector) {
  3165. return this.divideToRef(otherVector, this);
  3166. };
  3167. /**
  3168. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3169. * @param other defines the second operand
  3170. * @returns the current updated Vector3
  3171. */
  3172. Vector3.prototype.minimizeInPlace = function (other) {
  3173. if (other.x < this.x)
  3174. this.x = other.x;
  3175. if (other.y < this.y)
  3176. this.y = other.y;
  3177. if (other.z < this.z)
  3178. this.z = other.z;
  3179. return this;
  3180. };
  3181. /**
  3182. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3183. * @param other defines the second operand
  3184. * @returns the current updated Vector3
  3185. */
  3186. Vector3.prototype.maximizeInPlace = function (other) {
  3187. if (other.x > this.x)
  3188. this.x = other.x;
  3189. if (other.y > this.y)
  3190. this.y = other.y;
  3191. if (other.z > this.z)
  3192. this.z = other.z;
  3193. return this;
  3194. };
  3195. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3196. /**
  3197. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3198. */
  3199. get: function () {
  3200. var absX = Math.abs(this.x);
  3201. var absY = Math.abs(this.y);
  3202. if (absX !== absY) {
  3203. return true;
  3204. }
  3205. var absZ = Math.abs(this.z);
  3206. if (absX !== absZ) {
  3207. return true;
  3208. }
  3209. if (absY !== absZ) {
  3210. return true;
  3211. }
  3212. return false;
  3213. },
  3214. enumerable: true,
  3215. configurable: true
  3216. });
  3217. /**
  3218. * Gets a new Vector3 from current Vector3 floored values
  3219. * @returns a new Vector3
  3220. */
  3221. Vector3.prototype.floor = function () {
  3222. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3223. };
  3224. /**
  3225. * Gets a new Vector3 from current Vector3 floored values
  3226. * @returns a new Vector3
  3227. */
  3228. Vector3.prototype.fract = function () {
  3229. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3230. };
  3231. // Properties
  3232. /**
  3233. * Gets the length of the Vector3
  3234. * @returns the length of the Vecto3
  3235. */
  3236. Vector3.prototype.length = function () {
  3237. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3238. };
  3239. /**
  3240. * Gets the squared length of the Vector3
  3241. * @returns squared length of the Vector3
  3242. */
  3243. Vector3.prototype.lengthSquared = function () {
  3244. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3245. };
  3246. /**
  3247. * Normalize the current Vector3.
  3248. * Please note that this is an in place operation.
  3249. * @returns the current updated Vector3
  3250. */
  3251. Vector3.prototype.normalize = function () {
  3252. var len = this.length();
  3253. if (len === 0 || len === 1.0)
  3254. return this;
  3255. var num = 1.0 / len;
  3256. this.x *= num;
  3257. this.y *= num;
  3258. this.z *= num;
  3259. return this;
  3260. };
  3261. /**
  3262. * Normalize the current Vector3 to a new vector
  3263. * @returns the new Vector3
  3264. */
  3265. Vector3.prototype.normalizeToNew = function () {
  3266. var normalized = new Vector3(0, 0, 0);
  3267. this.normalizeToRef(normalized);
  3268. return normalized;
  3269. };
  3270. /**
  3271. * Normalize the current Vector3 to the reference
  3272. * @param reference define the Vector3 to update
  3273. * @returns the updated Vector3
  3274. */
  3275. Vector3.prototype.normalizeToRef = function (reference) {
  3276. var len = this.length();
  3277. if (len === 0 || len === 1.0) {
  3278. reference.set(this.x, this.y, this.z);
  3279. return reference;
  3280. }
  3281. var scale = 1.0 / len;
  3282. this.scaleToRef(scale, reference);
  3283. return reference;
  3284. };
  3285. /**
  3286. * Creates a new Vector3 copied from the current Vector3
  3287. * @returns the new Vector3
  3288. */
  3289. Vector3.prototype.clone = function () {
  3290. return new Vector3(this.x, this.y, this.z);
  3291. };
  3292. /**
  3293. * Copies the given vector coordinates to the current Vector3 ones
  3294. * @param source defines the source Vector3
  3295. * @returns the current updated Vector3
  3296. */
  3297. Vector3.prototype.copyFrom = function (source) {
  3298. this.x = source.x;
  3299. this.y = source.y;
  3300. this.z = source.z;
  3301. return this;
  3302. };
  3303. /**
  3304. * Copies the given floats to the current Vector3 coordinates
  3305. * @param x defines the x coordinate of the operand
  3306. * @param y defines the y coordinate of the operand
  3307. * @param z defines the z coordinate of the operand
  3308. * @returns the current updated Vector3
  3309. */
  3310. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3311. this.x = x;
  3312. this.y = y;
  3313. this.z = z;
  3314. return this;
  3315. };
  3316. /**
  3317. * Copies the given floats to the current Vector3 coordinates
  3318. * @param x defines the x coordinate of the operand
  3319. * @param y defines the y coordinate of the operand
  3320. * @param z defines the z coordinate of the operand
  3321. * @returns the current updated Vector3
  3322. */
  3323. Vector3.prototype.set = function (x, y, z) {
  3324. return this.copyFromFloats(x, y, z);
  3325. };
  3326. // Statics
  3327. /**
  3328. * Get the clip factor between two vectors
  3329. * @param vector0 defines the first operand
  3330. * @param vector1 defines the second operand
  3331. * @param axis defines the axis to use
  3332. * @param size defines the size along the axis
  3333. * @returns the clip factor
  3334. */
  3335. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3336. var d0 = Vector3.Dot(vector0, axis) - size;
  3337. var d1 = Vector3.Dot(vector1, axis) - size;
  3338. var s = d0 / (d0 - d1);
  3339. return s;
  3340. };
  3341. /**
  3342. * Get angle between two vectors
  3343. * @param vector0 angle between vector0 and vector1
  3344. * @param vector1 angle between vector0 and vector1
  3345. * @param normal direction of the normal
  3346. * @return the angle between vector0 and vector1
  3347. */
  3348. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3349. var v0 = vector0.clone().normalize();
  3350. var v1 = vector1.clone().normalize();
  3351. var dot = Vector3.Dot(v0, v1);
  3352. var n = Vector3.Cross(v0, v1);
  3353. if (Vector3.Dot(n, normal) > 0) {
  3354. return Math.acos(dot);
  3355. }
  3356. return -Math.acos(dot);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 set from the index "offset" of the given array
  3360. * @param array defines the source array
  3361. * @param offset defines the offset in the source array
  3362. * @returns the new Vector3
  3363. */
  3364. Vector3.FromArray = function (array, offset) {
  3365. if (!offset) {
  3366. offset = 0;
  3367. }
  3368. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3369. };
  3370. /**
  3371. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3372. * This function is deprecated. Use FromArray instead
  3373. * @param array defines the source array
  3374. * @param offset defines the offset in the source array
  3375. * @returns the new Vector3
  3376. */
  3377. Vector3.FromFloatArray = function (array, offset) {
  3378. return Vector3.FromArray(array, offset);
  3379. };
  3380. /**
  3381. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3382. * @param array defines the source array
  3383. * @param offset defines the offset in the source array
  3384. * @param result defines the Vector3 where to store the result
  3385. */
  3386. Vector3.FromArrayToRef = function (array, offset, result) {
  3387. result.x = array[offset];
  3388. result.y = array[offset + 1];
  3389. result.z = array[offset + 2];
  3390. };
  3391. /**
  3392. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3393. * This function is deprecated. Use FromArrayToRef instead.
  3394. * @param array defines the source array
  3395. * @param offset defines the offset in the source array
  3396. * @param result defines the Vector3 where to store the result
  3397. */
  3398. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3399. return Vector3.FromArrayToRef(array, offset, result);
  3400. };
  3401. /**
  3402. * Sets the given vector "result" with the given floats.
  3403. * @param x defines the x coordinate of the source
  3404. * @param y defines the y coordinate of the source
  3405. * @param z defines the z coordinate of the source
  3406. * @param result defines the Vector3 where to store the result
  3407. */
  3408. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3409. result.x = x;
  3410. result.y = y;
  3411. result.z = z;
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3415. * @returns a new empty Vector3
  3416. */
  3417. Vector3.Zero = function () {
  3418. return new Vector3(0.0, 0.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3422. * @returns a new unit Vector3
  3423. */
  3424. Vector3.One = function () {
  3425. return new Vector3(1.0, 1.0, 1.0);
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3429. * @returns a new up Vector3
  3430. */
  3431. Vector3.Up = function () {
  3432. return new Vector3(0.0, 1.0, 0.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3436. * @returns a new down Vector3
  3437. */
  3438. Vector3.Down = function () {
  3439. return new Vector3(0.0, -1.0, 0.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3443. * @returns a new forward Vector3
  3444. */
  3445. Vector3.Forward = function () {
  3446. return new Vector3(0.0, 0.0, 1.0);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3450. * @returns a new forward Vector3
  3451. */
  3452. Vector3.Backward = function () {
  3453. return new Vector3(0.0, 0.0, -1.0);
  3454. };
  3455. /**
  3456. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3457. * @returns a new right Vector3
  3458. */
  3459. Vector3.Right = function () {
  3460. return new Vector3(1.0, 0.0, 0.0);
  3461. };
  3462. /**
  3463. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3464. * @returns a new left Vector3
  3465. */
  3466. Vector3.Left = function () {
  3467. return new Vector3(-1.0, 0.0, 0.0);
  3468. };
  3469. /**
  3470. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3471. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3472. * @param vector defines the Vector3 to transform
  3473. * @param transformation defines the transformation matrix
  3474. * @returns the transformed Vector3
  3475. */
  3476. Vector3.TransformCoordinates = function (vector, transformation) {
  3477. var result = Vector3.Zero();
  3478. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3479. return result;
  3480. };
  3481. /**
  3482. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3483. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3484. * @param vector defines the Vector3 to transform
  3485. * @param transformation defines the transformation matrix
  3486. * @param result defines the Vector3 where to store the result
  3487. */
  3488. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3489. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3490. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3491. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3492. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3493. result.x = x / w;
  3494. result.y = y / w;
  3495. result.z = z / w;
  3496. };
  3497. /**
  3498. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3499. * This method computes tranformed coordinates only, not transformed direction vectors
  3500. * @param x define the x coordinate of the source vector
  3501. * @param y define the y coordinate of the source vector
  3502. * @param z define the z coordinate of the source vector
  3503. * @param transformation defines the transformation matrix
  3504. * @param result defines the Vector3 where to store the result
  3505. */
  3506. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3507. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3508. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3509. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3510. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3511. result.x = rx / rw;
  3512. result.y = ry / rw;
  3513. result.z = rz / rw;
  3514. };
  3515. /**
  3516. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3517. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3518. * @param vector defines the Vector3 to transform
  3519. * @param transformation defines the transformation matrix
  3520. * @returns the new Vector3
  3521. */
  3522. Vector3.TransformNormal = function (vector, transformation) {
  3523. var result = Vector3.Zero();
  3524. Vector3.TransformNormalToRef(vector, transformation, result);
  3525. return result;
  3526. };
  3527. /**
  3528. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3529. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3530. * @param vector defines the Vector3 to transform
  3531. * @param transformation defines the transformation matrix
  3532. * @param result defines the Vector3 where to store the result
  3533. */
  3534. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3535. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3536. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3537. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3538. result.x = x;
  3539. result.y = y;
  3540. result.z = z;
  3541. };
  3542. /**
  3543. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3544. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3545. * @param x define the x coordinate of the source vector
  3546. * @param y define the y coordinate of the source vector
  3547. * @param z define the z coordinate of the source vector
  3548. * @param transformation defines the transformation matrix
  3549. * @param result defines the Vector3 where to store the result
  3550. */
  3551. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3552. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3553. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3554. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3555. };
  3556. /**
  3557. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3558. * @param value1 defines the first control point
  3559. * @param value2 defines the second control point
  3560. * @param value3 defines the third control point
  3561. * @param value4 defines the fourth control point
  3562. * @param amount defines the amount on the spline to use
  3563. * @returns the new Vector3
  3564. */
  3565. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3566. var squared = amount * amount;
  3567. var cubed = amount * squared;
  3568. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3569. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3570. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3571. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3572. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3573. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3574. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3575. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3576. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3577. return new Vector3(x, y, z);
  3578. };
  3579. /**
  3580. * 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"
  3581. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3582. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3583. * @param value defines the current value
  3584. * @param min defines the lower range value
  3585. * @param max defines the upper range value
  3586. * @returns the new Vector3
  3587. */
  3588. Vector3.Clamp = function (value, min, max) {
  3589. var x = value.x;
  3590. x = (x > max.x) ? max.x : x;
  3591. x = (x < min.x) ? min.x : x;
  3592. var y = value.y;
  3593. y = (y > max.y) ? max.y : y;
  3594. y = (y < min.y) ? min.y : y;
  3595. var z = value.z;
  3596. z = (z > max.z) ? max.z : z;
  3597. z = (z < min.z) ? min.z : z;
  3598. return new Vector3(x, y, z);
  3599. };
  3600. /**
  3601. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3602. * @param value1 defines the first control point
  3603. * @param tangent1 defines the first tangent vector
  3604. * @param value2 defines the second control point
  3605. * @param tangent2 defines the second tangent vector
  3606. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3607. * @returns the new Vector3
  3608. */
  3609. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3610. var squared = amount * amount;
  3611. var cubed = amount * squared;
  3612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3614. var part3 = (cubed - (2.0 * squared)) + amount;
  3615. var part4 = cubed - squared;
  3616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3619. return new Vector3(x, y, z);
  3620. };
  3621. /**
  3622. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3623. * @param start defines the start value
  3624. * @param end defines the end value
  3625. * @param amount max defines amount between both (between 0 and 1)
  3626. * @returns the new Vector3
  3627. */
  3628. Vector3.Lerp = function (start, end, amount) {
  3629. var result = new Vector3(0, 0, 0);
  3630. Vector3.LerpToRef(start, end, amount, result);
  3631. return result;
  3632. };
  3633. /**
  3634. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3635. * @param start defines the start value
  3636. * @param end defines the end value
  3637. * @param amount max defines amount between both (between 0 and 1)
  3638. * @param result defines the Vector3 where to store the result
  3639. */
  3640. Vector3.LerpToRef = function (start, end, amount, result) {
  3641. result.x = start.x + ((end.x - start.x) * amount);
  3642. result.y = start.y + ((end.y - start.y) * amount);
  3643. result.z = start.z + ((end.z - start.z) * amount);
  3644. };
  3645. /**
  3646. * Returns the dot product (float) between the vectors "left" and "right"
  3647. * @param left defines the left operand
  3648. * @param right defines the right operand
  3649. * @returns the dot product
  3650. */
  3651. Vector3.Dot = function (left, right) {
  3652. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3653. };
  3654. /**
  3655. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3656. * The cross product is then orthogonal to both "left" and "right"
  3657. * @param left defines the left operand
  3658. * @param right defines the right operand
  3659. * @returns the cross product
  3660. */
  3661. Vector3.Cross = function (left, right) {
  3662. var result = Vector3.Zero();
  3663. Vector3.CrossToRef(left, right, result);
  3664. return result;
  3665. };
  3666. /**
  3667. * Sets the given vector "result" with the cross product of "left" and "right"
  3668. * The cross product is then orthogonal to both "left" and "right"
  3669. * @param left defines the left operand
  3670. * @param right defines the right operand
  3671. * @param result defines the Vector3 where to store the result
  3672. */
  3673. Vector3.CrossToRef = function (left, right, result) {
  3674. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3675. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3676. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3677. result.copyFrom(MathTmp.Vector3[0]);
  3678. };
  3679. /**
  3680. * Returns a new Vector3 as the normalization of the given vector
  3681. * @param vector defines the Vector3 to normalize
  3682. * @returns the new Vector3
  3683. */
  3684. Vector3.Normalize = function (vector) {
  3685. var result = Vector3.Zero();
  3686. Vector3.NormalizeToRef(vector, result);
  3687. return result;
  3688. };
  3689. /**
  3690. * Sets the given vector "result" with the normalization of the given first vector
  3691. * @param vector defines the Vector3 to normalize
  3692. * @param result defines the Vector3 where to store the result
  3693. */
  3694. Vector3.NormalizeToRef = function (vector, result) {
  3695. result.copyFrom(vector);
  3696. result.normalize();
  3697. };
  3698. /**
  3699. * Project a Vector3 onto screen space
  3700. * @param vector defines the Vector3 to project
  3701. * @param world defines the world matrix to use
  3702. * @param transform defines the transform (view x projection) matrix to use
  3703. * @param viewport defines the screen viewport to use
  3704. * @returns the new Vector3
  3705. */
  3706. Vector3.Project = function (vector, world, transform, viewport) {
  3707. var cw = viewport.width;
  3708. var ch = viewport.height;
  3709. var cx = viewport.x;
  3710. var cy = viewport.y;
  3711. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3712. 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);
  3713. var matrix = MathTmp.Matrix[0];
  3714. world.multiplyToRef(transform, matrix);
  3715. matrix.multiplyToRef(viewportMatrix, matrix);
  3716. return Vector3.TransformCoordinates(vector, matrix);
  3717. };
  3718. /**
  3719. * Unproject from screen space to object space
  3720. * @param source defines the screen space Vector3 to use
  3721. * @param viewportWidth defines the current width of the viewport
  3722. * @param viewportHeight defines the current height of the viewport
  3723. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3724. * @param transform defines the transform (view x projection) matrix to use
  3725. * @returns the new Vector3
  3726. */
  3727. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3728. var matrix = MathTmp.Matrix[0];
  3729. world.multiplyToRef(transform, matrix);
  3730. matrix.invert();
  3731. source.x = source.x / viewportWidth * 2 - 1;
  3732. source.y = -(source.y / viewportHeight * 2 - 1);
  3733. var vector = Vector3.TransformCoordinates(source, matrix);
  3734. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3735. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3736. vector = vector.scale(1.0 / num);
  3737. }
  3738. return vector;
  3739. };
  3740. /**
  3741. * Unproject from screen space to object space
  3742. * @param source defines the screen space Vector3 to use
  3743. * @param viewportWidth defines the current width of the viewport
  3744. * @param viewportHeight defines the current height of the viewport
  3745. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3746. * @param view defines the view matrix to use
  3747. * @param projection defines the projection matrix to use
  3748. * @returns the new Vector3
  3749. */
  3750. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3751. var result = Vector3.Zero();
  3752. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3753. return result;
  3754. };
  3755. /**
  3756. * Unproject from screen space to object space
  3757. * @param source defines the screen space Vector3 to use
  3758. * @param viewportWidth defines the current width of the viewport
  3759. * @param viewportHeight defines the current height of the viewport
  3760. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3761. * @param view defines the view matrix to use
  3762. * @param projection defines the projection matrix to use
  3763. * @param result defines the Vector3 where to store the result
  3764. */
  3765. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3766. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3767. };
  3768. /**
  3769. * Unproject from screen space to object space
  3770. * @param sourceX defines the screen space x coordinate to use
  3771. * @param sourceY defines the screen space y coordinate to use
  3772. * @param sourceZ defines the screen space z coordinate to use
  3773. * @param viewportWidth defines the current width of the viewport
  3774. * @param viewportHeight defines the current height of the viewport
  3775. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3776. * @param view defines the view matrix to use
  3777. * @param projection defines the projection matrix to use
  3778. * @param result defines the Vector3 where to store the result
  3779. */
  3780. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3781. var matrix = MathTmp.Matrix[0];
  3782. world.multiplyToRef(view, matrix);
  3783. matrix.multiplyToRef(projection, matrix);
  3784. matrix.invert();
  3785. var screenSource = MathTmp.Vector3[0];
  3786. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3787. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3788. screenSource.z = 2 * sourceZ - 1.0;
  3789. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3790. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3791. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3792. result.scaleInPlace(1.0 / num);
  3793. }
  3794. };
  3795. /**
  3796. * Gets the minimal coordinate values between two Vector3
  3797. * @param left defines the first operand
  3798. * @param right defines the second operand
  3799. * @returns the new Vector3
  3800. */
  3801. Vector3.Minimize = function (left, right) {
  3802. var min = left.clone();
  3803. min.minimizeInPlace(right);
  3804. return min;
  3805. };
  3806. /**
  3807. * Gets the maximal coordinate values between two Vector3
  3808. * @param left defines the first operand
  3809. * @param right defines the second operand
  3810. * @returns the new Vector3
  3811. */
  3812. Vector3.Maximize = function (left, right) {
  3813. var max = left.clone();
  3814. max.maximizeInPlace(right);
  3815. return max;
  3816. };
  3817. /**
  3818. * Returns the distance between the vectors "value1" and "value2"
  3819. * @param value1 defines the first operand
  3820. * @param value2 defines the second operand
  3821. * @returns the distance
  3822. */
  3823. Vector3.Distance = function (value1, value2) {
  3824. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3825. };
  3826. /**
  3827. * Returns the squared distance between the vectors "value1" and "value2"
  3828. * @param value1 defines the first operand
  3829. * @param value2 defines the second operand
  3830. * @returns the squared distance
  3831. */
  3832. Vector3.DistanceSquared = function (value1, value2) {
  3833. var x = value1.x - value2.x;
  3834. var y = value1.y - value2.y;
  3835. var z = value1.z - value2.z;
  3836. return (x * x) + (y * y) + (z * z);
  3837. };
  3838. /**
  3839. * Returns a new Vector3 located at the center between "value1" and "value2"
  3840. * @param value1 defines the first operand
  3841. * @param value2 defines the second operand
  3842. * @returns the new Vector3
  3843. */
  3844. Vector3.Center = function (value1, value2) {
  3845. var center = value1.add(value2);
  3846. center.scaleInPlace(0.5);
  3847. return center;
  3848. };
  3849. /**
  3850. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3851. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3852. * to something in order to rotate it from its local system to the given target system
  3853. * Note: axis1, axis2 and axis3 are normalized during this operation
  3854. * @param axis1 defines the first axis
  3855. * @param axis2 defines the second axis
  3856. * @param axis3 defines the third axis
  3857. * @returns a new Vector3
  3858. */
  3859. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3860. var rotation = Vector3.Zero();
  3861. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3862. return rotation;
  3863. };
  3864. /**
  3865. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3866. * @param axis1 defines the first axis
  3867. * @param axis2 defines the second axis
  3868. * @param axis3 defines the third axis
  3869. * @param ref defines the Vector3 where to store the result
  3870. */
  3871. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3872. var quat = MathTmp.Quaternion[0];
  3873. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3874. quat.toEulerAnglesToRef(ref);
  3875. };
  3876. return Vector3;
  3877. }());
  3878. BABYLON.Vector3 = Vector3;
  3879. //Vector4 class created for EulerAngle class conversion to Quaternion
  3880. var Vector4 = /** @class */ (function () {
  3881. /**
  3882. * Creates a Vector4 object from the given floats.
  3883. */
  3884. function Vector4(x, y, z, w) {
  3885. this.x = x;
  3886. this.y = y;
  3887. this.z = z;
  3888. this.w = w;
  3889. }
  3890. /**
  3891. * Returns the string with the Vector4 coordinates.
  3892. */
  3893. Vector4.prototype.toString = function () {
  3894. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3895. };
  3896. /**
  3897. * Returns the string "Vector4".
  3898. */
  3899. Vector4.prototype.getClassName = function () {
  3900. return "Vector4";
  3901. };
  3902. /**
  3903. * Returns the Vector4 hash code.
  3904. */
  3905. Vector4.prototype.getHashCode = function () {
  3906. var hash = this.x || 0;
  3907. hash = (hash * 397) ^ (this.y || 0);
  3908. hash = (hash * 397) ^ (this.z || 0);
  3909. hash = (hash * 397) ^ (this.w || 0);
  3910. return hash;
  3911. };
  3912. // Operators
  3913. /**
  3914. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3915. */
  3916. Vector4.prototype.asArray = function () {
  3917. var result = new Array();
  3918. this.toArray(result, 0);
  3919. return result;
  3920. };
  3921. /**
  3922. * Populates the given array from the given index with the Vector4 coordinates.
  3923. * Returns the Vector4.
  3924. */
  3925. Vector4.prototype.toArray = function (array, index) {
  3926. if (index === undefined) {
  3927. index = 0;
  3928. }
  3929. array[index] = this.x;
  3930. array[index + 1] = this.y;
  3931. array[index + 2] = this.z;
  3932. array[index + 3] = this.w;
  3933. return this;
  3934. };
  3935. /**
  3936. * Adds the given vector to the current Vector4.
  3937. * Returns the updated Vector4.
  3938. */
  3939. Vector4.prototype.addInPlace = function (otherVector) {
  3940. this.x += otherVector.x;
  3941. this.y += otherVector.y;
  3942. this.z += otherVector.z;
  3943. this.w += otherVector.w;
  3944. return this;
  3945. };
  3946. /**
  3947. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3948. */
  3949. Vector4.prototype.add = function (otherVector) {
  3950. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3951. };
  3952. /**
  3953. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3954. * Returns the current Vector4.
  3955. */
  3956. Vector4.prototype.addToRef = function (otherVector, result) {
  3957. result.x = this.x + otherVector.x;
  3958. result.y = this.y + otherVector.y;
  3959. result.z = this.z + otherVector.z;
  3960. result.w = this.w + otherVector.w;
  3961. return this;
  3962. };
  3963. /**
  3964. * Subtract in place the given vector from the current Vector4.
  3965. * Returns the updated Vector4.
  3966. */
  3967. Vector4.prototype.subtractInPlace = function (otherVector) {
  3968. this.x -= otherVector.x;
  3969. this.y -= otherVector.y;
  3970. this.z -= otherVector.z;
  3971. this.w -= otherVector.w;
  3972. return this;
  3973. };
  3974. /**
  3975. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3976. */
  3977. Vector4.prototype.subtract = function (otherVector) {
  3978. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3979. };
  3980. /**
  3981. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3982. * Returns the current Vector4.
  3983. */
  3984. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3985. result.x = this.x - otherVector.x;
  3986. result.y = this.y - otherVector.y;
  3987. result.z = this.z - otherVector.z;
  3988. result.w = this.w - otherVector.w;
  3989. return this;
  3990. };
  3991. /**
  3992. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3993. */
  3994. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3995. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3996. };
  3997. /**
  3998. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3999. * Returns the current Vector4.
  4000. */
  4001. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4002. result.x = this.x - x;
  4003. result.y = this.y - y;
  4004. result.z = this.z - z;
  4005. result.w = this.w - w;
  4006. return this;
  4007. };
  4008. /**
  4009. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4010. */
  4011. Vector4.prototype.negate = function () {
  4012. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4013. };
  4014. /**
  4015. * Multiplies the current Vector4 coordinates by scale (float).
  4016. * Returns the updated Vector4.
  4017. */
  4018. Vector4.prototype.scaleInPlace = function (scale) {
  4019. this.x *= scale;
  4020. this.y *= scale;
  4021. this.z *= scale;
  4022. this.w *= scale;
  4023. return this;
  4024. };
  4025. /**
  4026. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4027. */
  4028. Vector4.prototype.scale = function (scale) {
  4029. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4030. };
  4031. /**
  4032. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4033. * Returns the current Vector4.
  4034. */
  4035. Vector4.prototype.scaleToRef = function (scale, result) {
  4036. result.x = this.x * scale;
  4037. result.y = this.y * scale;
  4038. result.z = this.z * scale;
  4039. result.w = this.w * scale;
  4040. return this;
  4041. };
  4042. /**
  4043. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4044. * @param scale defines the scale factor
  4045. * @param result defines the Vector4 object where to store the result
  4046. * @returns the unmodified current Vector4
  4047. */
  4048. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4049. result.x += this.x * scale;
  4050. result.y += this.y * scale;
  4051. result.z += this.z * scale;
  4052. result.w += this.w * scale;
  4053. return this;
  4054. };
  4055. /**
  4056. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4057. */
  4058. Vector4.prototype.equals = function (otherVector) {
  4059. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4060. };
  4061. /**
  4062. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4063. */
  4064. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4065. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4066. return otherVector
  4067. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4068. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4069. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4070. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4071. };
  4072. /**
  4073. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4074. */
  4075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4076. return this.x === x && this.y === y && this.z === z && this.w === w;
  4077. };
  4078. /**
  4079. * Multiplies in place the current Vector4 by the given one.
  4080. * Returns the updated Vector4.
  4081. */
  4082. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4083. this.x *= otherVector.x;
  4084. this.y *= otherVector.y;
  4085. this.z *= otherVector.z;
  4086. this.w *= otherVector.w;
  4087. return this;
  4088. };
  4089. /**
  4090. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4091. */
  4092. Vector4.prototype.multiply = function (otherVector) {
  4093. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4094. };
  4095. /**
  4096. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4097. * Returns the current Vector4.
  4098. */
  4099. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4100. result.x = this.x * otherVector.x;
  4101. result.y = this.y * otherVector.y;
  4102. result.z = this.z * otherVector.z;
  4103. result.w = this.w * otherVector.w;
  4104. return this;
  4105. };
  4106. /**
  4107. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4108. */
  4109. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4110. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4111. };
  4112. /**
  4113. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4114. */
  4115. Vector4.prototype.divide = function (otherVector) {
  4116. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4120. * Returns the current Vector4.
  4121. */
  4122. Vector4.prototype.divideToRef = function (otherVector, result) {
  4123. result.x = this.x / otherVector.x;
  4124. result.y = this.y / otherVector.y;
  4125. result.z = this.z / otherVector.z;
  4126. result.w = this.w / otherVector.w;
  4127. return this;
  4128. };
  4129. /**
  4130. * Divides the current Vector3 coordinates by the given ones.
  4131. * @returns the updated Vector3.
  4132. */
  4133. Vector4.prototype.divideInPlace = function (otherVector) {
  4134. return this.divideToRef(otherVector, this);
  4135. };
  4136. /**
  4137. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4138. * @param other defines the second operand
  4139. * @returns the current updated Vector4
  4140. */
  4141. Vector4.prototype.minimizeInPlace = function (other) {
  4142. if (other.x < this.x)
  4143. this.x = other.x;
  4144. if (other.y < this.y)
  4145. this.y = other.y;
  4146. if (other.z < this.z)
  4147. this.z = other.z;
  4148. if (other.w < this.w)
  4149. this.w = other.w;
  4150. return this;
  4151. };
  4152. /**
  4153. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4154. * @param other defines the second operand
  4155. * @returns the current updated Vector4
  4156. */
  4157. Vector4.prototype.maximizeInPlace = function (other) {
  4158. if (other.x > this.x)
  4159. this.x = other.x;
  4160. if (other.y > this.y)
  4161. this.y = other.y;
  4162. if (other.z > this.z)
  4163. this.z = other.z;
  4164. if (other.w > this.w)
  4165. this.w = other.w;
  4166. return this;
  4167. };
  4168. /**
  4169. * Gets a new Vector4 from current Vector4 floored values
  4170. * @returns a new Vector4
  4171. */
  4172. Vector4.prototype.floor = function () {
  4173. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4174. };
  4175. /**
  4176. * Gets a new Vector4 from current Vector3 floored values
  4177. * @returns a new Vector4
  4178. */
  4179. Vector4.prototype.fract = function () {
  4180. 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));
  4181. };
  4182. // Properties
  4183. /**
  4184. * Returns the Vector4 length (float).
  4185. */
  4186. Vector4.prototype.length = function () {
  4187. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4188. };
  4189. /**
  4190. * Returns the Vector4 squared length (float).
  4191. */
  4192. Vector4.prototype.lengthSquared = function () {
  4193. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4194. };
  4195. // Methods
  4196. /**
  4197. * Normalizes in place the Vector4.
  4198. * Returns the updated Vector4.
  4199. */
  4200. Vector4.prototype.normalize = function () {
  4201. var len = this.length();
  4202. if (len === 0)
  4203. return this;
  4204. var num = 1.0 / len;
  4205. this.x *= num;
  4206. this.y *= num;
  4207. this.z *= num;
  4208. this.w *= num;
  4209. return this;
  4210. };
  4211. /**
  4212. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4213. */
  4214. Vector4.prototype.toVector3 = function () {
  4215. return new Vector3(this.x, this.y, this.z);
  4216. };
  4217. /**
  4218. * Returns a new Vector4 copied from the current one.
  4219. */
  4220. Vector4.prototype.clone = function () {
  4221. return new Vector4(this.x, this.y, this.z, this.w);
  4222. };
  4223. /**
  4224. * Updates the current Vector4 with the given one coordinates.
  4225. * Returns the updated Vector4.
  4226. */
  4227. Vector4.prototype.copyFrom = function (source) {
  4228. this.x = source.x;
  4229. this.y = source.y;
  4230. this.z = source.z;
  4231. this.w = source.w;
  4232. return this;
  4233. };
  4234. /**
  4235. * Updates the current Vector4 coordinates with the given floats.
  4236. * Returns the updated Vector4.
  4237. */
  4238. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4239. this.x = x;
  4240. this.y = y;
  4241. this.z = z;
  4242. this.w = w;
  4243. return this;
  4244. };
  4245. /**
  4246. * Updates the current Vector4 coordinates with the given floats.
  4247. * Returns the updated Vector4.
  4248. */
  4249. Vector4.prototype.set = function (x, y, z, w) {
  4250. return this.copyFromFloats(x, y, z, w);
  4251. };
  4252. // Statics
  4253. /**
  4254. * Returns a new Vector4 set from the starting index of the given array.
  4255. */
  4256. Vector4.FromArray = function (array, offset) {
  4257. if (!offset) {
  4258. offset = 0;
  4259. }
  4260. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4261. };
  4262. /**
  4263. * Updates the given vector "result" from the starting index of the given array.
  4264. */
  4265. Vector4.FromArrayToRef = function (array, offset, result) {
  4266. result.x = array[offset];
  4267. result.y = array[offset + 1];
  4268. result.z = array[offset + 2];
  4269. result.w = array[offset + 3];
  4270. };
  4271. /**
  4272. * Updates the given vector "result" from the starting index of the given Float32Array.
  4273. */
  4274. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4275. Vector4.FromArrayToRef(array, offset, result);
  4276. };
  4277. /**
  4278. * Updates the given vector "result" coordinates from the given floats.
  4279. */
  4280. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4281. result.x = x;
  4282. result.y = y;
  4283. result.z = z;
  4284. result.w = w;
  4285. };
  4286. /**
  4287. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4288. */
  4289. Vector4.Zero = function () {
  4290. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4291. };
  4292. /**
  4293. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4294. */
  4295. Vector4.One = function () {
  4296. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4297. };
  4298. /**
  4299. * Returns a new normalized Vector4 from the given one.
  4300. */
  4301. Vector4.Normalize = function (vector) {
  4302. var result = Vector4.Zero();
  4303. Vector4.NormalizeToRef(vector, result);
  4304. return result;
  4305. };
  4306. /**
  4307. * Updates the given vector "result" from the normalization of the given one.
  4308. */
  4309. Vector4.NormalizeToRef = function (vector, result) {
  4310. result.copyFrom(vector);
  4311. result.normalize();
  4312. };
  4313. Vector4.Minimize = function (left, right) {
  4314. var min = left.clone();
  4315. min.minimizeInPlace(right);
  4316. return min;
  4317. };
  4318. Vector4.Maximize = function (left, right) {
  4319. var max = left.clone();
  4320. max.maximizeInPlace(right);
  4321. return max;
  4322. };
  4323. /**
  4324. * Returns the distance (float) between the vectors "value1" and "value2".
  4325. */
  4326. Vector4.Distance = function (value1, value2) {
  4327. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4328. };
  4329. /**
  4330. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4331. */
  4332. Vector4.DistanceSquared = function (value1, value2) {
  4333. var x = value1.x - value2.x;
  4334. var y = value1.y - value2.y;
  4335. var z = value1.z - value2.z;
  4336. var w = value1.w - value2.w;
  4337. return (x * x) + (y * y) + (z * z) + (w * w);
  4338. };
  4339. /**
  4340. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4341. */
  4342. Vector4.Center = function (value1, value2) {
  4343. var center = value1.add(value2);
  4344. center.scaleInPlace(0.5);
  4345. return center;
  4346. };
  4347. /**
  4348. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4349. * This methods computes transformed normalized direction vectors only.
  4350. */
  4351. Vector4.TransformNormal = function (vector, transformation) {
  4352. var result = Vector4.Zero();
  4353. Vector4.TransformNormalToRef(vector, transformation, result);
  4354. return result;
  4355. };
  4356. /**
  4357. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4358. * This methods computes transformed normalized direction vectors only.
  4359. */
  4360. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4361. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4362. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4363. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4364. result.x = x;
  4365. result.y = y;
  4366. result.z = z;
  4367. result.w = vector.w;
  4368. };
  4369. /**
  4370. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4371. * This methods computes transformed normalized direction vectors only.
  4372. */
  4373. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4374. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4375. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4376. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4377. result.w = w;
  4378. };
  4379. return Vector4;
  4380. }());
  4381. BABYLON.Vector4 = Vector4;
  4382. var Size = /** @class */ (function () {
  4383. /**
  4384. * Creates a Size object from the given width and height (floats).
  4385. */
  4386. function Size(width, height) {
  4387. this.width = width;
  4388. this.height = height;
  4389. }
  4390. // Returns a string with the Size width and height.
  4391. Size.prototype.toString = function () {
  4392. return "{W: " + this.width + ", H: " + this.height + "}";
  4393. };
  4394. /**
  4395. * Returns the string "Size"
  4396. */
  4397. Size.prototype.getClassName = function () {
  4398. return "Size";
  4399. };
  4400. /**
  4401. * Returns the Size hash code.
  4402. */
  4403. Size.prototype.getHashCode = function () {
  4404. var hash = this.width || 0;
  4405. hash = (hash * 397) ^ (this.height || 0);
  4406. return hash;
  4407. };
  4408. /**
  4409. * Updates the current size from the given one.
  4410. * Returns the updated Size.
  4411. */
  4412. Size.prototype.copyFrom = function (src) {
  4413. this.width = src.width;
  4414. this.height = src.height;
  4415. };
  4416. /**
  4417. * Updates in place the current Size from the given floats.
  4418. * Returns the updated Size.
  4419. */
  4420. Size.prototype.copyFromFloats = function (width, height) {
  4421. this.width = width;
  4422. this.height = height;
  4423. return this;
  4424. };
  4425. /**
  4426. * Updates in place the current Size from the given floats.
  4427. * Returns the updated Size.
  4428. */
  4429. Size.prototype.set = function (width, height) {
  4430. return this.copyFromFloats(width, height);
  4431. };
  4432. /**
  4433. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4434. */
  4435. Size.prototype.multiplyByFloats = function (w, h) {
  4436. return new Size(this.width * w, this.height * h);
  4437. };
  4438. /**
  4439. * Returns a new Size copied from the given one.
  4440. */
  4441. Size.prototype.clone = function () {
  4442. return new Size(this.width, this.height);
  4443. };
  4444. /**
  4445. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4446. */
  4447. Size.prototype.equals = function (other) {
  4448. if (!other) {
  4449. return false;
  4450. }
  4451. return (this.width === other.width) && (this.height === other.height);
  4452. };
  4453. Object.defineProperty(Size.prototype, "surface", {
  4454. /**
  4455. * Returns the surface of the Size : width * height (float).
  4456. */
  4457. get: function () {
  4458. return this.width * this.height;
  4459. },
  4460. enumerable: true,
  4461. configurable: true
  4462. });
  4463. /**
  4464. * Returns a new Size set to (0.0, 0.0)
  4465. */
  4466. Size.Zero = function () {
  4467. return new Size(0.0, 0.0);
  4468. };
  4469. /**
  4470. * Returns a new Size set as the addition result of the current Size and the given one.
  4471. */
  4472. Size.prototype.add = function (otherSize) {
  4473. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4474. return r;
  4475. };
  4476. /**
  4477. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4478. */
  4479. Size.prototype.subtract = function (otherSize) {
  4480. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4481. return r;
  4482. };
  4483. /**
  4484. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4485. */
  4486. Size.Lerp = function (start, end, amount) {
  4487. var w = start.width + ((end.width - start.width) * amount);
  4488. var h = start.height + ((end.height - start.height) * amount);
  4489. return new Size(w, h);
  4490. };
  4491. return Size;
  4492. }());
  4493. BABYLON.Size = Size;
  4494. /**
  4495. * Class used to store quaternion data
  4496. * @see https://en.wikipedia.org/wiki/Quaternion
  4497. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4498. */
  4499. var Quaternion = /** @class */ (function () {
  4500. /**
  4501. * Creates a new Quaternion from the given floats
  4502. * @param x defines the first component (0 by default)
  4503. * @param y defines the second component (0 by default)
  4504. * @param z defines the third component (0 by default)
  4505. * @param w defines the fourth component (1.0 by default)
  4506. */
  4507. function Quaternion(
  4508. /** defines the first component (0 by default) */
  4509. x,
  4510. /** defines the second component (0 by default) */
  4511. y,
  4512. /** defines the third component (0 by default) */
  4513. z,
  4514. /** defines the fourth component (1.0 by default) */
  4515. w) {
  4516. if (x === void 0) { x = 0.0; }
  4517. if (y === void 0) { y = 0.0; }
  4518. if (z === void 0) { z = 0.0; }
  4519. if (w === void 0) { w = 1.0; }
  4520. this.x = x;
  4521. this.y = y;
  4522. this.z = z;
  4523. this.w = w;
  4524. }
  4525. /**
  4526. * Gets a string representation for the current quaternion
  4527. * @returns a string with the Quaternion coordinates
  4528. */
  4529. Quaternion.prototype.toString = function () {
  4530. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4531. };
  4532. /**
  4533. * Gets the class name of the quaternion
  4534. * @returns the string "Quaternion"
  4535. */
  4536. Quaternion.prototype.getClassName = function () {
  4537. return "Quaternion";
  4538. };
  4539. /**
  4540. * Gets a hash code for this quaternion
  4541. * @returns the quaternion hash code
  4542. */
  4543. Quaternion.prototype.getHashCode = function () {
  4544. var hash = this.x || 0;
  4545. hash = (hash * 397) ^ (this.y || 0);
  4546. hash = (hash * 397) ^ (this.z || 0);
  4547. hash = (hash * 397) ^ (this.w || 0);
  4548. return hash;
  4549. };
  4550. /**
  4551. * Copy the quaternion to an array
  4552. * @returns a new array populated with 4 elements from the quaternion coordinates
  4553. */
  4554. Quaternion.prototype.asArray = function () {
  4555. return [this.x, this.y, this.z, this.w];
  4556. };
  4557. /**
  4558. * Check if two quaternions are equals
  4559. * @param otherQuaternion defines the second operand
  4560. * @return true if the current quaternion and the given one coordinates are strictly equals
  4561. */
  4562. Quaternion.prototype.equals = function (otherQuaternion) {
  4563. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4564. };
  4565. /**
  4566. * Clone the current quaternion
  4567. * @returns a new quaternion copied from the current one
  4568. */
  4569. Quaternion.prototype.clone = function () {
  4570. return new Quaternion(this.x, this.y, this.z, this.w);
  4571. };
  4572. /**
  4573. * Copy a quaternion to the current one
  4574. * @param other defines the other quaternion
  4575. * @returns the updated current quaternion
  4576. */
  4577. Quaternion.prototype.copyFrom = function (other) {
  4578. this.x = other.x;
  4579. this.y = other.y;
  4580. this.z = other.z;
  4581. this.w = other.w;
  4582. return this;
  4583. };
  4584. /**
  4585. * Updates the current quaternion with the given float coordinates
  4586. * @param x defines the x coordinate
  4587. * @param y defines the y coordinate
  4588. * @param z defines the z coordinate
  4589. * @param w defines the w coordinate
  4590. * @returns the updated current quaternion
  4591. */
  4592. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4593. this.x = x;
  4594. this.y = y;
  4595. this.z = z;
  4596. this.w = w;
  4597. return this;
  4598. };
  4599. /**
  4600. * Updates the current quaternion from the given float coordinates
  4601. * @param x defines the x coordinate
  4602. * @param y defines the y coordinate
  4603. * @param z defines the z coordinate
  4604. * @param w defines the w coordinate
  4605. * @returns the updated current quaternion
  4606. */
  4607. Quaternion.prototype.set = function (x, y, z, w) {
  4608. return this.copyFromFloats(x, y, z, w);
  4609. };
  4610. /**
  4611. * Adds two quaternions
  4612. * @param other defines the second operand
  4613. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4614. */
  4615. Quaternion.prototype.add = function (other) {
  4616. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4617. };
  4618. /**
  4619. * Add a quaternion to the current one
  4620. * @param other defines the quaternion to add
  4621. * @returns the current quaternion
  4622. */
  4623. Quaternion.prototype.addInPlace = function (other) {
  4624. this.x += other.x;
  4625. this.y += other.y;
  4626. this.z += other.z;
  4627. this.w += other.w;
  4628. return this;
  4629. };
  4630. /**
  4631. * Subtract two quaternions
  4632. * @param other defines the second operand
  4633. * @returns a new quaternion as the subtraction result of the given one from the current one
  4634. */
  4635. Quaternion.prototype.subtract = function (other) {
  4636. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4637. };
  4638. /**
  4639. * Multiplies the current quaternion by a scale factor
  4640. * @param value defines the scale factor
  4641. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4642. */
  4643. Quaternion.prototype.scale = function (value) {
  4644. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4645. };
  4646. /**
  4647. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4648. * @param scale defines the scale factor
  4649. * @param result defines the Quaternion object where to store the result
  4650. * @returns the unmodified current quaternion
  4651. */
  4652. Quaternion.prototype.scaleToRef = function (scale, result) {
  4653. result.x = this.x * scale;
  4654. result.y = this.y * scale;
  4655. result.z = this.z * scale;
  4656. result.w = this.w * scale;
  4657. return this;
  4658. };
  4659. /**
  4660. * Multiplies in place the current quaternion by a scale factor
  4661. * @param value defines the scale factor
  4662. * @returns the current modified quaternion
  4663. */
  4664. Quaternion.prototype.scaleInPlace = function (value) {
  4665. this.x *= value;
  4666. this.y *= value;
  4667. this.z *= value;
  4668. this.w *= value;
  4669. return this;
  4670. };
  4671. /**
  4672. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4673. * @param scale defines the scale factor
  4674. * @param result defines the Quaternion object where to store the result
  4675. * @returns the unmodified current quaternion
  4676. */
  4677. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4678. result.x += this.x * scale;
  4679. result.y += this.y * scale;
  4680. result.z += this.z * scale;
  4681. result.w += this.w * scale;
  4682. return this;
  4683. };
  4684. /**
  4685. * Multiplies two quaternions
  4686. * @param q1 defines the second operand
  4687. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4688. */
  4689. Quaternion.prototype.multiply = function (q1) {
  4690. var result = new Quaternion(0, 0, 0, 1.0);
  4691. this.multiplyToRef(q1, result);
  4692. return result;
  4693. };
  4694. /**
  4695. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4696. * @param q1 defines the second operand
  4697. * @param result defines the target quaternion
  4698. * @returns the current quaternion
  4699. */
  4700. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4701. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4702. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4703. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4704. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4705. result.copyFromFloats(x, y, z, w);
  4706. return this;
  4707. };
  4708. /**
  4709. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4710. * @param q1 defines the second operand
  4711. * @returns the currentupdated quaternion
  4712. */
  4713. Quaternion.prototype.multiplyInPlace = function (q1) {
  4714. this.multiplyToRef(q1, this);
  4715. return this;
  4716. };
  4717. /**
  4718. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4719. * @param ref defines the target quaternion
  4720. * @returns the current quaternion
  4721. */
  4722. Quaternion.prototype.conjugateToRef = function (ref) {
  4723. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4724. return this;
  4725. };
  4726. /**
  4727. * Conjugates in place (1-q) the current quaternion
  4728. * @returns the current updated quaternion
  4729. */
  4730. Quaternion.prototype.conjugateInPlace = function () {
  4731. this.x *= -1;
  4732. this.y *= -1;
  4733. this.z *= -1;
  4734. return this;
  4735. };
  4736. /**
  4737. * Conjugates in place (1-q) the current quaternion
  4738. * @returns a new quaternion
  4739. */
  4740. Quaternion.prototype.conjugate = function () {
  4741. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4742. return result;
  4743. };
  4744. /**
  4745. * Gets length of current quaternion
  4746. * @returns the quaternion length (float)
  4747. */
  4748. Quaternion.prototype.length = function () {
  4749. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4750. };
  4751. /**
  4752. * Normalize in place the current quaternion
  4753. * @returns the current updated quaternion
  4754. */
  4755. Quaternion.prototype.normalize = function () {
  4756. var length = 1.0 / this.length();
  4757. this.x *= length;
  4758. this.y *= length;
  4759. this.z *= length;
  4760. this.w *= length;
  4761. return this;
  4762. };
  4763. /**
  4764. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4765. * @param order is a reserved parameter and is ignore for now
  4766. * @returns a new Vector3 containing the Euler angles
  4767. */
  4768. Quaternion.prototype.toEulerAngles = function (order) {
  4769. if (order === void 0) { order = "YZX"; }
  4770. var result = Vector3.Zero();
  4771. this.toEulerAnglesToRef(result, order);
  4772. return result;
  4773. };
  4774. /**
  4775. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4776. * @param result defines the vector which will be filled with the Euler angles
  4777. * @param order is a reserved parameter and is ignore for now
  4778. * @returns the current unchanged quaternion
  4779. */
  4780. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4781. if (order === void 0) { order = "YZX"; }
  4782. var qz = this.z;
  4783. var qx = this.x;
  4784. var qy = this.y;
  4785. var qw = this.w;
  4786. var sqw = qw * qw;
  4787. var sqz = qz * qz;
  4788. var sqx = qx * qx;
  4789. var sqy = qy * qy;
  4790. var zAxisY = qy * qz - qx * qw;
  4791. var limit = .4999999;
  4792. if (zAxisY < -limit) {
  4793. result.y = 2 * Math.atan2(qy, qw);
  4794. result.x = Math.PI / 2;
  4795. result.z = 0;
  4796. }
  4797. else if (zAxisY > limit) {
  4798. result.y = 2 * Math.atan2(qy, qw);
  4799. result.x = -Math.PI / 2;
  4800. result.z = 0;
  4801. }
  4802. else {
  4803. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4804. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4805. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4806. }
  4807. return this;
  4808. };
  4809. /**
  4810. * Updates the given rotation matrix with the current quaternion values
  4811. * @param result defines the target matrix
  4812. * @returns the current unchanged quaternion
  4813. */
  4814. Quaternion.prototype.toRotationMatrix = function (result) {
  4815. var xx = this.x * this.x;
  4816. var yy = this.y * this.y;
  4817. var zz = this.z * this.z;
  4818. var xy = this.x * this.y;
  4819. var zw = this.z * this.w;
  4820. var zx = this.z * this.x;
  4821. var yw = this.y * this.w;
  4822. var yz = this.y * this.z;
  4823. var xw = this.x * this.w;
  4824. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4825. result.m[1] = 2.0 * (xy + zw);
  4826. result.m[2] = 2.0 * (zx - yw);
  4827. result.m[3] = 0;
  4828. result.m[4] = 2.0 * (xy - zw);
  4829. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4830. result.m[6] = 2.0 * (yz + xw);
  4831. result.m[7] = 0;
  4832. result.m[8] = 2.0 * (zx + yw);
  4833. result.m[9] = 2.0 * (yz - xw);
  4834. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4835. result.m[11] = 0;
  4836. result.m[12] = 0;
  4837. result.m[13] = 0;
  4838. result.m[14] = 0;
  4839. result.m[15] = 1.0;
  4840. result._markAsUpdated();
  4841. return this;
  4842. };
  4843. /**
  4844. * Updates the current quaternion from the given rotation matrix values
  4845. * @param matrix defines the source matrix
  4846. * @returns the current updated quaternion
  4847. */
  4848. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4849. Quaternion.FromRotationMatrixToRef(matrix, this);
  4850. return this;
  4851. };
  4852. // Statics
  4853. /**
  4854. * Creates a new quaternion from a rotation matrix
  4855. * @param matrix defines the source matrix
  4856. * @returns a new quaternion created from the given rotation matrix values
  4857. */
  4858. Quaternion.FromRotationMatrix = function (matrix) {
  4859. var result = new Quaternion();
  4860. Quaternion.FromRotationMatrixToRef(matrix, result);
  4861. return result;
  4862. };
  4863. /**
  4864. * Updates the given quaternion with the given rotation matrix values
  4865. * @param matrix defines the source matrix
  4866. * @param result defines the target quaternion
  4867. */
  4868. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4869. var data = matrix.m;
  4870. var m11 = data[0], m12 = data[4], m13 = data[8];
  4871. var m21 = data[1], m22 = data[5], m23 = data[9];
  4872. var m31 = data[2], m32 = data[6], m33 = data[10];
  4873. var trace = m11 + m22 + m33;
  4874. var s;
  4875. if (trace > 0) {
  4876. s = 0.5 / Math.sqrt(trace + 1.0);
  4877. result.w = 0.25 / s;
  4878. result.x = (m32 - m23) * s;
  4879. result.y = (m13 - m31) * s;
  4880. result.z = (m21 - m12) * s;
  4881. }
  4882. else if (m11 > m22 && m11 > m33) {
  4883. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4884. result.w = (m32 - m23) / s;
  4885. result.x = 0.25 * s;
  4886. result.y = (m12 + m21) / s;
  4887. result.z = (m13 + m31) / s;
  4888. }
  4889. else if (m22 > m33) {
  4890. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4891. result.w = (m13 - m31) / s;
  4892. result.x = (m12 + m21) / s;
  4893. result.y = 0.25 * s;
  4894. result.z = (m23 + m32) / s;
  4895. }
  4896. else {
  4897. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4898. result.w = (m21 - m12) / s;
  4899. result.x = (m13 + m31) / s;
  4900. result.y = (m23 + m32) / s;
  4901. result.z = 0.25 * s;
  4902. }
  4903. };
  4904. /**
  4905. * Returns the dot product (float) between the quaternions "left" and "right"
  4906. * @param left defines the left operand
  4907. * @param right defines the right operand
  4908. * @returns the dot product
  4909. */
  4910. Quaternion.Dot = function (left, right) {
  4911. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4912. };
  4913. /**
  4914. * Checks if the two quaternions are close to each other
  4915. * @param quat0 defines the first quaternion to check
  4916. * @param quat1 defines the second quaternion to check
  4917. * @returns true if the two quaternions are close to each other
  4918. */
  4919. Quaternion.AreClose = function (quat0, quat1) {
  4920. var dot = Quaternion.Dot(quat0, quat1);
  4921. return dot >= 0;
  4922. };
  4923. /**
  4924. * Creates an empty quaternion
  4925. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4926. */
  4927. Quaternion.Zero = function () {
  4928. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4929. };
  4930. /**
  4931. * Inverse a given quaternion
  4932. * @param q defines the source quaternion
  4933. * @returns a new quaternion as the inverted current quaternion
  4934. */
  4935. Quaternion.Inverse = function (q) {
  4936. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4937. };
  4938. /**
  4939. * Creates an identity quaternion
  4940. * @returns the identity quaternion
  4941. */
  4942. Quaternion.Identity = function () {
  4943. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4944. };
  4945. /**
  4946. * Gets a boolean indicating if the given quaternion is identity
  4947. * @param quaternion defines the quaternion to check
  4948. * @returns true if the quaternion is identity
  4949. */
  4950. Quaternion.IsIdentity = function (quaternion) {
  4951. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4952. };
  4953. /**
  4954. * Creates a quaternion from a rotation around an axis
  4955. * @param axis defines the axis to use
  4956. * @param angle defines the angle to use
  4957. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4958. */
  4959. Quaternion.RotationAxis = function (axis, angle) {
  4960. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4961. };
  4962. /**
  4963. * Creates a rotation around an axis and stores it into the given quaternion
  4964. * @param axis defines the axis to use
  4965. * @param angle defines the angle to use
  4966. * @param result defines the target quaternion
  4967. * @returns the target quaternion
  4968. */
  4969. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4970. var sin = Math.sin(angle / 2);
  4971. axis.normalize();
  4972. result.w = Math.cos(angle / 2);
  4973. result.x = axis.x * sin;
  4974. result.y = axis.y * sin;
  4975. result.z = axis.z * sin;
  4976. return result;
  4977. };
  4978. /**
  4979. * Creates a new quaternion from data stored into an array
  4980. * @param array defines the data source
  4981. * @param offset defines the offset in the source array where the data starts
  4982. * @returns a new quaternion
  4983. */
  4984. Quaternion.FromArray = function (array, offset) {
  4985. if (!offset) {
  4986. offset = 0;
  4987. }
  4988. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4989. };
  4990. /**
  4991. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4992. * @param yaw defines the rotation around Y axis
  4993. * @param pitch defines the rotation around X axis
  4994. * @param roll defines the rotation around Z axis
  4995. * @returns the new quaternion
  4996. */
  4997. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4998. var q = new Quaternion();
  4999. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5000. return q;
  5001. };
  5002. /**
  5003. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5004. * @param yaw defines the rotation around Y axis
  5005. * @param pitch defines the rotation around X axis
  5006. * @param roll defines the rotation around Z axis
  5007. * @param result defines the target quaternion
  5008. */
  5009. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5010. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5011. var halfRoll = roll * 0.5;
  5012. var halfPitch = pitch * 0.5;
  5013. var halfYaw = yaw * 0.5;
  5014. var sinRoll = Math.sin(halfRoll);
  5015. var cosRoll = Math.cos(halfRoll);
  5016. var sinPitch = Math.sin(halfPitch);
  5017. var cosPitch = Math.cos(halfPitch);
  5018. var sinYaw = Math.sin(halfYaw);
  5019. var cosYaw = Math.cos(halfYaw);
  5020. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5021. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5022. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5023. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5024. };
  5025. /**
  5026. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5027. * @param alpha defines the rotation around first axis
  5028. * @param beta defines the rotation around second axis
  5029. * @param gamma defines the rotation around third axis
  5030. * @returns the new quaternion
  5031. */
  5032. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5033. var result = new Quaternion();
  5034. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5035. return result;
  5036. };
  5037. /**
  5038. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5039. * @param alpha defines the rotation around first axis
  5040. * @param beta defines the rotation around second axis
  5041. * @param gamma defines the rotation around third axis
  5042. * @param result defines the target quaternion
  5043. */
  5044. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5045. // Produces a quaternion from Euler angles in the z-x-z orientation
  5046. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5047. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5048. var halfBeta = beta * 0.5;
  5049. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5050. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5051. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5052. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5053. };
  5054. /**
  5055. * 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)
  5056. * @param axis1 defines the first axis
  5057. * @param axis2 defines the second axis
  5058. * @param axis3 defines the third axis
  5059. * @returns the new quaternion
  5060. */
  5061. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5062. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5063. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5064. return quat;
  5065. };
  5066. /**
  5067. * 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
  5068. * @param axis1 defines the first axis
  5069. * @param axis2 defines the second axis
  5070. * @param axis3 defines the third axis
  5071. * @param ref defines the target quaternion
  5072. */
  5073. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5074. var rotMat = MathTmp.Matrix[0];
  5075. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5076. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5077. };
  5078. /**
  5079. * Interpolates between two quaternions
  5080. * @param left defines first quaternion
  5081. * @param right defines second quaternion
  5082. * @param amount defines the gradient to use
  5083. * @returns the new interpolated quaternion
  5084. */
  5085. Quaternion.Slerp = function (left, right, amount) {
  5086. var result = Quaternion.Identity();
  5087. Quaternion.SlerpToRef(left, right, amount, result);
  5088. return result;
  5089. };
  5090. /**
  5091. * Interpolates between two quaternions and stores it into a target quaternion
  5092. * @param left defines first quaternion
  5093. * @param right defines second quaternion
  5094. * @param amount defines the gradient to use
  5095. * @param result defines the target quaternion
  5096. */
  5097. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5098. var num2;
  5099. var num3;
  5100. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5101. var flag = false;
  5102. if (num4 < 0) {
  5103. flag = true;
  5104. num4 = -num4;
  5105. }
  5106. if (num4 > 0.999999) {
  5107. num3 = 1 - amount;
  5108. num2 = flag ? -amount : amount;
  5109. }
  5110. else {
  5111. var num5 = Math.acos(num4);
  5112. var num6 = (1.0 / Math.sin(num5));
  5113. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5114. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5115. }
  5116. result.x = (num3 * left.x) + (num2 * right.x);
  5117. result.y = (num3 * left.y) + (num2 * right.y);
  5118. result.z = (num3 * left.z) + (num2 * right.z);
  5119. result.w = (num3 * left.w) + (num2 * right.w);
  5120. };
  5121. /**
  5122. * Interpolate between two quaternions using Hermite interpolation
  5123. * @param value1 defines first quaternion
  5124. * @param tangent1 defines the incoming tangent
  5125. * @param value2 defines second quaternion
  5126. * @param tangent2 defines the outgoing tangent
  5127. * @param amount defines the target quaternion
  5128. * @returns the new interpolated quaternion
  5129. */
  5130. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5131. var squared = amount * amount;
  5132. var cubed = amount * squared;
  5133. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5134. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5135. var part3 = (cubed - (2.0 * squared)) + amount;
  5136. var part4 = cubed - squared;
  5137. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5138. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5139. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5140. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5141. return new Quaternion(x, y, z, w);
  5142. };
  5143. return Quaternion;
  5144. }());
  5145. BABYLON.Quaternion = Quaternion;
  5146. /**
  5147. * Class used to store matrix data (4x4)
  5148. */
  5149. var Matrix = /** @class */ (function () {
  5150. /**
  5151. * Creates an empty matrix (filled with zeros)
  5152. */
  5153. function Matrix() {
  5154. this._isIdentity = false;
  5155. this._isIdentityDirty = true;
  5156. /**
  5157. * Gets or sets the internal data of the matrix
  5158. */
  5159. this.m = new Float32Array(16);
  5160. this._markAsUpdated();
  5161. }
  5162. /** @hidden */
  5163. Matrix.prototype._markAsUpdated = function () {
  5164. this.updateFlag = Matrix._updateFlagSeed++;
  5165. this._isIdentityDirty = true;
  5166. };
  5167. // Properties
  5168. /**
  5169. * Check if the current matrix is indentity
  5170. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5171. * @returns true is the matrix is the identity matrix
  5172. */
  5173. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5174. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5175. if (this._isIdentityDirty) {
  5176. this._isIdentityDirty = false;
  5177. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5178. this._isIdentity = false;
  5179. }
  5180. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5181. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5182. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5183. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5184. this._isIdentity = false;
  5185. }
  5186. else {
  5187. this._isIdentity = true;
  5188. }
  5189. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5190. this._isIdentity = false;
  5191. }
  5192. }
  5193. return this._isIdentity;
  5194. };
  5195. /**
  5196. * Gets the determinant of the matrix
  5197. * @returns the matrix determinant
  5198. */
  5199. Matrix.prototype.determinant = function () {
  5200. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5201. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5202. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5203. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5204. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5205. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5206. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5207. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5208. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5209. };
  5210. // Methods
  5211. /**
  5212. * Returns the matrix as a Float32Array
  5213. * @returns the matrix underlying array
  5214. */
  5215. Matrix.prototype.toArray = function () {
  5216. return this.m;
  5217. };
  5218. /**
  5219. * Returns the matrix as a Float32Array
  5220. * @returns the matrix underlying array.
  5221. */
  5222. Matrix.prototype.asArray = function () {
  5223. return this.toArray();
  5224. };
  5225. /**
  5226. * Inverts the current matrix in place
  5227. * @returns the current inverted matrix
  5228. */
  5229. Matrix.prototype.invert = function () {
  5230. this.invertToRef(this);
  5231. return this;
  5232. };
  5233. /**
  5234. * Sets all the matrix elements to zero
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.reset = function () {
  5238. for (var index = 0; index < 16; index++) {
  5239. this.m[index] = 0.0;
  5240. }
  5241. this._markAsUpdated();
  5242. return this;
  5243. };
  5244. /**
  5245. * Adds the current matrix with a second one
  5246. * @param other defines the matrix to add
  5247. * @returns a new matrix as the addition of the current matrix and the given one
  5248. */
  5249. Matrix.prototype.add = function (other) {
  5250. var result = new Matrix();
  5251. this.addToRef(other, result);
  5252. return result;
  5253. };
  5254. /**
  5255. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5256. * @param other defines the matrix to add
  5257. * @param result defines the target matrix
  5258. * @returns the current matrix
  5259. */
  5260. Matrix.prototype.addToRef = function (other, result) {
  5261. for (var index = 0; index < 16; index++) {
  5262. result.m[index] = this.m[index] + other.m[index];
  5263. }
  5264. result._markAsUpdated();
  5265. return this;
  5266. };
  5267. /**
  5268. * Adds in place the given matrix to the current matrix
  5269. * @param other defines the second operand
  5270. * @returns the current updated matrix
  5271. */
  5272. Matrix.prototype.addToSelf = function (other) {
  5273. for (var index = 0; index < 16; index++) {
  5274. this.m[index] += other.m[index];
  5275. }
  5276. this._markAsUpdated();
  5277. return this;
  5278. };
  5279. /**
  5280. * Sets the given matrix to the current inverted Matrix
  5281. * @param other defines the target matrix
  5282. * @returns the unmodified current matrix
  5283. */
  5284. Matrix.prototype.invertToRef = function (other) {
  5285. var l1 = this.m[0];
  5286. var l2 = this.m[1];
  5287. var l3 = this.m[2];
  5288. var l4 = this.m[3];
  5289. var l5 = this.m[4];
  5290. var l6 = this.m[5];
  5291. var l7 = this.m[6];
  5292. var l8 = this.m[7];
  5293. var l9 = this.m[8];
  5294. var l10 = this.m[9];
  5295. var l11 = this.m[10];
  5296. var l12 = this.m[11];
  5297. var l13 = this.m[12];
  5298. var l14 = this.m[13];
  5299. var l15 = this.m[14];
  5300. var l16 = this.m[15];
  5301. var l17 = (l11 * l16) - (l12 * l15);
  5302. var l18 = (l10 * l16) - (l12 * l14);
  5303. var l19 = (l10 * l15) - (l11 * l14);
  5304. var l20 = (l9 * l16) - (l12 * l13);
  5305. var l21 = (l9 * l15) - (l11 * l13);
  5306. var l22 = (l9 * l14) - (l10 * l13);
  5307. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5308. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5309. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5310. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5311. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5312. var l28 = (l7 * l16) - (l8 * l15);
  5313. var l29 = (l6 * l16) - (l8 * l14);
  5314. var l30 = (l6 * l15) - (l7 * l14);
  5315. var l31 = (l5 * l16) - (l8 * l13);
  5316. var l32 = (l5 * l15) - (l7 * l13);
  5317. var l33 = (l5 * l14) - (l6 * l13);
  5318. var l34 = (l7 * l12) - (l8 * l11);
  5319. var l35 = (l6 * l12) - (l8 * l10);
  5320. var l36 = (l6 * l11) - (l7 * l10);
  5321. var l37 = (l5 * l12) - (l8 * l9);
  5322. var l38 = (l5 * l11) - (l7 * l9);
  5323. var l39 = (l5 * l10) - (l6 * l9);
  5324. other.m[0] = l23 * l27;
  5325. other.m[4] = l24 * l27;
  5326. other.m[8] = l25 * l27;
  5327. other.m[12] = l26 * l27;
  5328. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5329. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5330. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5331. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5332. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5333. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5334. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5335. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5336. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5337. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5338. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5339. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5340. other._markAsUpdated();
  5341. return this;
  5342. };
  5343. /**
  5344. * Inserts the translation vector (using 3 floats) in the current matrix
  5345. * @param x defines the 1st component of the translation
  5346. * @param y defines the 2nd component of the translation
  5347. * @param z defines the 3rd component of the translation
  5348. * @returns the current updated matrix
  5349. */
  5350. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5351. this.m[12] = x;
  5352. this.m[13] = y;
  5353. this.m[14] = z;
  5354. this._markAsUpdated();
  5355. return this;
  5356. };
  5357. /**
  5358. * Inserts the translation vector in the current matrix
  5359. * @param vector3 defines the translation to insert
  5360. * @returns the current updated matrix
  5361. */
  5362. Matrix.prototype.setTranslation = function (vector3) {
  5363. this.m[12] = vector3.x;
  5364. this.m[13] = vector3.y;
  5365. this.m[14] = vector3.z;
  5366. this._markAsUpdated();
  5367. return this;
  5368. };
  5369. /**
  5370. * Gets the translation value of the current matrix
  5371. * @returns a new Vector3 as the extracted translation from the matrix
  5372. */
  5373. Matrix.prototype.getTranslation = function () {
  5374. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5375. };
  5376. /**
  5377. * Fill a Vector3 with the extracted translation from the matrix
  5378. * @param result defines the Vector3 where to store the translation
  5379. * @returns the current matrix
  5380. */
  5381. Matrix.prototype.getTranslationToRef = function (result) {
  5382. result.x = this.m[12];
  5383. result.y = this.m[13];
  5384. result.z = this.m[14];
  5385. return this;
  5386. };
  5387. /**
  5388. * Remove rotation and scaling part from the matrix
  5389. * @returns the updated matrix
  5390. */
  5391. Matrix.prototype.removeRotationAndScaling = function () {
  5392. this.setRowFromFloats(0, 1, 0, 0, 0);
  5393. this.setRowFromFloats(1, 0, 1, 0, 0);
  5394. this.setRowFromFloats(2, 0, 0, 1, 0);
  5395. return this;
  5396. };
  5397. /**
  5398. * Multiply two matrices
  5399. * @param other defines the second operand
  5400. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5401. */
  5402. Matrix.prototype.multiply = function (other) {
  5403. var result = new Matrix();
  5404. this.multiplyToRef(other, result);
  5405. return result;
  5406. };
  5407. /**
  5408. * Copy the current matrix from the given one
  5409. * @param other defines the source matrix
  5410. * @returns the current updated matrix
  5411. */
  5412. Matrix.prototype.copyFrom = function (other) {
  5413. for (var index = 0; index < 16; index++) {
  5414. this.m[index] = other.m[index];
  5415. }
  5416. this._markAsUpdated();
  5417. return this;
  5418. };
  5419. /**
  5420. * Populates the given array from the starting index with the current matrix values
  5421. * @param array defines the target array
  5422. * @param offset defines the offset in the target array where to start storing values
  5423. * @returns the current matrix
  5424. */
  5425. Matrix.prototype.copyToArray = function (array, offset) {
  5426. if (offset === void 0) { offset = 0; }
  5427. for (var index = 0; index < 16; index++) {
  5428. array[offset + index] = this.m[index];
  5429. }
  5430. return this;
  5431. };
  5432. /**
  5433. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5434. * @param other defines the second operand
  5435. * @param result defines the matrix where to store the multiplication
  5436. * @returns the current matrix
  5437. */
  5438. Matrix.prototype.multiplyToRef = function (other, result) {
  5439. this.multiplyToArray(other, result.m, 0);
  5440. result._markAsUpdated();
  5441. return this;
  5442. };
  5443. /**
  5444. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5445. * @param other defines the second operand
  5446. * @param result defines the array where to store the multiplication
  5447. * @param offset defines the offset in the target array where to start storing values
  5448. * @returns the current matrix
  5449. */
  5450. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5451. var tm0 = this.m[0];
  5452. var tm1 = this.m[1];
  5453. var tm2 = this.m[2];
  5454. var tm3 = this.m[3];
  5455. var tm4 = this.m[4];
  5456. var tm5 = this.m[5];
  5457. var tm6 = this.m[6];
  5458. var tm7 = this.m[7];
  5459. var tm8 = this.m[8];
  5460. var tm9 = this.m[9];
  5461. var tm10 = this.m[10];
  5462. var tm11 = this.m[11];
  5463. var tm12 = this.m[12];
  5464. var tm13 = this.m[13];
  5465. var tm14 = this.m[14];
  5466. var tm15 = this.m[15];
  5467. var om0 = other.m[0];
  5468. var om1 = other.m[1];
  5469. var om2 = other.m[2];
  5470. var om3 = other.m[3];
  5471. var om4 = other.m[4];
  5472. var om5 = other.m[5];
  5473. var om6 = other.m[6];
  5474. var om7 = other.m[7];
  5475. var om8 = other.m[8];
  5476. var om9 = other.m[9];
  5477. var om10 = other.m[10];
  5478. var om11 = other.m[11];
  5479. var om12 = other.m[12];
  5480. var om13 = other.m[13];
  5481. var om14 = other.m[14];
  5482. var om15 = other.m[15];
  5483. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5484. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5485. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5486. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5487. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5488. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5489. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5490. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5491. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5492. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5493. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5494. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5495. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5496. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5497. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5498. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5499. return this;
  5500. };
  5501. /**
  5502. * Check equality between this matrix and a second one
  5503. * @param value defines the second matrix to compare
  5504. * @returns true is the current matrix and the given one values are strictly equal
  5505. */
  5506. Matrix.prototype.equals = function (value) {
  5507. return value &&
  5508. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5509. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5510. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5511. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5512. };
  5513. /**
  5514. * Clone the current matrix
  5515. * @returns a new matrix from the current matrix
  5516. */
  5517. Matrix.prototype.clone = function () {
  5518. 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]);
  5519. };
  5520. /**
  5521. * Returns the name of the current matrix class
  5522. * @returns the string "Matrix"
  5523. */
  5524. Matrix.prototype.getClassName = function () {
  5525. return "Matrix";
  5526. };
  5527. /**
  5528. * Gets the hash code of the current matrix
  5529. * @returns the hash code
  5530. */
  5531. Matrix.prototype.getHashCode = function () {
  5532. var hash = this.m[0] || 0;
  5533. for (var i = 1; i < 16; i++) {
  5534. hash = (hash * 397) ^ (this.m[i] || 0);
  5535. }
  5536. return hash;
  5537. };
  5538. /**
  5539. * Decomposes the current Matrix into a translation, rotation and scaling components
  5540. * @param scale defines the scale vector3 given as a reference to update
  5541. * @param rotation defines the rotation quaternion given as a reference to update
  5542. * @param translation defines the translation vector3 given as a reference to update
  5543. * @returns true if operation was successful
  5544. */
  5545. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5546. if (translation) {
  5547. translation.x = this.m[12];
  5548. translation.y = this.m[13];
  5549. translation.z = this.m[14];
  5550. }
  5551. scale = scale || MathTmp.Vector3[0];
  5552. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5553. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5554. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5555. if (this.determinant() <= 0) {
  5556. scale.y *= -1;
  5557. }
  5558. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5559. if (rotation) {
  5560. rotation.x = 0;
  5561. rotation.y = 0;
  5562. rotation.z = 0;
  5563. rotation.w = 1;
  5564. }
  5565. return false;
  5566. }
  5567. if (rotation) {
  5568. 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]);
  5569. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5570. }
  5571. return true;
  5572. };
  5573. /**
  5574. * Gets specific row of the matrix
  5575. * @param index defines the number of the row to get
  5576. * @returns the index-th row of the current matrix as a new Vector4
  5577. */
  5578. Matrix.prototype.getRow = function (index) {
  5579. if (index < 0 || index > 3) {
  5580. return null;
  5581. }
  5582. var i = index * 4;
  5583. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5584. };
  5585. /**
  5586. * Sets the index-th row of the current matrix to the vector4 values
  5587. * @param index defines the number of the row to set
  5588. * @param row defines the target vector4
  5589. * @returns the updated current matrix
  5590. */
  5591. Matrix.prototype.setRow = function (index, row) {
  5592. if (index < 0 || index > 3) {
  5593. return this;
  5594. }
  5595. var i = index * 4;
  5596. this.m[i + 0] = row.x;
  5597. this.m[i + 1] = row.y;
  5598. this.m[i + 2] = row.z;
  5599. this.m[i + 3] = row.w;
  5600. this._markAsUpdated();
  5601. return this;
  5602. };
  5603. /**
  5604. * Compute the transpose of the matrix
  5605. * @returns the new transposed matrix
  5606. */
  5607. Matrix.prototype.transpose = function () {
  5608. return Matrix.Transpose(this);
  5609. };
  5610. /**
  5611. * Compute the transpose of the matrix and store it in a given matrix
  5612. * @param result defines the target matrix
  5613. * @returns the current matrix
  5614. */
  5615. Matrix.prototype.transposeToRef = function (result) {
  5616. Matrix.TransposeToRef(this, result);
  5617. return this;
  5618. };
  5619. /**
  5620. * Sets the index-th row of the current matrix with the given 4 x float values
  5621. * @param index defines the row index
  5622. * @param x defines the x component to set
  5623. * @param y defines the y component to set
  5624. * @param z defines the z component to set
  5625. * @param w defines the w component to set
  5626. * @returns the updated current matrix
  5627. */
  5628. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5629. if (index < 0 || index > 3) {
  5630. return this;
  5631. }
  5632. var i = index * 4;
  5633. this.m[i + 0] = x;
  5634. this.m[i + 1] = y;
  5635. this.m[i + 2] = z;
  5636. this.m[i + 3] = w;
  5637. this._markAsUpdated();
  5638. return this;
  5639. };
  5640. /**
  5641. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5642. * @param scale defines the scale factor
  5643. * @returns a new matrix
  5644. */
  5645. Matrix.prototype.scale = function (scale) {
  5646. var result = new Matrix();
  5647. this.scaleToRef(scale, result);
  5648. return result;
  5649. };
  5650. /**
  5651. * Scale the current matrix values by a factor to a given result matrix
  5652. * @param scale defines the scale factor
  5653. * @param result defines the matrix to store the result
  5654. * @returns the current matrix
  5655. */
  5656. Matrix.prototype.scaleToRef = function (scale, result) {
  5657. for (var index = 0; index < 16; index++) {
  5658. result.m[index] = this.m[index] * scale;
  5659. }
  5660. result._markAsUpdated();
  5661. return this;
  5662. };
  5663. /**
  5664. * Scale the current matrix values by a factor and add the result to a given matrix
  5665. * @param scale defines the scale factor
  5666. * @param result defines the Matrix to store the result
  5667. * @returns the current matrix
  5668. */
  5669. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5670. for (var index = 0; index < 16; index++) {
  5671. result.m[index] += this.m[index] * scale;
  5672. }
  5673. result._markAsUpdated();
  5674. return this;
  5675. };
  5676. /**
  5677. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5678. * @param ref matrix to store the result
  5679. */
  5680. Matrix.prototype.toNormalMatrix = function (ref) {
  5681. this.invertToRef(ref);
  5682. ref.transpose();
  5683. var m = ref.m;
  5684. 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);
  5685. };
  5686. /**
  5687. * Gets only rotation part of the current matrix
  5688. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5689. */
  5690. Matrix.prototype.getRotationMatrix = function () {
  5691. var result = Matrix.Identity();
  5692. this.getRotationMatrixToRef(result);
  5693. return result;
  5694. };
  5695. /**
  5696. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5697. * @param result defines the target matrix to store data to
  5698. * @returns the current matrix
  5699. */
  5700. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5701. var m = this.m;
  5702. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5703. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5704. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5705. if (this.determinant() <= 0) {
  5706. sy *= -1;
  5707. }
  5708. if (sx === 0 || sy === 0 || sz === 0) {
  5709. Matrix.IdentityToRef(result);
  5710. }
  5711. else {
  5712. 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);
  5713. }
  5714. return this;
  5715. };
  5716. // Statics
  5717. /**
  5718. * Creates a matrix from an array
  5719. * @param array defines the source array
  5720. * @param offset defines an offset in the source array
  5721. * @returns a new Matrix set from the starting index of the given array
  5722. */
  5723. Matrix.FromArray = function (array, offset) {
  5724. var result = new Matrix();
  5725. if (!offset) {
  5726. offset = 0;
  5727. }
  5728. Matrix.FromArrayToRef(array, offset, result);
  5729. return result;
  5730. };
  5731. /**
  5732. * Copy the content of an array into a given matrix
  5733. * @param array defines the source array
  5734. * @param offset defines an offset in the source array
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.FromArrayToRef = function (array, offset, result) {
  5738. for (var index = 0; index < 16; index++) {
  5739. result.m[index] = array[index + offset];
  5740. }
  5741. result._markAsUpdated();
  5742. };
  5743. /**
  5744. * Stores an array into a matrix after having multiplied each component by a given factor
  5745. * @param array defines the source array
  5746. * @param offset defines the offset in the source array
  5747. * @param scale defines the scaling factor
  5748. * @param result defines the target matrix
  5749. */
  5750. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5751. for (var index = 0; index < 16; index++) {
  5752. result.m[index] = array[index + offset] * scale;
  5753. }
  5754. result._markAsUpdated();
  5755. };
  5756. /**
  5757. * Stores a list of values (16) inside a given matrix
  5758. * @param initialM11 defines 1st value of 1st row
  5759. * @param initialM12 defines 2nd value of 1st row
  5760. * @param initialM13 defines 3rd value of 1st row
  5761. * @param initialM14 defines 4th value of 1st row
  5762. * @param initialM21 defines 1st value of 2nd row
  5763. * @param initialM22 defines 2nd value of 2nd row
  5764. * @param initialM23 defines 3rd value of 2nd row
  5765. * @param initialM24 defines 4th value of 2nd row
  5766. * @param initialM31 defines 1st value of 3rd row
  5767. * @param initialM32 defines 2nd value of 3rd row
  5768. * @param initialM33 defines 3rd value of 3rd row
  5769. * @param initialM34 defines 4th value of 3rd row
  5770. * @param initialM41 defines 1st value of 4th row
  5771. * @param initialM42 defines 2nd value of 4th row
  5772. * @param initialM43 defines 3rd value of 4th row
  5773. * @param initialM44 defines 4th value of 4th row
  5774. * @param result defines the target matrix
  5775. */
  5776. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5777. result.m[0] = initialM11;
  5778. result.m[1] = initialM12;
  5779. result.m[2] = initialM13;
  5780. result.m[3] = initialM14;
  5781. result.m[4] = initialM21;
  5782. result.m[5] = initialM22;
  5783. result.m[6] = initialM23;
  5784. result.m[7] = initialM24;
  5785. result.m[8] = initialM31;
  5786. result.m[9] = initialM32;
  5787. result.m[10] = initialM33;
  5788. result.m[11] = initialM34;
  5789. result.m[12] = initialM41;
  5790. result.m[13] = initialM42;
  5791. result.m[14] = initialM43;
  5792. result.m[15] = initialM44;
  5793. result._markAsUpdated();
  5794. };
  5795. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5796. /**
  5797. * Gets an identity matrix that must not be updated
  5798. */
  5799. get: function () {
  5800. return Matrix._identityReadOnly;
  5801. },
  5802. enumerable: true,
  5803. configurable: true
  5804. });
  5805. /**
  5806. * Creates new matrix from a list of values (16)
  5807. * @param initialM11 defines 1st value of 1st row
  5808. * @param initialM12 defines 2nd value of 1st row
  5809. * @param initialM13 defines 3rd value of 1st row
  5810. * @param initialM14 defines 4th value of 1st row
  5811. * @param initialM21 defines 1st value of 2nd row
  5812. * @param initialM22 defines 2nd value of 2nd row
  5813. * @param initialM23 defines 3rd value of 2nd row
  5814. * @param initialM24 defines 4th value of 2nd row
  5815. * @param initialM31 defines 1st value of 3rd row
  5816. * @param initialM32 defines 2nd value of 3rd row
  5817. * @param initialM33 defines 3rd value of 3rd row
  5818. * @param initialM34 defines 4th value of 3rd row
  5819. * @param initialM41 defines 1st value of 4th row
  5820. * @param initialM42 defines 2nd value of 4th row
  5821. * @param initialM43 defines 3rd value of 4th row
  5822. * @param initialM44 defines 4th value of 4th row
  5823. * @returns the new matrix
  5824. */
  5825. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5826. var result = new Matrix();
  5827. result.m[0] = initialM11;
  5828. result.m[1] = initialM12;
  5829. result.m[2] = initialM13;
  5830. result.m[3] = initialM14;
  5831. result.m[4] = initialM21;
  5832. result.m[5] = initialM22;
  5833. result.m[6] = initialM23;
  5834. result.m[7] = initialM24;
  5835. result.m[8] = initialM31;
  5836. result.m[9] = initialM32;
  5837. result.m[10] = initialM33;
  5838. result.m[11] = initialM34;
  5839. result.m[12] = initialM41;
  5840. result.m[13] = initialM42;
  5841. result.m[14] = initialM43;
  5842. result.m[15] = initialM44;
  5843. return result;
  5844. };
  5845. /**
  5846. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5847. * @param scale defines the scale vector3
  5848. * @param rotation defines the rotation quaternion
  5849. * @param translation defines the translation vector3
  5850. * @returns a new matrix
  5851. */
  5852. Matrix.Compose = function (scale, rotation, translation) {
  5853. var result = Matrix.Identity();
  5854. Matrix.ComposeToRef(scale, rotation, translation, result);
  5855. return result;
  5856. };
  5857. /**
  5858. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5859. * @param scale defines the scale vector3
  5860. * @param rotation defines the rotation quaternion
  5861. * @param translation defines the translation vector3
  5862. * @param result defines the target matrix
  5863. */
  5864. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5865. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5866. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5867. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5868. result.setTranslation(translation);
  5869. };
  5870. /**
  5871. * Creates a new identity matrix
  5872. * @returns a new identity matrix
  5873. */
  5874. Matrix.Identity = function () {
  5875. 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);
  5876. };
  5877. /**
  5878. * Creates a new identity matrix and stores the result in a given matrix
  5879. * @param result defines the target matrix
  5880. */
  5881. Matrix.IdentityToRef = function (result) {
  5882. 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);
  5883. };
  5884. /**
  5885. * Creates a new zero matrix
  5886. * @returns a new zero matrix
  5887. */
  5888. Matrix.Zero = function () {
  5889. 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);
  5890. };
  5891. /**
  5892. * Creates a new rotation matrix for "angle" radians around the X axis
  5893. * @param angle defines the angle (in radians) to use
  5894. * @return the new matrix
  5895. */
  5896. Matrix.RotationX = function (angle) {
  5897. var result = new Matrix();
  5898. Matrix.RotationXToRef(angle, result);
  5899. return result;
  5900. };
  5901. /**
  5902. * Creates a new matrix as the invert of a given matrix
  5903. * @param source defines the source matrix
  5904. * @returns the new matrix
  5905. */
  5906. Matrix.Invert = function (source) {
  5907. var result = new Matrix();
  5908. source.invertToRef(result);
  5909. return result;
  5910. };
  5911. /**
  5912. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5913. * @param angle defines the angle (in radians) to use
  5914. * @param result defines the target matrix
  5915. */
  5916. Matrix.RotationXToRef = function (angle, result) {
  5917. var s = Math.sin(angle);
  5918. var c = Math.cos(angle);
  5919. result.m[0] = 1.0;
  5920. result.m[15] = 1.0;
  5921. result.m[5] = c;
  5922. result.m[10] = c;
  5923. result.m[9] = -s;
  5924. result.m[6] = s;
  5925. result.m[1] = 0.0;
  5926. result.m[2] = 0.0;
  5927. result.m[3] = 0.0;
  5928. result.m[4] = 0.0;
  5929. result.m[7] = 0.0;
  5930. result.m[8] = 0.0;
  5931. result.m[11] = 0.0;
  5932. result.m[12] = 0.0;
  5933. result.m[13] = 0.0;
  5934. result.m[14] = 0.0;
  5935. result._markAsUpdated();
  5936. };
  5937. /**
  5938. * Creates a new rotation matrix for "angle" radians around the Y axis
  5939. * @param angle defines the angle (in radians) to use
  5940. * @return the new matrix
  5941. */
  5942. Matrix.RotationY = function (angle) {
  5943. var result = new Matrix();
  5944. Matrix.RotationYToRef(angle, result);
  5945. return result;
  5946. };
  5947. /**
  5948. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5949. * @param angle defines the angle (in radians) to use
  5950. * @param result defines the target matrix
  5951. */
  5952. Matrix.RotationYToRef = function (angle, result) {
  5953. var s = Math.sin(angle);
  5954. var c = Math.cos(angle);
  5955. result.m[5] = 1.0;
  5956. result.m[15] = 1.0;
  5957. result.m[0] = c;
  5958. result.m[2] = -s;
  5959. result.m[8] = s;
  5960. result.m[10] = c;
  5961. result.m[1] = 0.0;
  5962. result.m[3] = 0.0;
  5963. result.m[4] = 0.0;
  5964. result.m[6] = 0.0;
  5965. result.m[7] = 0.0;
  5966. result.m[9] = 0.0;
  5967. result.m[11] = 0.0;
  5968. result.m[12] = 0.0;
  5969. result.m[13] = 0.0;
  5970. result.m[14] = 0.0;
  5971. result._markAsUpdated();
  5972. };
  5973. /**
  5974. * Creates a new rotation matrix for "angle" radians around the Z axis
  5975. * @param angle defines the angle (in radians) to use
  5976. * @return the new matrix
  5977. */
  5978. Matrix.RotationZ = function (angle) {
  5979. var result = new Matrix();
  5980. Matrix.RotationZToRef(angle, result);
  5981. return result;
  5982. };
  5983. /**
  5984. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5985. * @param angle defines the angle (in radians) to use
  5986. * @param result defines the target matrix
  5987. */
  5988. Matrix.RotationZToRef = function (angle, result) {
  5989. var s = Math.sin(angle);
  5990. var c = Math.cos(angle);
  5991. result.m[10] = 1.0;
  5992. result.m[15] = 1.0;
  5993. result.m[0] = c;
  5994. result.m[1] = s;
  5995. result.m[4] = -s;
  5996. result.m[5] = c;
  5997. result.m[2] = 0.0;
  5998. result.m[3] = 0.0;
  5999. result.m[6] = 0.0;
  6000. result.m[7] = 0.0;
  6001. result.m[8] = 0.0;
  6002. result.m[9] = 0.0;
  6003. result.m[11] = 0.0;
  6004. result.m[12] = 0.0;
  6005. result.m[13] = 0.0;
  6006. result.m[14] = 0.0;
  6007. result._markAsUpdated();
  6008. };
  6009. /**
  6010. * Creates a new rotation matrix for "angle" radians around the given axis
  6011. * @param axis defines the axis to use
  6012. * @param angle defines the angle (in radians) to use
  6013. * @return the new matrix
  6014. */
  6015. Matrix.RotationAxis = function (axis, angle) {
  6016. var result = Matrix.Zero();
  6017. Matrix.RotationAxisToRef(axis, angle, result);
  6018. return result;
  6019. };
  6020. /**
  6021. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6022. * @param axis defines the axis to use
  6023. * @param angle defines the angle (in radians) to use
  6024. * @param result defines the target matrix
  6025. */
  6026. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6027. var s = Math.sin(-angle);
  6028. var c = Math.cos(-angle);
  6029. var c1 = 1 - c;
  6030. axis.normalize();
  6031. result.m[0] = (axis.x * axis.x) * c1 + c;
  6032. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6033. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6034. result.m[3] = 0.0;
  6035. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6036. result.m[5] = (axis.y * axis.y) * c1 + c;
  6037. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6038. result.m[7] = 0.0;
  6039. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6040. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6041. result.m[10] = (axis.z * axis.z) * c1 + c;
  6042. result.m[11] = 0.0;
  6043. result.m[15] = 1.0;
  6044. result._markAsUpdated();
  6045. };
  6046. /**
  6047. * Creates a rotation matrix
  6048. * @param yaw defines the yaw angle in radians (Y axis)
  6049. * @param pitch defines the pitch angle in radians (X axis)
  6050. * @param roll defines the roll angle in radians (X axis)
  6051. * @returns the new rotation matrix
  6052. */
  6053. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6054. var result = new Matrix();
  6055. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6056. return result;
  6057. };
  6058. /**
  6059. * Creates a rotation matrix and stores it in a given matrix
  6060. * @param yaw defines the yaw angle in radians (Y axis)
  6061. * @param pitch defines the pitch angle in radians (X axis)
  6062. * @param roll defines the roll angle in radians (X axis)
  6063. * @param result defines the target matrix
  6064. */
  6065. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6066. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6067. this._tempQuaternion.toRotationMatrix(result);
  6068. };
  6069. /**
  6070. * Creates a scaling matrix
  6071. * @param x defines the scale factor on X axis
  6072. * @param y defines the scale factor on Y axis
  6073. * @param z defines the scale factor on Z axis
  6074. * @returns the new matrix
  6075. */
  6076. Matrix.Scaling = function (x, y, z) {
  6077. var result = Matrix.Zero();
  6078. Matrix.ScalingToRef(x, y, z, result);
  6079. return result;
  6080. };
  6081. /**
  6082. * Creates a scaling matrix and stores it in a given matrix
  6083. * @param x defines the scale factor on X axis
  6084. * @param y defines the scale factor on Y axis
  6085. * @param z defines the scale factor on Z axis
  6086. * @param result defines the target matrix
  6087. */
  6088. Matrix.ScalingToRef = function (x, y, z, result) {
  6089. result.m[0] = x;
  6090. result.m[1] = 0.0;
  6091. result.m[2] = 0.0;
  6092. result.m[3] = 0.0;
  6093. result.m[4] = 0.0;
  6094. result.m[5] = y;
  6095. result.m[6] = 0.0;
  6096. result.m[7] = 0.0;
  6097. result.m[8] = 0.0;
  6098. result.m[9] = 0.0;
  6099. result.m[10] = z;
  6100. result.m[11] = 0.0;
  6101. result.m[12] = 0.0;
  6102. result.m[13] = 0.0;
  6103. result.m[14] = 0.0;
  6104. result.m[15] = 1.0;
  6105. result._markAsUpdated();
  6106. };
  6107. /**
  6108. * Creates a translation matrix
  6109. * @param x defines the translation on X axis
  6110. * @param y defines the translation on Y axis
  6111. * @param z defines the translationon Z axis
  6112. * @returns the new matrix
  6113. */
  6114. Matrix.Translation = function (x, y, z) {
  6115. var result = Matrix.Identity();
  6116. Matrix.TranslationToRef(x, y, z, result);
  6117. return result;
  6118. };
  6119. /**
  6120. * Creates a translation matrix and stores it in a given matrix
  6121. * @param x defines the translation on X axis
  6122. * @param y defines the translation on Y axis
  6123. * @param z defines the translationon Z axis
  6124. * @param result defines the target matrix
  6125. */
  6126. Matrix.TranslationToRef = function (x, y, z, result) {
  6127. 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);
  6128. };
  6129. /**
  6130. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6131. * @param startValue defines the start value
  6132. * @param endValue defines the end value
  6133. * @param gradient defines the gradient factor
  6134. * @returns the new matrix
  6135. */
  6136. Matrix.Lerp = function (startValue, endValue, gradient) {
  6137. var result = Matrix.Zero();
  6138. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6139. return result;
  6140. };
  6141. /**
  6142. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6143. * @param startValue defines the start value
  6144. * @param endValue defines the end value
  6145. * @param gradient defines the gradient factor
  6146. * @param result defines the Matrix object where to store data
  6147. */
  6148. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6149. for (var index = 0; index < 16; index++) {
  6150. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6151. }
  6152. result._markAsUpdated();
  6153. };
  6154. /**
  6155. * Builds a new matrix whose values are computed by:
  6156. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6157. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6158. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6159. * @param startValue defines the first matrix
  6160. * @param endValue defines the second matrix
  6161. * @param gradient defines the gradient between the two matrices
  6162. * @returns the new matrix
  6163. */
  6164. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6165. var result = Matrix.Zero();
  6166. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6167. return result;
  6168. };
  6169. /**
  6170. * Update a matrix to values which are computed by:
  6171. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6172. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6173. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6174. * @param startValue defines the first matrix
  6175. * @param endValue defines the second matrix
  6176. * @param gradient defines the gradient between the two matrices
  6177. * @param result defines the target matrix
  6178. */
  6179. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6180. var startScale = MathTmp.Vector3[0];
  6181. var startRotation = MathTmp.Quaternion[0];
  6182. var startTranslation = MathTmp.Vector3[1];
  6183. startValue.decompose(startScale, startRotation, startTranslation);
  6184. var endScale = MathTmp.Vector3[2];
  6185. var endRotation = MathTmp.Quaternion[1];
  6186. var endTranslation = MathTmp.Vector3[3];
  6187. endValue.decompose(endScale, endRotation, endTranslation);
  6188. var resultScale = MathTmp.Vector3[4];
  6189. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6190. var resultRotation = MathTmp.Quaternion[2];
  6191. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6192. var resultTranslation = MathTmp.Vector3[5];
  6193. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6194. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6195. };
  6196. /**
  6197. * 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"
  6198. * This function works in left 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. * @returns the new matrix
  6203. */
  6204. Matrix.LookAtLH = function (eye, target, up) {
  6205. var result = Matrix.Zero();
  6206. Matrix.LookAtLHToRef(eye, target, up, result);
  6207. return result;
  6208. };
  6209. /**
  6210. * 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".
  6211. * This function works in left handed mode
  6212. * @param eye defines the final position of the entity
  6213. * @param target defines where the entity should look at
  6214. * @param up defines the up vector for the entity
  6215. * @param result defines the target matrix
  6216. */
  6217. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6218. // Z axis
  6219. target.subtractToRef(eye, this._zAxis);
  6220. this._zAxis.normalize();
  6221. // X axis
  6222. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6223. if (this._xAxis.lengthSquared() === 0) {
  6224. this._xAxis.x = 1.0;
  6225. }
  6226. else {
  6227. this._xAxis.normalize();
  6228. }
  6229. // Y axis
  6230. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6231. this._yAxis.normalize();
  6232. // Eye angles
  6233. var ex = -Vector3.Dot(this._xAxis, eye);
  6234. var ey = -Vector3.Dot(this._yAxis, eye);
  6235. var ez = -Vector3.Dot(this._zAxis, eye);
  6236. 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);
  6237. };
  6238. /**
  6239. * 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"
  6240. * This function works in right handed mode
  6241. * @param eye defines the final position of the entity
  6242. * @param target defines where the entity should look at
  6243. * @param up defines the up vector for the entity
  6244. * @returns the new matrix
  6245. */
  6246. Matrix.LookAtRH = function (eye, target, up) {
  6247. var result = Matrix.Zero();
  6248. Matrix.LookAtRHToRef(eye, target, up, result);
  6249. return result;
  6250. };
  6251. /**
  6252. * 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".
  6253. * This function works in right handed mode
  6254. * @param eye defines the final position of the entity
  6255. * @param target defines where the entity should look at
  6256. * @param up defines the up vector for the entity
  6257. * @param result defines the target matrix
  6258. */
  6259. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6260. // Z axis
  6261. eye.subtractToRef(target, this._zAxis);
  6262. this._zAxis.normalize();
  6263. // X axis
  6264. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6265. if (this._xAxis.lengthSquared() === 0) {
  6266. this._xAxis.x = 1.0;
  6267. }
  6268. else {
  6269. this._xAxis.normalize();
  6270. }
  6271. // Y axis
  6272. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6273. this._yAxis.normalize();
  6274. // Eye angles
  6275. var ex = -Vector3.Dot(this._xAxis, eye);
  6276. var ey = -Vector3.Dot(this._yAxis, eye);
  6277. var ez = -Vector3.Dot(this._zAxis, eye);
  6278. 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);
  6279. };
  6280. /**
  6281. * Create a left-handed orthographic projection matrix
  6282. * @param width defines the viewport width
  6283. * @param height defines the viewport height
  6284. * @param znear defines the near clip plane
  6285. * @param zfar defines the far clip plane
  6286. * @returns a new matrix as a left-handed orthographic projection matrix
  6287. */
  6288. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6289. var matrix = Matrix.Zero();
  6290. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6291. return matrix;
  6292. };
  6293. /**
  6294. * Store a left-handed orthographic projection to a given matrix
  6295. * @param width defines the viewport width
  6296. * @param height defines the viewport height
  6297. * @param znear defines the near clip plane
  6298. * @param zfar defines the far clip plane
  6299. * @param result defines the target matrix
  6300. */
  6301. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6302. var n = znear;
  6303. var f = zfar;
  6304. var a = 2.0 / width;
  6305. var b = 2.0 / height;
  6306. var c = 2.0 / (f - n);
  6307. var d = -(f + n) / (f - n);
  6308. 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);
  6309. };
  6310. /**
  6311. * Create a left-handed orthographic projection matrix
  6312. * @param left defines the viewport left coordinate
  6313. * @param right defines the viewport right coordinate
  6314. * @param bottom defines the viewport bottom coordinate
  6315. * @param top defines the viewport top coordinate
  6316. * @param znear defines the near clip plane
  6317. * @param zfar defines the far clip plane
  6318. * @returns a new matrix as a left-handed orthographic projection matrix
  6319. */
  6320. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6321. var matrix = Matrix.Zero();
  6322. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6323. return matrix;
  6324. };
  6325. /**
  6326. * Stores a left-handed orthographic projection into a given matrix
  6327. * @param left defines the viewport left coordinate
  6328. * @param right defines the viewport right coordinate
  6329. * @param bottom defines the viewport bottom coordinate
  6330. * @param top defines the viewport top coordinate
  6331. * @param znear defines the near clip plane
  6332. * @param zfar defines the far clip plane
  6333. * @param result defines the target matrix
  6334. */
  6335. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6336. var n = znear;
  6337. var f = zfar;
  6338. var a = 2.0 / (right - left);
  6339. var b = 2.0 / (top - bottom);
  6340. var c = 2.0 / (f - n);
  6341. var d = -(f + n) / (f - n);
  6342. var i0 = (left + right) / (left - right);
  6343. var i1 = (top + bottom) / (bottom - top);
  6344. 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);
  6345. };
  6346. /**
  6347. * Creates a right-handed orthographic projection matrix
  6348. * @param left defines the viewport left coordinate
  6349. * @param right defines the viewport right coordinate
  6350. * @param bottom defines the viewport bottom coordinate
  6351. * @param top defines the viewport top coordinate
  6352. * @param znear defines the near clip plane
  6353. * @param zfar defines the far clip plane
  6354. * @returns a new matrix as a right-handed orthographic projection matrix
  6355. */
  6356. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6357. var matrix = Matrix.Zero();
  6358. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6359. return matrix;
  6360. };
  6361. /**
  6362. * Stores a right-handed orthographic projection into a given matrix
  6363. * @param left defines the viewport left coordinate
  6364. * @param right defines the viewport right coordinate
  6365. * @param bottom defines the viewport bottom coordinate
  6366. * @param top defines the viewport top coordinate
  6367. * @param znear defines the near clip plane
  6368. * @param zfar defines the far clip plane
  6369. * @param result defines the target matrix
  6370. */
  6371. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6372. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6373. result.m[10] *= -1.0;
  6374. };
  6375. /**
  6376. * Creates a left-handed perspective projection matrix
  6377. * @param width defines the viewport width
  6378. * @param height defines the viewport height
  6379. * @param znear defines the near clip plane
  6380. * @param zfar defines the far clip plane
  6381. * @returns a new matrix as a left-handed perspective projection matrix
  6382. */
  6383. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6384. var matrix = Matrix.Zero();
  6385. var n = znear;
  6386. var f = zfar;
  6387. var a = 2.0 * n / width;
  6388. var b = 2.0 * n / height;
  6389. var c = (f + n) / (f - n);
  6390. var d = -2.0 * f * n / (f - n);
  6391. 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);
  6392. return matrix;
  6393. };
  6394. /**
  6395. * Creates a left-handed perspective projection matrix
  6396. * @param fov defines the horizontal field of view
  6397. * @param aspect defines the aspect ratio
  6398. * @param znear defines the near clip plane
  6399. * @param zfar defines the far clip plane
  6400. * @returns a new matrix as a left-handed perspective projection matrix
  6401. */
  6402. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6403. var matrix = Matrix.Zero();
  6404. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6405. return matrix;
  6406. };
  6407. /**
  6408. * Stores a left-handed perspective projection into a given matrix
  6409. * @param fov defines the horizontal field of view
  6410. * @param aspect defines the aspect ratio
  6411. * @param znear defines the near clip plane
  6412. * @param zfar defines the far clip plane
  6413. * @param result defines the target matrix
  6414. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6415. */
  6416. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6417. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6418. var n = znear;
  6419. var f = zfar;
  6420. var t = 1.0 / (Math.tan(fov * 0.5));
  6421. var a = isVerticalFovFixed ? (t / aspect) : t;
  6422. var b = isVerticalFovFixed ? t : (t * aspect);
  6423. var c = (f + n) / (f - n);
  6424. var d = -2.0 * f * n / (f - n);
  6425. 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);
  6426. };
  6427. /**
  6428. * Creates a right-handed perspective projection matrix
  6429. * @param fov defines the horizontal field of view
  6430. * @param aspect defines the aspect ratio
  6431. * @param znear defines the near clip plane
  6432. * @param zfar defines the far clip plane
  6433. * @returns a new matrix as a right-handed perspective projection matrix
  6434. */
  6435. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6436. var matrix = Matrix.Zero();
  6437. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6438. return matrix;
  6439. };
  6440. /**
  6441. * Stores a right-handed perspective projection into a given matrix
  6442. * @param fov defines the horizontal field of view
  6443. * @param aspect defines the aspect ratio
  6444. * @param znear defines the near clip plane
  6445. * @param zfar defines the far clip plane
  6446. * @param result defines the target matrix
  6447. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6448. */
  6449. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6450. //alternatively this could be expressed as:
  6451. // m = PerspectiveFovLHToRef
  6452. // m[10] *= -1.0;
  6453. // m[11] *= -1.0;
  6454. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6455. var n = znear;
  6456. var f = zfar;
  6457. var t = 1.0 / (Math.tan(fov * 0.5));
  6458. var a = isVerticalFovFixed ? (t / aspect) : t;
  6459. var b = isVerticalFovFixed ? t : (t * aspect);
  6460. var c = -(f + n) / (f - n);
  6461. var d = -2 * f * n / (f - n);
  6462. 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);
  6463. };
  6464. /**
  6465. * Stores a perspective projection for WebVR info a given matrix
  6466. * @param fov defines the field of view
  6467. * @param znear defines the near clip plane
  6468. * @param zfar defines the far clip plane
  6469. * @param result defines the target matrix
  6470. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6471. */
  6472. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6473. if (rightHanded === void 0) { rightHanded = false; }
  6474. var rightHandedFactor = rightHanded ? -1 : 1;
  6475. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6476. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6477. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6478. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6479. var xScale = 2.0 / (leftTan + rightTan);
  6480. var yScale = 2.0 / (upTan + downTan);
  6481. result.m[0] = xScale;
  6482. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6483. result.m[5] = yScale;
  6484. result.m[6] = result.m[7] = 0.0;
  6485. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6486. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6487. result.m[10] = -zfar / (znear - zfar);
  6488. result.m[11] = 1.0 * rightHandedFactor;
  6489. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6490. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6491. result._markAsUpdated();
  6492. };
  6493. /**
  6494. * Computes a complete transformation matrix
  6495. * @param viewport defines the viewport to use
  6496. * @param world defines the world matrix
  6497. * @param view defines the view matrix
  6498. * @param projection defines the projection matrix
  6499. * @param zmin defines the near clip plane
  6500. * @param zmax defines the far clip plane
  6501. * @returns the transformation matrix
  6502. */
  6503. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6504. var cw = viewport.width;
  6505. var ch = viewport.height;
  6506. var cx = viewport.x;
  6507. var cy = viewport.y;
  6508. 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);
  6509. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6510. };
  6511. /**
  6512. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6513. * @param matrix defines the matrix to use
  6514. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6515. */
  6516. Matrix.GetAsMatrix2x2 = function (matrix) {
  6517. return new Float32Array([
  6518. matrix.m[0], matrix.m[1],
  6519. matrix.m[4], matrix.m[5]
  6520. ]);
  6521. };
  6522. /**
  6523. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6524. * @param matrix defines the matrix to use
  6525. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6526. */
  6527. Matrix.GetAsMatrix3x3 = function (matrix) {
  6528. return new Float32Array([
  6529. matrix.m[0], matrix.m[1], matrix.m[2],
  6530. matrix.m[4], matrix.m[5], matrix.m[6],
  6531. matrix.m[8], matrix.m[9], matrix.m[10]
  6532. ]);
  6533. };
  6534. /**
  6535. * Compute the transpose of a given matrix
  6536. * @param matrix defines the matrix to transpose
  6537. * @returns the new matrix
  6538. */
  6539. Matrix.Transpose = function (matrix) {
  6540. var result = new Matrix();
  6541. Matrix.TransposeToRef(matrix, result);
  6542. return result;
  6543. };
  6544. /**
  6545. * Compute the transpose of a matrix and store it in a target matrix
  6546. * @param matrix defines the matrix to transpose
  6547. * @param result defines the target matrix
  6548. */
  6549. Matrix.TransposeToRef = function (matrix, result) {
  6550. result.m[0] = matrix.m[0];
  6551. result.m[1] = matrix.m[4];
  6552. result.m[2] = matrix.m[8];
  6553. result.m[3] = matrix.m[12];
  6554. result.m[4] = matrix.m[1];
  6555. result.m[5] = matrix.m[5];
  6556. result.m[6] = matrix.m[9];
  6557. result.m[7] = matrix.m[13];
  6558. result.m[8] = matrix.m[2];
  6559. result.m[9] = matrix.m[6];
  6560. result.m[10] = matrix.m[10];
  6561. result.m[11] = matrix.m[14];
  6562. result.m[12] = matrix.m[3];
  6563. result.m[13] = matrix.m[7];
  6564. result.m[14] = matrix.m[11];
  6565. result.m[15] = matrix.m[15];
  6566. };
  6567. /**
  6568. * Computes a reflection matrix from a plane
  6569. * @param plane defines the reflection plane
  6570. * @returns a new matrix
  6571. */
  6572. Matrix.Reflection = function (plane) {
  6573. var matrix = new Matrix();
  6574. Matrix.ReflectionToRef(plane, matrix);
  6575. return matrix;
  6576. };
  6577. /**
  6578. * Computes a reflection matrix from a plane
  6579. * @param plane defines the reflection plane
  6580. * @param result defines the target matrix
  6581. */
  6582. Matrix.ReflectionToRef = function (plane, result) {
  6583. plane.normalize();
  6584. var x = plane.normal.x;
  6585. var y = plane.normal.y;
  6586. var z = plane.normal.z;
  6587. var temp = -2 * x;
  6588. var temp2 = -2 * y;
  6589. var temp3 = -2 * z;
  6590. result.m[0] = (temp * x) + 1;
  6591. result.m[1] = temp2 * x;
  6592. result.m[2] = temp3 * x;
  6593. result.m[3] = 0.0;
  6594. result.m[4] = temp * y;
  6595. result.m[5] = (temp2 * y) + 1;
  6596. result.m[6] = temp3 * y;
  6597. result.m[7] = 0.0;
  6598. result.m[8] = temp * z;
  6599. result.m[9] = temp2 * z;
  6600. result.m[10] = (temp3 * z) + 1;
  6601. result.m[11] = 0.0;
  6602. result.m[12] = temp * plane.d;
  6603. result.m[13] = temp2 * plane.d;
  6604. result.m[14] = temp3 * plane.d;
  6605. result.m[15] = 1.0;
  6606. result._markAsUpdated();
  6607. };
  6608. /**
  6609. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6610. * @param xaxis defines the value of the 1st axis
  6611. * @param yaxis defines the value of the 2nd axis
  6612. * @param zaxis defines the value of the 3rd axis
  6613. * @param result defines the target matrix
  6614. */
  6615. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6616. result.m[0] = xaxis.x;
  6617. result.m[1] = xaxis.y;
  6618. result.m[2] = xaxis.z;
  6619. result.m[3] = 0.0;
  6620. result.m[4] = yaxis.x;
  6621. result.m[5] = yaxis.y;
  6622. result.m[6] = yaxis.z;
  6623. result.m[7] = 0.0;
  6624. result.m[8] = zaxis.x;
  6625. result.m[9] = zaxis.y;
  6626. result.m[10] = zaxis.z;
  6627. result.m[11] = 0.0;
  6628. result.m[12] = 0.0;
  6629. result.m[13] = 0.0;
  6630. result.m[14] = 0.0;
  6631. result.m[15] = 1.0;
  6632. result._markAsUpdated();
  6633. };
  6634. /**
  6635. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6636. * @param quat defines the quaternion to use
  6637. * @param result defines the target matrix
  6638. */
  6639. Matrix.FromQuaternionToRef = function (quat, result) {
  6640. var xx = quat.x * quat.x;
  6641. var yy = quat.y * quat.y;
  6642. var zz = quat.z * quat.z;
  6643. var xy = quat.x * quat.y;
  6644. var zw = quat.z * quat.w;
  6645. var zx = quat.z * quat.x;
  6646. var yw = quat.y * quat.w;
  6647. var yz = quat.y * quat.z;
  6648. var xw = quat.x * quat.w;
  6649. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6650. result.m[1] = 2.0 * (xy + zw);
  6651. result.m[2] = 2.0 * (zx - yw);
  6652. result.m[3] = 0.0;
  6653. result.m[4] = 2.0 * (xy - zw);
  6654. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6655. result.m[6] = 2.0 * (yz + xw);
  6656. result.m[7] = 0.0;
  6657. result.m[8] = 2.0 * (zx + yw);
  6658. result.m[9] = 2.0 * (yz - xw);
  6659. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6660. result.m[11] = 0.0;
  6661. result.m[12] = 0.0;
  6662. result.m[13] = 0.0;
  6663. result.m[14] = 0.0;
  6664. result.m[15] = 1.0;
  6665. result._markAsUpdated();
  6666. };
  6667. Matrix._tempQuaternion = new Quaternion();
  6668. Matrix._xAxis = Vector3.Zero();
  6669. Matrix._yAxis = Vector3.Zero();
  6670. Matrix._zAxis = Vector3.Zero();
  6671. Matrix._updateFlagSeed = 0;
  6672. Matrix._identityReadOnly = Matrix.Identity();
  6673. return Matrix;
  6674. }());
  6675. BABYLON.Matrix = Matrix;
  6676. var Plane = /** @class */ (function () {
  6677. /**
  6678. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6679. */
  6680. function Plane(a, b, c, d) {
  6681. this.normal = new Vector3(a, b, c);
  6682. this.d = d;
  6683. }
  6684. /**
  6685. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6686. */
  6687. Plane.prototype.asArray = function () {
  6688. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6689. };
  6690. // Methods
  6691. /**
  6692. * Returns a new plane copied from the current Plane.
  6693. */
  6694. Plane.prototype.clone = function () {
  6695. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6696. };
  6697. /**
  6698. * Returns the string "Plane".
  6699. */
  6700. Plane.prototype.getClassName = function () {
  6701. return "Plane";
  6702. };
  6703. /**
  6704. * Returns the Plane hash code.
  6705. */
  6706. Plane.prototype.getHashCode = function () {
  6707. var hash = this.normal.getHashCode();
  6708. hash = (hash * 397) ^ (this.d || 0);
  6709. return hash;
  6710. };
  6711. /**
  6712. * Normalize the current Plane in place.
  6713. * Returns the updated Plane.
  6714. */
  6715. Plane.prototype.normalize = function () {
  6716. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6717. var magnitude = 0.0;
  6718. if (norm !== 0) {
  6719. magnitude = 1.0 / norm;
  6720. }
  6721. this.normal.x *= magnitude;
  6722. this.normal.y *= magnitude;
  6723. this.normal.z *= magnitude;
  6724. this.d *= magnitude;
  6725. return this;
  6726. };
  6727. /**
  6728. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6729. */
  6730. Plane.prototype.transform = function (transformation) {
  6731. var transposedMatrix = Matrix.Transpose(transformation);
  6732. var x = this.normal.x;
  6733. var y = this.normal.y;
  6734. var z = this.normal.z;
  6735. var d = this.d;
  6736. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6737. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6738. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6739. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6740. return new Plane(normalX, normalY, normalZ, finalD);
  6741. };
  6742. /**
  6743. * Returns the dot product (float) of the point coordinates and the plane normal.
  6744. */
  6745. Plane.prototype.dotCoordinate = function (point) {
  6746. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6747. };
  6748. /**
  6749. * Updates the current Plane from the plane defined by the three given points.
  6750. * Returns the updated Plane.
  6751. */
  6752. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6753. var x1 = point2.x - point1.x;
  6754. var y1 = point2.y - point1.y;
  6755. var z1 = point2.z - point1.z;
  6756. var x2 = point3.x - point1.x;
  6757. var y2 = point3.y - point1.y;
  6758. var z2 = point3.z - point1.z;
  6759. var yz = (y1 * z2) - (z1 * y2);
  6760. var xz = (z1 * x2) - (x1 * z2);
  6761. var xy = (x1 * y2) - (y1 * x2);
  6762. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6763. var invPyth;
  6764. if (pyth !== 0) {
  6765. invPyth = 1.0 / pyth;
  6766. }
  6767. else {
  6768. invPyth = 0.0;
  6769. }
  6770. this.normal.x = yz * invPyth;
  6771. this.normal.y = xz * invPyth;
  6772. this.normal.z = xy * invPyth;
  6773. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6774. return this;
  6775. };
  6776. /**
  6777. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6778. */
  6779. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6780. var dot = Vector3.Dot(this.normal, direction);
  6781. return (dot <= epsilon);
  6782. };
  6783. /**
  6784. * Returns the signed distance (float) from the given point to the Plane.
  6785. */
  6786. Plane.prototype.signedDistanceTo = function (point) {
  6787. return Vector3.Dot(point, this.normal) + this.d;
  6788. };
  6789. // Statics
  6790. /**
  6791. * Returns a new Plane from the given array.
  6792. */
  6793. Plane.FromArray = function (array) {
  6794. return new Plane(array[0], array[1], array[2], array[3]);
  6795. };
  6796. /**
  6797. * Returns a new Plane defined by the three given points.
  6798. */
  6799. Plane.FromPoints = function (point1, point2, point3) {
  6800. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6801. result.copyFromPoints(point1, point2, point3);
  6802. return result;
  6803. };
  6804. /**
  6805. * Returns a new Plane the normal vector to this plane at the given origin point.
  6806. * Note : the vector "normal" is updated because normalized.
  6807. */
  6808. Plane.FromPositionAndNormal = function (origin, normal) {
  6809. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6810. normal.normalize();
  6811. result.normal = normal;
  6812. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6813. return result;
  6814. };
  6815. /**
  6816. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6817. */
  6818. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6819. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6820. return Vector3.Dot(point, normal) + d;
  6821. };
  6822. return Plane;
  6823. }());
  6824. BABYLON.Plane = Plane;
  6825. /**
  6826. * Class used to represent a viewport on screen
  6827. */
  6828. var Viewport = /** @class */ (function () {
  6829. /**
  6830. * Creates a Viewport object located at (x, y) and sized (width, height)
  6831. * @param x defines viewport left coordinate
  6832. * @param y defines viewport top coordinate
  6833. * @param width defines the viewport width
  6834. * @param height defines the viewport height
  6835. */
  6836. function Viewport(
  6837. /** viewport left coordinate */
  6838. x,
  6839. /** viewport top coordinate */
  6840. y,
  6841. /**viewport width */
  6842. width,
  6843. /** viewport height */
  6844. height) {
  6845. this.x = x;
  6846. this.y = y;
  6847. this.width = width;
  6848. this.height = height;
  6849. }
  6850. /**
  6851. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  6852. * @param renderWidthOrEngine defines either an engine or the rendering width
  6853. * @param renderHeight defines the rendering height
  6854. * @returns a new Viewport
  6855. */
  6856. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6857. if (renderWidthOrEngine.getRenderWidth) {
  6858. var engine = renderWidthOrEngine;
  6859. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6860. }
  6861. var renderWidth = renderWidthOrEngine;
  6862. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6863. };
  6864. /**
  6865. * Returns a new Viewport copied from the current one
  6866. * @returns a new Viewport
  6867. */
  6868. Viewport.prototype.clone = function () {
  6869. return new Viewport(this.x, this.y, this.width, this.height);
  6870. };
  6871. return Viewport;
  6872. }());
  6873. BABYLON.Viewport = Viewport;
  6874. var Frustum = /** @class */ (function () {
  6875. function Frustum() {
  6876. }
  6877. /**
  6878. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6879. */
  6880. Frustum.GetPlanes = function (transform) {
  6881. var frustumPlanes = [];
  6882. for (var index = 0; index < 6; index++) {
  6883. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6884. }
  6885. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6886. return frustumPlanes;
  6887. };
  6888. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6889. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6890. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6891. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6892. frustumPlane.d = transform.m[15] + transform.m[14];
  6893. frustumPlane.normalize();
  6894. };
  6895. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6896. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6897. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6898. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6899. frustumPlane.d = transform.m[15] - transform.m[14];
  6900. frustumPlane.normalize();
  6901. };
  6902. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6903. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6904. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6905. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6906. frustumPlane.d = transform.m[15] + transform.m[12];
  6907. frustumPlane.normalize();
  6908. };
  6909. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6910. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6911. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6912. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6913. frustumPlane.d = transform.m[15] - transform.m[12];
  6914. frustumPlane.normalize();
  6915. };
  6916. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6917. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6918. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6919. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6920. frustumPlane.d = transform.m[15] - transform.m[13];
  6921. frustumPlane.normalize();
  6922. };
  6923. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6924. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6925. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6926. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6927. frustumPlane.d = transform.m[15] + transform.m[13];
  6928. frustumPlane.normalize();
  6929. };
  6930. /**
  6931. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6932. */
  6933. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6934. // Near
  6935. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6936. // Far
  6937. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6938. // Left
  6939. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6940. // Right
  6941. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6942. // Top
  6943. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6944. // Bottom
  6945. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6946. };
  6947. return Frustum;
  6948. }());
  6949. BABYLON.Frustum = Frustum;
  6950. /** Defines supported spaces */
  6951. var Space;
  6952. (function (Space) {
  6953. /** Local (object) space */
  6954. Space[Space["LOCAL"] = 0] = "LOCAL";
  6955. /** World space */
  6956. Space[Space["WORLD"] = 1] = "WORLD";
  6957. /** Bone space */
  6958. Space[Space["BONE"] = 2] = "BONE";
  6959. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6960. /** Defines the 3 main axes */
  6961. var Axis = /** @class */ (function () {
  6962. function Axis() {
  6963. }
  6964. /** X axis */
  6965. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6966. /** Y axis */
  6967. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6968. /** Z axis */
  6969. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6970. return Axis;
  6971. }());
  6972. BABYLON.Axis = Axis;
  6973. ;
  6974. /** Class used to represent a Bezier curve */
  6975. var BezierCurve = /** @class */ (function () {
  6976. function BezierCurve() {
  6977. }
  6978. /**
  6979. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  6980. * @param t defines the time
  6981. * @param x1 defines the left coordinate on X axis
  6982. * @param y1 defines the left coordinate on Y axis
  6983. * @param x2 defines the right coordinate on X axis
  6984. * @param y2 defines the right coordinate on Y axis
  6985. * @returns the interpolated value
  6986. */
  6987. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  6988. // Extract X (which is equal to time here)
  6989. var f0 = 1 - 3 * x2 + 3 * x1;
  6990. var f1 = 3 * x2 - 6 * x1;
  6991. var f2 = 3 * x1;
  6992. var refinedT = t;
  6993. for (var i = 0; i < 5; i++) {
  6994. var refinedT2 = refinedT * refinedT;
  6995. var refinedT3 = refinedT2 * refinedT;
  6996. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6997. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6998. refinedT -= (x - t) * slope;
  6999. refinedT = Math.min(1, Math.max(0, refinedT));
  7000. }
  7001. // Resolve cubic bezier for the given x
  7002. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7003. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7004. Math.pow(refinedT, 3);
  7005. };
  7006. return BezierCurve;
  7007. }());
  7008. BABYLON.BezierCurve = BezierCurve;
  7009. /**
  7010. * Defines potential orientation for back face culling
  7011. */
  7012. var Orientation;
  7013. (function (Orientation) {
  7014. /**
  7015. * Clockwise
  7016. */
  7017. Orientation[Orientation["CW"] = 0] = "CW";
  7018. /** Counter clockwise */
  7019. Orientation[Orientation["CCW"] = 1] = "CCW";
  7020. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7021. /**
  7022. * Defines angle representation
  7023. */
  7024. var Angle = /** @class */ (function () {
  7025. /**
  7026. * Creates an Angle object of "radians" radians (float).
  7027. */
  7028. function Angle(radians) {
  7029. this._radians = radians;
  7030. if (this._radians < 0.0)
  7031. this._radians += (2.0 * Math.PI);
  7032. }
  7033. /**
  7034. * Get value in degrees
  7035. * @returns the Angle value in degrees (float)
  7036. */
  7037. Angle.prototype.degrees = function () {
  7038. return this._radians * 180.0 / Math.PI;
  7039. };
  7040. /**
  7041. * Get value in radians
  7042. * @returns the Angle value in radians (float)
  7043. */
  7044. Angle.prototype.radians = function () {
  7045. return this._radians;
  7046. };
  7047. /**
  7048. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7049. * @param a defines first vector
  7050. * @param b defines second vector
  7051. * @returns a new Angle
  7052. */
  7053. Angle.BetweenTwoPoints = function (a, b) {
  7054. var delta = b.subtract(a);
  7055. var theta = Math.atan2(delta.y, delta.x);
  7056. return new Angle(theta);
  7057. };
  7058. /**
  7059. * Gets a new Angle object from the given float in radians
  7060. * @param radians defines the angle value in radians
  7061. * @returns a new Angle
  7062. */
  7063. Angle.FromRadians = function (radians) {
  7064. return new Angle(radians);
  7065. };
  7066. /**
  7067. * Gets a new Angle object from the given float in degrees
  7068. * @param degrees defines the angle value in degrees
  7069. * @returns a new Angle
  7070. */
  7071. Angle.FromDegrees = function (degrees) {
  7072. return new Angle(degrees * Math.PI / 180.0);
  7073. };
  7074. return Angle;
  7075. }());
  7076. BABYLON.Angle = Angle;
  7077. /**
  7078. * This represents an arc in a 2d space.
  7079. */
  7080. var Arc2 = /** @class */ (function () {
  7081. /**
  7082. * Creates an Arc object from the three given points : start, middle and end.
  7083. * @param startPoint Defines the start point of the arc
  7084. * @param midPoint Defines the midlle point of the arc
  7085. * @param endPoint Defines the end point of the arc
  7086. */
  7087. function Arc2(
  7088. /** Defines the start point of the arc */
  7089. startPoint,
  7090. /** Defines the mid point of the arc */
  7091. midPoint,
  7092. /** Defines the end point of the arc */
  7093. endPoint) {
  7094. this.startPoint = startPoint;
  7095. this.midPoint = midPoint;
  7096. this.endPoint = endPoint;
  7097. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7098. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7099. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7100. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7101. 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);
  7102. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7103. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7104. var a1 = this.startAngle.degrees();
  7105. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7106. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7107. // angles correction
  7108. if (a2 - a1 > +180.0)
  7109. a2 -= 360.0;
  7110. if (a2 - a1 < -180.0)
  7111. a2 += 360.0;
  7112. if (a3 - a2 > +180.0)
  7113. a3 -= 360.0;
  7114. if (a3 - a2 < -180.0)
  7115. a3 += 360.0;
  7116. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7117. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7118. }
  7119. return Arc2;
  7120. }());
  7121. BABYLON.Arc2 = Arc2;
  7122. var Path2 = /** @class */ (function () {
  7123. /**
  7124. * Creates a Path2 object from the starting 2D coordinates x and y.
  7125. */
  7126. function Path2(x, y) {
  7127. this._points = new Array();
  7128. this._length = 0.0;
  7129. this.closed = false;
  7130. this._points.push(new Vector2(x, y));
  7131. }
  7132. /**
  7133. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7134. * Returns the updated Path2.
  7135. */
  7136. Path2.prototype.addLineTo = function (x, y) {
  7137. if (this.closed) {
  7138. return this;
  7139. }
  7140. var newPoint = new Vector2(x, y);
  7141. var previousPoint = this._points[this._points.length - 1];
  7142. this._points.push(newPoint);
  7143. this._length += newPoint.subtract(previousPoint).length();
  7144. return this;
  7145. };
  7146. /**
  7147. * 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.
  7148. * Returns the updated Path2.
  7149. */
  7150. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7151. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7152. if (this.closed) {
  7153. return this;
  7154. }
  7155. var startPoint = this._points[this._points.length - 1];
  7156. var midPoint = new Vector2(midX, midY);
  7157. var endPoint = new Vector2(endX, endY);
  7158. var arc = new Arc2(startPoint, midPoint, endPoint);
  7159. var increment = arc.angle.radians() / numberOfSegments;
  7160. if (arc.orientation === Orientation.CW)
  7161. increment *= -1;
  7162. var currentAngle = arc.startAngle.radians() + increment;
  7163. for (var i = 0; i < numberOfSegments; i++) {
  7164. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7165. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7166. this.addLineTo(x, y);
  7167. currentAngle += increment;
  7168. }
  7169. return this;
  7170. };
  7171. /**
  7172. * Closes the Path2.
  7173. * Returns the Path2.
  7174. */
  7175. Path2.prototype.close = function () {
  7176. this.closed = true;
  7177. return this;
  7178. };
  7179. /**
  7180. * Returns the Path2 total length (float).
  7181. */
  7182. Path2.prototype.length = function () {
  7183. var result = this._length;
  7184. if (!this.closed) {
  7185. var lastPoint = this._points[this._points.length - 1];
  7186. var firstPoint = this._points[0];
  7187. result += (firstPoint.subtract(lastPoint).length());
  7188. }
  7189. return result;
  7190. };
  7191. /**
  7192. * Returns the Path2 internal array of points.
  7193. */
  7194. Path2.prototype.getPoints = function () {
  7195. return this._points;
  7196. };
  7197. /**
  7198. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7199. */
  7200. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7201. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7202. return Vector2.Zero();
  7203. }
  7204. var lengthPosition = normalizedLengthPosition * this.length();
  7205. var previousOffset = 0;
  7206. for (var i = 0; i < this._points.length; i++) {
  7207. var j = (i + 1) % this._points.length;
  7208. var a = this._points[i];
  7209. var b = this._points[j];
  7210. var bToA = b.subtract(a);
  7211. var nextOffset = (bToA.length() + previousOffset);
  7212. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7213. var dir = bToA.normalize();
  7214. var localOffset = lengthPosition - previousOffset;
  7215. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7216. }
  7217. previousOffset = nextOffset;
  7218. }
  7219. return Vector2.Zero();
  7220. };
  7221. /**
  7222. * Returns a new Path2 starting at the coordinates (x, y).
  7223. */
  7224. Path2.StartingAt = function (x, y) {
  7225. return new Path2(x, y);
  7226. };
  7227. return Path2;
  7228. }());
  7229. BABYLON.Path2 = Path2;
  7230. var Path3D = /** @class */ (function () {
  7231. /**
  7232. * new Path3D(path, normal, raw)
  7233. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7234. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7235. * path : an array of Vector3, the curve axis of the Path3D
  7236. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7237. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7238. */
  7239. function Path3D(path, firstNormal, raw) {
  7240. if (firstNormal === void 0) { firstNormal = null; }
  7241. this.path = path;
  7242. this._curve = new Array();
  7243. this._distances = new Array();
  7244. this._tangents = new Array();
  7245. this._normals = new Array();
  7246. this._binormals = new Array();
  7247. for (var p = 0; p < path.length; p++) {
  7248. this._curve[p] = path[p].clone(); // hard copy
  7249. }
  7250. this._raw = raw || false;
  7251. this._compute(firstNormal);
  7252. }
  7253. /**
  7254. * Returns the Path3D array of successive Vector3 designing its curve.
  7255. */
  7256. Path3D.prototype.getCurve = function () {
  7257. return this._curve;
  7258. };
  7259. /**
  7260. * Returns an array populated with tangent vectors on each Path3D curve point.
  7261. */
  7262. Path3D.prototype.getTangents = function () {
  7263. return this._tangents;
  7264. };
  7265. /**
  7266. * Returns an array populated with normal vectors on each Path3D curve point.
  7267. */
  7268. Path3D.prototype.getNormals = function () {
  7269. return this._normals;
  7270. };
  7271. /**
  7272. * Returns an array populated with binormal vectors on each Path3D curve point.
  7273. */
  7274. Path3D.prototype.getBinormals = function () {
  7275. return this._binormals;
  7276. };
  7277. /**
  7278. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7279. */
  7280. Path3D.prototype.getDistances = function () {
  7281. return this._distances;
  7282. };
  7283. /**
  7284. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7285. * Returns the same object updated.
  7286. */
  7287. Path3D.prototype.update = function (path, firstNormal) {
  7288. if (firstNormal === void 0) { firstNormal = null; }
  7289. for (var p = 0; p < path.length; p++) {
  7290. this._curve[p].x = path[p].x;
  7291. this._curve[p].y = path[p].y;
  7292. this._curve[p].z = path[p].z;
  7293. }
  7294. this._compute(firstNormal);
  7295. return this;
  7296. };
  7297. // private function compute() : computes tangents, normals and binormals
  7298. Path3D.prototype._compute = function (firstNormal) {
  7299. var l = this._curve.length;
  7300. // first and last tangents
  7301. this._tangents[0] = this._getFirstNonNullVector(0);
  7302. if (!this._raw) {
  7303. this._tangents[0].normalize();
  7304. }
  7305. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7306. if (!this._raw) {
  7307. this._tangents[l - 1].normalize();
  7308. }
  7309. // normals and binormals at first point : arbitrary vector with _normalVector()
  7310. var tg0 = this._tangents[0];
  7311. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7312. this._normals[0] = pp0;
  7313. if (!this._raw) {
  7314. this._normals[0].normalize();
  7315. }
  7316. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7317. if (!this._raw) {
  7318. this._binormals[0].normalize();
  7319. }
  7320. this._distances[0] = 0.0;
  7321. // normals and binormals : next points
  7322. var prev; // previous vector (segment)
  7323. var cur; // current vector (segment)
  7324. var curTang; // current tangent
  7325. // previous normal
  7326. var prevBinor; // previous binormal
  7327. for (var i = 1; i < l; i++) {
  7328. // tangents
  7329. prev = this._getLastNonNullVector(i);
  7330. if (i < l - 1) {
  7331. cur = this._getFirstNonNullVector(i);
  7332. this._tangents[i] = prev.add(cur);
  7333. this._tangents[i].normalize();
  7334. }
  7335. this._distances[i] = this._distances[i - 1] + prev.length();
  7336. // normals and binormals
  7337. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7338. curTang = this._tangents[i];
  7339. prevBinor = this._binormals[i - 1];
  7340. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7341. if (!this._raw) {
  7342. this._normals[i].normalize();
  7343. }
  7344. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7345. if (!this._raw) {
  7346. this._binormals[i].normalize();
  7347. }
  7348. }
  7349. };
  7350. // private function getFirstNonNullVector(index)
  7351. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7352. Path3D.prototype._getFirstNonNullVector = function (index) {
  7353. var i = 1;
  7354. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7355. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7356. i++;
  7357. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7358. }
  7359. return nNVector;
  7360. };
  7361. // private function getLastNonNullVector(index)
  7362. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7363. Path3D.prototype._getLastNonNullVector = function (index) {
  7364. var i = 1;
  7365. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7366. while (nLVector.length() === 0 && index > i + 1) {
  7367. i++;
  7368. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7369. }
  7370. return nLVector;
  7371. };
  7372. // private function normalVector(v0, vt, va) :
  7373. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7374. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7375. Path3D.prototype._normalVector = function (v0, vt, va) {
  7376. var normal0;
  7377. var tgl = vt.length();
  7378. if (tgl === 0.0) {
  7379. tgl = 1.0;
  7380. }
  7381. if (va === undefined || va === null) {
  7382. var point;
  7383. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7384. point = new Vector3(0.0, -1.0, 0.0);
  7385. }
  7386. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7387. point = new Vector3(1.0, 0.0, 0.0);
  7388. }
  7389. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7390. point = new Vector3(0.0, 0.0, 1.0);
  7391. }
  7392. else {
  7393. point = Vector3.Zero();
  7394. }
  7395. normal0 = Vector3.Cross(vt, point);
  7396. }
  7397. else {
  7398. normal0 = Vector3.Cross(vt, va);
  7399. Vector3.CrossToRef(normal0, vt, normal0);
  7400. }
  7401. normal0.normalize();
  7402. return normal0;
  7403. };
  7404. return Path3D;
  7405. }());
  7406. BABYLON.Path3D = Path3D;
  7407. var Curve3 = /** @class */ (function () {
  7408. /**
  7409. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7410. * A Curve3 is designed from a series of successive Vector3.
  7411. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7412. */
  7413. function Curve3(points) {
  7414. this._length = 0.0;
  7415. this._points = points;
  7416. this._length = this._computeLength(points);
  7417. }
  7418. /**
  7419. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7420. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7421. * @param v1 (Vector3) the control point
  7422. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7423. * @param nbPoints (integer) the wanted number of points in the curve
  7424. */
  7425. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7426. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7427. var bez = new Array();
  7428. var equation = function (t, val0, val1, val2) {
  7429. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7430. return res;
  7431. };
  7432. for (var i = 0; i <= nbPoints; i++) {
  7433. 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)));
  7434. }
  7435. return new Curve3(bez);
  7436. };
  7437. /**
  7438. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7439. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7440. * @param v1 (Vector3) the first control point
  7441. * @param v2 (Vector3) the second control point
  7442. * @param v3 (Vector3) the end point of the Cubic Bezier
  7443. * @param nbPoints (integer) the wanted number of points in the curve
  7444. */
  7445. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7446. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7447. var bez = new Array();
  7448. var equation = function (t, val0, val1, val2, val3) {
  7449. 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;
  7450. return res;
  7451. };
  7452. for (var i = 0; i <= nbPoints; i++) {
  7453. 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)));
  7454. }
  7455. return new Curve3(bez);
  7456. };
  7457. /**
  7458. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7459. * @param p1 (Vector3) the origin point of the Hermite Spline
  7460. * @param t1 (Vector3) the tangent vector at the origin point
  7461. * @param p2 (Vector3) the end point of the Hermite Spline
  7462. * @param t2 (Vector3) the tangent vector at the end point
  7463. * @param nbPoints (integer) the wanted number of points in the curve
  7464. */
  7465. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7466. var hermite = new Array();
  7467. var step = 1.0 / nbPoints;
  7468. for (var i = 0; i <= nbPoints; i++) {
  7469. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7470. }
  7471. return new Curve3(hermite);
  7472. };
  7473. /**
  7474. * Returns a Curve3 object along a CatmullRom Spline curve :
  7475. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7476. * @param nbPoints (integer) the wanted number of points between each curve control points
  7477. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7478. */
  7479. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7480. var catmullRom = new Array();
  7481. var step = 1.0 / nbPoints;
  7482. var amount = 0.0;
  7483. if (closed) {
  7484. var pointsCount = points.length;
  7485. for (var i = 0; i < pointsCount; i++) {
  7486. amount = 0;
  7487. for (var c = 0; c < nbPoints; c++) {
  7488. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7489. amount += step;
  7490. }
  7491. }
  7492. catmullRom.push(catmullRom[0]);
  7493. }
  7494. else {
  7495. var totalPoints = new Array();
  7496. totalPoints.push(points[0].clone());
  7497. Array.prototype.push.apply(totalPoints, points);
  7498. totalPoints.push(points[points.length - 1].clone());
  7499. for (var i = 0; i < totalPoints.length - 3; i++) {
  7500. amount = 0;
  7501. for (var c = 0; c < nbPoints; c++) {
  7502. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7503. amount += step;
  7504. }
  7505. }
  7506. i--;
  7507. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7508. }
  7509. return new Curve3(catmullRom);
  7510. };
  7511. /**
  7512. * Returns the Curve3 stored array of successive Vector3
  7513. */
  7514. Curve3.prototype.getPoints = function () {
  7515. return this._points;
  7516. };
  7517. /**
  7518. * Returns the computed length (float) of the curve.
  7519. */
  7520. Curve3.prototype.length = function () {
  7521. return this._length;
  7522. };
  7523. /**
  7524. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7525. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7526. * curveA and curveB keep unchanged.
  7527. */
  7528. Curve3.prototype.continue = function (curve) {
  7529. var lastPoint = this._points[this._points.length - 1];
  7530. var continuedPoints = this._points.slice();
  7531. var curvePoints = curve.getPoints();
  7532. for (var i = 1; i < curvePoints.length; i++) {
  7533. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7534. }
  7535. var continuedCurve = new Curve3(continuedPoints);
  7536. return continuedCurve;
  7537. };
  7538. Curve3.prototype._computeLength = function (path) {
  7539. var l = 0;
  7540. for (var i = 1; i < path.length; i++) {
  7541. l += (path[i].subtract(path[i - 1])).length();
  7542. }
  7543. return l;
  7544. };
  7545. return Curve3;
  7546. }());
  7547. BABYLON.Curve3 = Curve3;
  7548. // Vertex formats
  7549. var PositionNormalVertex = /** @class */ (function () {
  7550. function PositionNormalVertex(position, normal) {
  7551. if (position === void 0) { position = Vector3.Zero(); }
  7552. if (normal === void 0) { normal = Vector3.Up(); }
  7553. this.position = position;
  7554. this.normal = normal;
  7555. }
  7556. PositionNormalVertex.prototype.clone = function () {
  7557. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7558. };
  7559. return PositionNormalVertex;
  7560. }());
  7561. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7562. var PositionNormalTextureVertex = /** @class */ (function () {
  7563. function PositionNormalTextureVertex(position, normal, uv) {
  7564. if (position === void 0) { position = Vector3.Zero(); }
  7565. if (normal === void 0) { normal = Vector3.Up(); }
  7566. if (uv === void 0) { uv = Vector2.Zero(); }
  7567. this.position = position;
  7568. this.normal = normal;
  7569. this.uv = uv;
  7570. }
  7571. PositionNormalTextureVertex.prototype.clone = function () {
  7572. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7573. };
  7574. return PositionNormalTextureVertex;
  7575. }());
  7576. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7577. // Temporary pre-allocated objects for engine internal use
  7578. // usage in any internal function :
  7579. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7580. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7581. var Tmp = /** @class */ (function () {
  7582. function Tmp() {
  7583. }
  7584. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7585. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7586. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7587. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7588. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7589. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7590. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7591. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7592. Matrix.Zero(), Matrix.Zero(),
  7593. Matrix.Zero(), Matrix.Zero(),
  7594. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7595. return Tmp;
  7596. }());
  7597. BABYLON.Tmp = Tmp;
  7598. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7599. var MathTmp = /** @class */ (function () {
  7600. function MathTmp() {
  7601. }
  7602. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7603. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7604. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7605. return MathTmp;
  7606. }());
  7607. })(BABYLON || (BABYLON = {}));
  7608. //# sourceMappingURL=babylon.math.js.map
  7609. var BABYLON;
  7610. (function (BABYLON) {
  7611. var Scalar = /** @class */ (function () {
  7612. function Scalar() {
  7613. }
  7614. /**
  7615. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7616. */
  7617. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7618. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7619. var num = a - b;
  7620. return -epsilon <= num && num <= epsilon;
  7621. };
  7622. /**
  7623. * Returns a string : the upper case translation of the number i to hexadecimal.
  7624. */
  7625. Scalar.ToHex = function (i) {
  7626. var str = i.toString(16);
  7627. if (i <= 15) {
  7628. return ("0" + str).toUpperCase();
  7629. }
  7630. return str.toUpperCase();
  7631. };
  7632. /**
  7633. * Returns -1 if value is negative and +1 is value is positive.
  7634. * Returns the value itself if it's equal to zero.
  7635. */
  7636. Scalar.Sign = function (value) {
  7637. value = +value; // convert to a number
  7638. if (value === 0 || isNaN(value))
  7639. return value;
  7640. return value > 0 ? 1 : -1;
  7641. };
  7642. /**
  7643. * Returns the value itself if it's between min and max.
  7644. * Returns min if the value is lower than min.
  7645. * Returns max if the value is greater than max.
  7646. */
  7647. Scalar.Clamp = function (value, min, max) {
  7648. if (min === void 0) { min = 0; }
  7649. if (max === void 0) { max = 1; }
  7650. return Math.min(max, Math.max(min, value));
  7651. };
  7652. /**
  7653. * Returns the log2 of value.
  7654. */
  7655. Scalar.Log2 = function (value) {
  7656. return Math.log(value) * Math.LOG2E;
  7657. };
  7658. /**
  7659. * Loops the value, so that it is never larger than length and never smaller than 0.
  7660. *
  7661. * This is similar to the modulo operator but it works with floating point numbers.
  7662. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7663. * With t = 5 and length = 2.5, the result would be 0.0.
  7664. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7665. */
  7666. Scalar.Repeat = function (value, length) {
  7667. return value - Math.floor(value / length) * length;
  7668. };
  7669. /**
  7670. * Normalize the value between 0.0 and 1.0 using min and max values
  7671. */
  7672. Scalar.Normalize = function (value, min, max) {
  7673. return (value - min) / (max - min);
  7674. };
  7675. /**
  7676. * Denormalize the value from 0.0 and 1.0 using min and max values
  7677. */
  7678. Scalar.Denormalize = function (normalized, min, max) {
  7679. return (normalized * (max - min) + min);
  7680. };
  7681. /**
  7682. * Calculates the shortest difference between two given angles given in degrees.
  7683. */
  7684. Scalar.DeltaAngle = function (current, target) {
  7685. var num = Scalar.Repeat(target - current, 360.0);
  7686. if (num > 180.0) {
  7687. num -= 360.0;
  7688. }
  7689. return num;
  7690. };
  7691. /**
  7692. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7693. *
  7694. * The returned value will move back and forth between 0 and length
  7695. */
  7696. Scalar.PingPong = function (tx, length) {
  7697. var t = Scalar.Repeat(tx, length * 2.0);
  7698. return length - Math.abs(t - length);
  7699. };
  7700. /**
  7701. * Interpolates between min and max with smoothing at the limits.
  7702. *
  7703. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7704. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7705. */
  7706. Scalar.SmoothStep = function (from, to, tx) {
  7707. var t = Scalar.Clamp(tx);
  7708. t = -2.0 * t * t * t + 3.0 * t * t;
  7709. return to * t + from * (1.0 - t);
  7710. };
  7711. /**
  7712. * Moves a value current towards target.
  7713. *
  7714. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7715. * Negative values of maxDelta pushes the value away from target.
  7716. */
  7717. Scalar.MoveTowards = function (current, target, maxDelta) {
  7718. var result = 0;
  7719. if (Math.abs(target - current) <= maxDelta) {
  7720. result = target;
  7721. }
  7722. else {
  7723. result = current + Scalar.Sign(target - current) * maxDelta;
  7724. }
  7725. return result;
  7726. };
  7727. /**
  7728. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7729. *
  7730. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7731. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7732. */
  7733. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7734. var num = Scalar.DeltaAngle(current, target);
  7735. var result = 0;
  7736. if (-maxDelta < num && num < maxDelta) {
  7737. result = target;
  7738. }
  7739. else {
  7740. target = current + num;
  7741. result = Scalar.MoveTowards(current, target, maxDelta);
  7742. }
  7743. return result;
  7744. };
  7745. /**
  7746. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7747. */
  7748. Scalar.Lerp = function (start, end, amount) {
  7749. return start + ((end - start) * amount);
  7750. };
  7751. /**
  7752. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7753. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7754. */
  7755. Scalar.LerpAngle = function (start, end, amount) {
  7756. var num = Scalar.Repeat(end - start, 360.0);
  7757. if (num > 180.0) {
  7758. num -= 360.0;
  7759. }
  7760. return start + num * Scalar.Clamp(amount);
  7761. };
  7762. /**
  7763. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7764. */
  7765. Scalar.InverseLerp = function (a, b, value) {
  7766. var result = 0;
  7767. if (a != b) {
  7768. result = Scalar.Clamp((value - a) / (b - a));
  7769. }
  7770. else {
  7771. result = 0.0;
  7772. }
  7773. return result;
  7774. };
  7775. /**
  7776. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7777. */
  7778. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7779. var squared = amount * amount;
  7780. var cubed = amount * squared;
  7781. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7782. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7783. var part3 = (cubed - (2.0 * squared)) + amount;
  7784. var part4 = cubed - squared;
  7785. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7786. };
  7787. /**
  7788. * Returns a random float number between and min and max values
  7789. */
  7790. Scalar.RandomRange = function (min, max) {
  7791. if (min === max)
  7792. return min;
  7793. return ((Math.random() * (max - min)) + min);
  7794. };
  7795. /**
  7796. * This function returns percentage of a number in a given range.
  7797. *
  7798. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7799. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7800. */
  7801. Scalar.RangeToPercent = function (number, min, max) {
  7802. return ((number - min) / (max - min));
  7803. };
  7804. /**
  7805. * This function returns number that corresponds to the percentage in a given range.
  7806. *
  7807. * PercentToRange(0.34,0,100) will return 34.
  7808. */
  7809. Scalar.PercentToRange = function (percent, min, max) {
  7810. return ((max - min) * percent + min);
  7811. };
  7812. /**
  7813. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7814. * @param angle The angle to normalize in radian.
  7815. * @return The converted angle.
  7816. */
  7817. Scalar.NormalizeRadians = function (angle) {
  7818. // More precise but slower version kept for reference.
  7819. // angle = angle % Tools.TwoPi;
  7820. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7821. //if (angle > Math.PI) {
  7822. // angle -= Tools.TwoPi;
  7823. //}
  7824. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7825. return angle;
  7826. };
  7827. /**
  7828. * Two pi constants convenient for computation.
  7829. */
  7830. Scalar.TwoPi = Math.PI * 2;
  7831. return Scalar;
  7832. }());
  7833. BABYLON.Scalar = Scalar;
  7834. })(BABYLON || (BABYLON = {}));
  7835. //# sourceMappingURL=babylon.math.scalar.js.map
  7836. //# sourceMappingURL=babylon.mixins.js.map
  7837. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7838. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7839. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7840. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7841. //# sourceMappingURL=babylon.webgl2.js.map
  7842. var BABYLON;
  7843. (function (BABYLON) {
  7844. var __decoratorInitialStore = {};
  7845. var __mergedStore = {};
  7846. var _copySource = function (creationFunction, source, instanciate) {
  7847. var destination = creationFunction();
  7848. // Tags
  7849. if (BABYLON.Tags) {
  7850. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7851. }
  7852. var classStore = getMergedStore(destination);
  7853. // Properties
  7854. for (var property in classStore) {
  7855. var propertyDescriptor = classStore[property];
  7856. var sourceProperty = source[property];
  7857. var propertyType = propertyDescriptor.type;
  7858. if (sourceProperty !== undefined && sourceProperty !== null) {
  7859. switch (propertyType) {
  7860. case 0: // Value
  7861. case 6: // Mesh reference
  7862. case 11: // Camera reference
  7863. destination[property] = sourceProperty;
  7864. break;
  7865. case 1: // Texture
  7866. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7867. break;
  7868. case 2: // Color3
  7869. case 3: // FresnelParameters
  7870. case 4: // Vector2
  7871. case 5: // Vector3
  7872. case 7: // Color Curves
  7873. case 10: // Quaternion
  7874. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7875. break;
  7876. }
  7877. }
  7878. }
  7879. return destination;
  7880. };
  7881. function getDirectStore(target) {
  7882. var classKey = target.getClassName();
  7883. if (!__decoratorInitialStore[classKey]) {
  7884. __decoratorInitialStore[classKey] = {};
  7885. }
  7886. return __decoratorInitialStore[classKey];
  7887. }
  7888. /**
  7889. * Return the list of properties flagged as serializable
  7890. * @param target: host object
  7891. */
  7892. function getMergedStore(target) {
  7893. var classKey = target.getClassName();
  7894. if (__mergedStore[classKey]) {
  7895. return __mergedStore[classKey];
  7896. }
  7897. __mergedStore[classKey] = {};
  7898. var store = __mergedStore[classKey];
  7899. var currentTarget = target;
  7900. var currentKey = classKey;
  7901. while (currentKey) {
  7902. var initialStore = __decoratorInitialStore[currentKey];
  7903. for (var property in initialStore) {
  7904. store[property] = initialStore[property];
  7905. }
  7906. var parent_1 = void 0;
  7907. var done = false;
  7908. do {
  7909. parent_1 = Object.getPrototypeOf(currentTarget);
  7910. if (!parent_1.getClassName) {
  7911. done = true;
  7912. break;
  7913. }
  7914. if (parent_1.getClassName() !== currentKey) {
  7915. break;
  7916. }
  7917. currentTarget = parent_1;
  7918. } while (parent_1);
  7919. if (done) {
  7920. break;
  7921. }
  7922. currentKey = parent_1.getClassName();
  7923. currentTarget = parent_1;
  7924. }
  7925. return store;
  7926. }
  7927. function generateSerializableMember(type, sourceName) {
  7928. return function (target, propertyKey) {
  7929. var classStore = getDirectStore(target);
  7930. if (!classStore[propertyKey]) {
  7931. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7932. }
  7933. };
  7934. }
  7935. function generateExpandMember(setCallback, targetKey) {
  7936. if (targetKey === void 0) { targetKey = null; }
  7937. return function (target, propertyKey) {
  7938. var key = targetKey || ("_" + propertyKey);
  7939. Object.defineProperty(target, propertyKey, {
  7940. get: function () {
  7941. return this[key];
  7942. },
  7943. set: function (value) {
  7944. if (this[key] === value) {
  7945. return;
  7946. }
  7947. this[key] = value;
  7948. target[setCallback].apply(this);
  7949. },
  7950. enumerable: true,
  7951. configurable: true
  7952. });
  7953. };
  7954. }
  7955. function expandToProperty(callback, targetKey) {
  7956. if (targetKey === void 0) { targetKey = null; }
  7957. return generateExpandMember(callback, targetKey);
  7958. }
  7959. BABYLON.expandToProperty = expandToProperty;
  7960. function serialize(sourceName) {
  7961. return generateSerializableMember(0, sourceName); // value member
  7962. }
  7963. BABYLON.serialize = serialize;
  7964. function serializeAsTexture(sourceName) {
  7965. return generateSerializableMember(1, sourceName); // texture member
  7966. }
  7967. BABYLON.serializeAsTexture = serializeAsTexture;
  7968. function serializeAsColor3(sourceName) {
  7969. return generateSerializableMember(2, sourceName); // color3 member
  7970. }
  7971. BABYLON.serializeAsColor3 = serializeAsColor3;
  7972. function serializeAsFresnelParameters(sourceName) {
  7973. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7974. }
  7975. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7976. function serializeAsVector2(sourceName) {
  7977. return generateSerializableMember(4, sourceName); // vector2 member
  7978. }
  7979. BABYLON.serializeAsVector2 = serializeAsVector2;
  7980. function serializeAsVector3(sourceName) {
  7981. return generateSerializableMember(5, sourceName); // vector3 member
  7982. }
  7983. BABYLON.serializeAsVector3 = serializeAsVector3;
  7984. function serializeAsMeshReference(sourceName) {
  7985. return generateSerializableMember(6, sourceName); // mesh reference member
  7986. }
  7987. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7988. function serializeAsColorCurves(sourceName) {
  7989. return generateSerializableMember(7, sourceName); // color curves
  7990. }
  7991. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7992. function serializeAsColor4(sourceName) {
  7993. return generateSerializableMember(8, sourceName); // color 4
  7994. }
  7995. BABYLON.serializeAsColor4 = serializeAsColor4;
  7996. function serializeAsImageProcessingConfiguration(sourceName) {
  7997. return generateSerializableMember(9, sourceName); // image processing
  7998. }
  7999. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8000. function serializeAsQuaternion(sourceName) {
  8001. return generateSerializableMember(10, sourceName); // quaternion member
  8002. }
  8003. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8004. /**
  8005. * Decorator used to define property that can be serialized as reference to a camera
  8006. * @param sourceName defines the name of the property to decorate
  8007. */
  8008. function serializeAsCameraReference(sourceName) {
  8009. return generateSerializableMember(11, sourceName); // camera reference member
  8010. }
  8011. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8012. var SerializationHelper = /** @class */ (function () {
  8013. function SerializationHelper() {
  8014. }
  8015. SerializationHelper.Serialize = function (entity, serializationObject) {
  8016. if (!serializationObject) {
  8017. serializationObject = {};
  8018. }
  8019. // Tags
  8020. if (BABYLON.Tags) {
  8021. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8022. }
  8023. var serializedProperties = getMergedStore(entity);
  8024. // Properties
  8025. for (var property in serializedProperties) {
  8026. var propertyDescriptor = serializedProperties[property];
  8027. var targetPropertyName = propertyDescriptor.sourceName || property;
  8028. var propertyType = propertyDescriptor.type;
  8029. var sourceProperty = entity[property];
  8030. if (sourceProperty !== undefined && sourceProperty !== null) {
  8031. switch (propertyType) {
  8032. case 0: // Value
  8033. serializationObject[targetPropertyName] = sourceProperty;
  8034. break;
  8035. case 1: // Texture
  8036. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8037. break;
  8038. case 2: // Color3
  8039. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8040. break;
  8041. case 3: // FresnelParameters
  8042. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8043. break;
  8044. case 4: // Vector2
  8045. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8046. break;
  8047. case 5: // Vector3
  8048. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8049. break;
  8050. case 6: // Mesh reference
  8051. serializationObject[targetPropertyName] = sourceProperty.id;
  8052. break;
  8053. case 7: // Color Curves
  8054. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8055. break;
  8056. case 8: // Color 4
  8057. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8058. break;
  8059. case 9: // Image Processing
  8060. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8061. break;
  8062. case 10: // Quaternion
  8063. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8064. break;
  8065. case 11: // Camera reference
  8066. serializationObject[targetPropertyName] = sourceProperty.id;
  8067. break;
  8068. }
  8069. }
  8070. }
  8071. return serializationObject;
  8072. };
  8073. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8074. if (rootUrl === void 0) { rootUrl = null; }
  8075. var destination = creationFunction();
  8076. if (!rootUrl) {
  8077. rootUrl = "";
  8078. }
  8079. // Tags
  8080. if (BABYLON.Tags) {
  8081. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8082. }
  8083. var classStore = getMergedStore(destination);
  8084. // Properties
  8085. for (var property in classStore) {
  8086. var propertyDescriptor = classStore[property];
  8087. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8088. var propertyType = propertyDescriptor.type;
  8089. if (sourceProperty !== undefined && sourceProperty !== null) {
  8090. var dest = destination;
  8091. switch (propertyType) {
  8092. case 0: // Value
  8093. dest[property] = sourceProperty;
  8094. break;
  8095. case 1: // Texture
  8096. if (scene) {
  8097. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8098. }
  8099. break;
  8100. case 2: // Color3
  8101. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8102. break;
  8103. case 3: // FresnelParameters
  8104. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8105. break;
  8106. case 4: // Vector2
  8107. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8108. break;
  8109. case 5: // Vector3
  8110. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8111. break;
  8112. case 6: // Mesh reference
  8113. if (scene) {
  8114. dest[property] = scene.getLastMeshByID(sourceProperty);
  8115. }
  8116. break;
  8117. case 7: // Color Curves
  8118. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8119. break;
  8120. case 8: // Color 4
  8121. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8122. break;
  8123. case 9: // Image Processing
  8124. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8125. break;
  8126. case 10: // Quaternion
  8127. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8128. break;
  8129. case 11: // Camera reference
  8130. if (scene) {
  8131. dest[property] = scene.getCameraByID(sourceProperty);
  8132. }
  8133. break;
  8134. }
  8135. }
  8136. }
  8137. return destination;
  8138. };
  8139. SerializationHelper.Clone = function (creationFunction, source) {
  8140. return _copySource(creationFunction, source, false);
  8141. };
  8142. SerializationHelper.Instanciate = function (creationFunction, source) {
  8143. return _copySource(creationFunction, source, true);
  8144. };
  8145. return SerializationHelper;
  8146. }());
  8147. BABYLON.SerializationHelper = SerializationHelper;
  8148. })(BABYLON || (BABYLON = {}));
  8149. //# sourceMappingURL=babylon.decorators.js.map
  8150. var BABYLON;
  8151. (function (BABYLON) {
  8152. /**
  8153. * Wrapper class for promise with external resolve and reject.
  8154. */
  8155. var Deferred = /** @class */ (function () {
  8156. /**
  8157. * Constructor for this deferred object.
  8158. */
  8159. function Deferred() {
  8160. var _this = this;
  8161. this.promise = new Promise(function (resolve, reject) {
  8162. _this._resolve = resolve;
  8163. _this._reject = reject;
  8164. });
  8165. }
  8166. Object.defineProperty(Deferred.prototype, "resolve", {
  8167. /**
  8168. * The resolve method of the promise associated with this deferred object.
  8169. */
  8170. get: function () {
  8171. return this._resolve;
  8172. },
  8173. enumerable: true,
  8174. configurable: true
  8175. });
  8176. Object.defineProperty(Deferred.prototype, "reject", {
  8177. /**
  8178. * The reject method of the promise associated with this deferred object.
  8179. */
  8180. get: function () {
  8181. return this._reject;
  8182. },
  8183. enumerable: true,
  8184. configurable: true
  8185. });
  8186. return Deferred;
  8187. }());
  8188. BABYLON.Deferred = Deferred;
  8189. })(BABYLON || (BABYLON = {}));
  8190. //# sourceMappingURL=babylon.deferred.js.map
  8191. var BABYLON;
  8192. (function (BABYLON) {
  8193. /**
  8194. * A class serves as a medium between the observable and its observers
  8195. */
  8196. var EventState = /** @class */ (function () {
  8197. /**
  8198. * Create a new EventState
  8199. * @param mask defines the mask associated with this state
  8200. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8201. * @param target defines the original target of the state
  8202. * @param currentTarget defines the current target of the state
  8203. */
  8204. function EventState(mask, skipNextObservers, target, currentTarget) {
  8205. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8206. this.initalize(mask, skipNextObservers, target, currentTarget);
  8207. }
  8208. /**
  8209. * Initialize the current event state
  8210. * @param mask defines the mask associated with this state
  8211. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8212. * @param target defines the original target of the state
  8213. * @param currentTarget defines the current target of the state
  8214. * @returns the current event state
  8215. */
  8216. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8217. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8218. this.mask = mask;
  8219. this.skipNextObservers = skipNextObservers;
  8220. this.target = target;
  8221. this.currentTarget = currentTarget;
  8222. return this;
  8223. };
  8224. return EventState;
  8225. }());
  8226. BABYLON.EventState = EventState;
  8227. /**
  8228. * Represent an Observer registered to a given Observable object.
  8229. */
  8230. var Observer = /** @class */ (function () {
  8231. /**
  8232. * Creates a new observer
  8233. * @param callback defines the callback to call when the observer is notified
  8234. * @param mask defines the mask of the observer (used to filter notifications)
  8235. * @param scope defines the current scope used to restore the JS context
  8236. */
  8237. function Observer(
  8238. /**
  8239. * Defines the callback to call when the observer is notified
  8240. */
  8241. callback,
  8242. /**
  8243. * Defines the mask of the observer (used to filter notifications)
  8244. */
  8245. mask,
  8246. /**
  8247. * Defines the current scope used to restore the JS context
  8248. */
  8249. scope) {
  8250. if (scope === void 0) { scope = null; }
  8251. this.callback = callback;
  8252. this.mask = mask;
  8253. this.scope = scope;
  8254. /** @hidden */
  8255. this._willBeUnregistered = false;
  8256. /**
  8257. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8258. */
  8259. this.unregisterOnNextCall = false;
  8260. }
  8261. return Observer;
  8262. }());
  8263. BABYLON.Observer = Observer;
  8264. /**
  8265. * Represent a list of observers registered to multiple Observables object.
  8266. */
  8267. var MultiObserver = /** @class */ (function () {
  8268. function MultiObserver() {
  8269. }
  8270. /**
  8271. * Release associated resources
  8272. */
  8273. MultiObserver.prototype.dispose = function () {
  8274. if (this._observers && this._observables) {
  8275. for (var index = 0; index < this._observers.length; index++) {
  8276. this._observables[index].remove(this._observers[index]);
  8277. }
  8278. }
  8279. this._observers = null;
  8280. this._observables = null;
  8281. };
  8282. /**
  8283. * Raise a callback when one of the observable will notify
  8284. * @param observables defines a list of observables to watch
  8285. * @param callback defines the callback to call on notification
  8286. * @param mask defines the mask used to filter notifications
  8287. * @param scope defines the current scope used to restore the JS context
  8288. * @returns the new MultiObserver
  8289. */
  8290. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8291. if (mask === void 0) { mask = -1; }
  8292. if (scope === void 0) { scope = null; }
  8293. var result = new MultiObserver();
  8294. result._observers = new Array();
  8295. result._observables = observables;
  8296. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8297. var observable = observables_1[_i];
  8298. var observer = observable.add(callback, mask, false, scope);
  8299. if (observer) {
  8300. result._observers.push(observer);
  8301. }
  8302. }
  8303. return result;
  8304. };
  8305. return MultiObserver;
  8306. }());
  8307. BABYLON.MultiObserver = MultiObserver;
  8308. /**
  8309. * The Observable class is a simple implementation of the Observable pattern.
  8310. *
  8311. * 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.
  8312. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8313. * 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).
  8314. * 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.
  8315. */
  8316. var Observable = /** @class */ (function () {
  8317. /**
  8318. * Creates a new observable
  8319. * @param onObserverAdded defines a callback to call when a new observer is added
  8320. */
  8321. function Observable(onObserverAdded) {
  8322. this._observers = new Array();
  8323. this._eventState = new EventState(0);
  8324. if (onObserverAdded) {
  8325. this._onObserverAdded = onObserverAdded;
  8326. }
  8327. }
  8328. /**
  8329. * Create a new Observer with the specified callback
  8330. * @param callback the callback that will be executed for that Observer
  8331. * @param mask the mask used to filter observers
  8332. * @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.
  8333. * @param scope optional scope for the callback to be called from
  8334. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8335. * @returns the new observer created for the callback
  8336. */
  8337. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8338. if (mask === void 0) { mask = -1; }
  8339. if (insertFirst === void 0) { insertFirst = false; }
  8340. if (scope === void 0) { scope = null; }
  8341. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8342. if (!callback) {
  8343. return null;
  8344. }
  8345. var observer = new Observer(callback, mask, scope);
  8346. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8347. if (insertFirst) {
  8348. this._observers.unshift(observer);
  8349. }
  8350. else {
  8351. this._observers.push(observer);
  8352. }
  8353. if (this._onObserverAdded) {
  8354. this._onObserverAdded(observer);
  8355. }
  8356. return observer;
  8357. };
  8358. /**
  8359. * Create a new Observer with the specified callback and unregisters after the next notification
  8360. * @param callback the callback that will be executed for that Observer
  8361. * @returns the new observer created for the callback
  8362. */
  8363. Observable.prototype.addOnce = function (callback) {
  8364. return this.add(callback, undefined, undefined, undefined, true);
  8365. };
  8366. /**
  8367. * Remove an Observer from the Observable object
  8368. * @param observer the instance of the Observer to remove
  8369. * @returns false if it doesn't belong to this Observable
  8370. */
  8371. Observable.prototype.remove = function (observer) {
  8372. if (!observer) {
  8373. return false;
  8374. }
  8375. var index = this._observers.indexOf(observer);
  8376. if (index !== -1) {
  8377. this._deferUnregister(observer);
  8378. return true;
  8379. }
  8380. return false;
  8381. };
  8382. /**
  8383. * Remove a callback from the Observable object
  8384. * @param callback the callback to remove
  8385. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8386. * @returns false if it doesn't belong to this Observable
  8387. */
  8388. Observable.prototype.removeCallback = function (callback, scope) {
  8389. for (var index = 0; index < this._observers.length; index++) {
  8390. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8391. this._deferUnregister(this._observers[index]);
  8392. return true;
  8393. }
  8394. }
  8395. return false;
  8396. };
  8397. Observable.prototype._deferUnregister = function (observer) {
  8398. var _this = this;
  8399. observer.unregisterOnNextCall = false;
  8400. observer._willBeUnregistered = true;
  8401. BABYLON.Tools.SetImmediate(function () {
  8402. _this._remove(observer);
  8403. });
  8404. };
  8405. // This should only be called when not iterating over _observers to avoid callback skipping.
  8406. // Removes an observer from the _observer Array.
  8407. Observable.prototype._remove = function (observer) {
  8408. if (!observer) {
  8409. return false;
  8410. }
  8411. var index = this._observers.indexOf(observer);
  8412. if (index !== -1) {
  8413. this._observers.splice(index, 1);
  8414. return true;
  8415. }
  8416. return false;
  8417. };
  8418. /**
  8419. * Notify all Observers by calling their respective callback with the given data
  8420. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8421. * @param eventData defines the data to send to all observers
  8422. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8423. * @param target defines the original target of the state
  8424. * @param currentTarget defines the current target of the state
  8425. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8426. */
  8427. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8428. if (mask === void 0) { mask = -1; }
  8429. if (!this._observers.length) {
  8430. return true;
  8431. }
  8432. var state = this._eventState;
  8433. state.mask = mask;
  8434. state.target = target;
  8435. state.currentTarget = currentTarget;
  8436. state.skipNextObservers = false;
  8437. state.lastReturnValue = eventData;
  8438. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8439. var obs = _a[_i];
  8440. if (obs._willBeUnregistered) {
  8441. continue;
  8442. }
  8443. if (obs.mask & mask) {
  8444. if (obs.scope) {
  8445. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8446. }
  8447. else {
  8448. state.lastReturnValue = obs.callback(eventData, state);
  8449. }
  8450. if (obs.unregisterOnNextCall) {
  8451. this._deferUnregister(obs);
  8452. }
  8453. }
  8454. if (state.skipNextObservers) {
  8455. return false;
  8456. }
  8457. }
  8458. return true;
  8459. };
  8460. /**
  8461. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8462. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8463. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8464. * and it is crucial that all callbacks will be executed.
  8465. * The order of the callbacks is kept, callbacks are not executed parallel.
  8466. *
  8467. * @param eventData The data to be sent to each callback
  8468. * @param mask is used to filter observers defaults to -1
  8469. * @param target defines the callback target (see EventState)
  8470. * @param currentTarget defines he current object in the bubbling phase
  8471. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8472. */
  8473. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8474. var _this = this;
  8475. if (mask === void 0) { mask = -1; }
  8476. // create an empty promise
  8477. var p = Promise.resolve(eventData);
  8478. // no observers? return this promise.
  8479. if (!this._observers.length) {
  8480. return p;
  8481. }
  8482. var state = this._eventState;
  8483. state.mask = mask;
  8484. state.target = target;
  8485. state.currentTarget = currentTarget;
  8486. state.skipNextObservers = false;
  8487. // execute one callback after another (not using Promise.all, the order is important)
  8488. this._observers.forEach(function (obs) {
  8489. if (state.skipNextObservers) {
  8490. return;
  8491. }
  8492. if (obs._willBeUnregistered) {
  8493. return;
  8494. }
  8495. if (obs.mask & mask) {
  8496. if (obs.scope) {
  8497. p = p.then(function (lastReturnedValue) {
  8498. state.lastReturnValue = lastReturnedValue;
  8499. return obs.callback.apply(obs.scope, [eventData, state]);
  8500. });
  8501. }
  8502. else {
  8503. p = p.then(function (lastReturnedValue) {
  8504. state.lastReturnValue = lastReturnedValue;
  8505. return obs.callback(eventData, state);
  8506. });
  8507. }
  8508. if (obs.unregisterOnNextCall) {
  8509. _this._deferUnregister(obs);
  8510. }
  8511. }
  8512. });
  8513. // return the eventData
  8514. return p.then(function () { return eventData; });
  8515. };
  8516. /**
  8517. * Notify a specific observer
  8518. * @param observer defines the observer to notify
  8519. * @param eventData defines the data to be sent to each callback
  8520. * @param mask is used to filter observers defaults to -1
  8521. */
  8522. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8523. if (mask === void 0) { mask = -1; }
  8524. var state = this._eventState;
  8525. state.mask = mask;
  8526. state.skipNextObservers = false;
  8527. observer.callback(eventData, state);
  8528. };
  8529. /**
  8530. * Gets a boolean indicating if the observable has at least one observer
  8531. * @returns true is the Observable has at least one Observer registered
  8532. */
  8533. Observable.prototype.hasObservers = function () {
  8534. return this._observers.length > 0;
  8535. };
  8536. /**
  8537. * Clear the list of observers
  8538. */
  8539. Observable.prototype.clear = function () {
  8540. this._observers = new Array();
  8541. this._onObserverAdded = null;
  8542. };
  8543. /**
  8544. * Clone the current observable
  8545. * @returns a new observable
  8546. */
  8547. Observable.prototype.clone = function () {
  8548. var result = new Observable();
  8549. result._observers = this._observers.slice(0);
  8550. return result;
  8551. };
  8552. /**
  8553. * Does this observable handles observer registered with a given mask
  8554. * @param mask defines the mask to be tested
  8555. * @return whether or not one observer registered with the given mask is handeled
  8556. **/
  8557. Observable.prototype.hasSpecificMask = function (mask) {
  8558. if (mask === void 0) { mask = -1; }
  8559. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8560. var obs = _a[_i];
  8561. if (obs.mask & mask || obs.mask === mask) {
  8562. return true;
  8563. }
  8564. }
  8565. return false;
  8566. };
  8567. return Observable;
  8568. }());
  8569. BABYLON.Observable = Observable;
  8570. })(BABYLON || (BABYLON = {}));
  8571. //# sourceMappingURL=babylon.observable.js.map
  8572. var BABYLON;
  8573. (function (BABYLON) {
  8574. /**
  8575. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8576. */
  8577. var SmartArray = /** @class */ (function () {
  8578. /**
  8579. * Instantiates a Smart Array.
  8580. * @param capacity defines the default capacity of the array.
  8581. */
  8582. function SmartArray(capacity) {
  8583. /**
  8584. * The active length of the array.
  8585. */
  8586. this.length = 0;
  8587. this.data = new Array(capacity);
  8588. this._id = SmartArray._GlobalId++;
  8589. }
  8590. /**
  8591. * Pushes a value at the end of the active data.
  8592. * @param value defines the object to push in the array.
  8593. */
  8594. SmartArray.prototype.push = function (value) {
  8595. this.data[this.length++] = value;
  8596. if (this.length > this.data.length) {
  8597. this.data.length *= 2;
  8598. }
  8599. };
  8600. /**
  8601. * Iterates over the active data and apply the lambda to them.
  8602. * @param func defines the action to apply on each value.
  8603. */
  8604. SmartArray.prototype.forEach = function (func) {
  8605. for (var index = 0; index < this.length; index++) {
  8606. func(this.data[index]);
  8607. }
  8608. };
  8609. /**
  8610. * Sorts the full sets of data.
  8611. * @param compareFn defines the comparison function to apply.
  8612. */
  8613. SmartArray.prototype.sort = function (compareFn) {
  8614. this.data.sort(compareFn);
  8615. };
  8616. /**
  8617. * Resets the active data to an empty array.
  8618. */
  8619. SmartArray.prototype.reset = function () {
  8620. this.length = 0;
  8621. };
  8622. /**
  8623. * Releases all the data from the array as well as the array.
  8624. */
  8625. SmartArray.prototype.dispose = function () {
  8626. this.reset();
  8627. if (this.data) {
  8628. this.data.length = 0;
  8629. this.data = [];
  8630. }
  8631. };
  8632. /**
  8633. * Concats the active data with a given array.
  8634. * @param array defines the data to concatenate with.
  8635. */
  8636. SmartArray.prototype.concat = function (array) {
  8637. if (array.length === 0) {
  8638. return;
  8639. }
  8640. if (this.length + array.length > this.data.length) {
  8641. this.data.length = (this.length + array.length) * 2;
  8642. }
  8643. for (var index = 0; index < array.length; index++) {
  8644. this.data[this.length++] = (array.data || array)[index];
  8645. }
  8646. };
  8647. /**
  8648. * Returns the position of a value in the active data.
  8649. * @param value defines the value to find the index for
  8650. * @returns the index if found in the active data otherwise -1
  8651. */
  8652. SmartArray.prototype.indexOf = function (value) {
  8653. var position = this.data.indexOf(value);
  8654. if (position >= this.length) {
  8655. return -1;
  8656. }
  8657. return position;
  8658. };
  8659. /**
  8660. * Returns whether an element is part of the active data.
  8661. * @param value defines the value to look for
  8662. * @returns true if found in the active data otherwise false
  8663. */
  8664. SmartArray.prototype.contains = function (value) {
  8665. return this.indexOf(value) !== -1;
  8666. };
  8667. // Statics
  8668. SmartArray._GlobalId = 0;
  8669. return SmartArray;
  8670. }());
  8671. BABYLON.SmartArray = SmartArray;
  8672. /**
  8673. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8674. * The data in this array can only be present once
  8675. */
  8676. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8677. __extends(SmartArrayNoDuplicate, _super);
  8678. function SmartArrayNoDuplicate() {
  8679. var _this = _super !== null && _super.apply(this, arguments) || this;
  8680. _this._duplicateId = 0;
  8681. return _this;
  8682. }
  8683. /**
  8684. * Pushes a value at the end of the active data.
  8685. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8686. * @param value defines the object to push in the array.
  8687. */
  8688. SmartArrayNoDuplicate.prototype.push = function (value) {
  8689. _super.prototype.push.call(this, value);
  8690. if (!value.__smartArrayFlags) {
  8691. value.__smartArrayFlags = {};
  8692. }
  8693. value.__smartArrayFlags[this._id] = this._duplicateId;
  8694. };
  8695. /**
  8696. * Pushes a value at the end of the active data.
  8697. * If the data is already present, it won t be added again
  8698. * @param value defines the object to push in the array.
  8699. * @returns true if added false if it was already present
  8700. */
  8701. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8702. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8703. return false;
  8704. }
  8705. this.push(value);
  8706. return true;
  8707. };
  8708. /**
  8709. * Resets the active data to an empty array.
  8710. */
  8711. SmartArrayNoDuplicate.prototype.reset = function () {
  8712. _super.prototype.reset.call(this);
  8713. this._duplicateId++;
  8714. };
  8715. /**
  8716. * Concats the active data with a given array.
  8717. * This ensures no dupplicate will be present in the result.
  8718. * @param array defines the data to concatenate with.
  8719. */
  8720. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8721. if (array.length === 0) {
  8722. return;
  8723. }
  8724. if (this.length + array.length > this.data.length) {
  8725. this.data.length = (this.length + array.length) * 2;
  8726. }
  8727. for (var index = 0; index < array.length; index++) {
  8728. var item = (array.data || array)[index];
  8729. this.pushNoDuplicate(item);
  8730. }
  8731. };
  8732. return SmartArrayNoDuplicate;
  8733. }(SmartArray));
  8734. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8735. })(BABYLON || (BABYLON = {}));
  8736. //# sourceMappingURL=babylon.smartArray.js.map
  8737. var BABYLON;
  8738. (function (BABYLON) {
  8739. /** Class used to store color4 gradient */
  8740. var ColorGradient = /** @class */ (function () {
  8741. function ColorGradient() {
  8742. }
  8743. /**
  8744. * Will get a color picked randomly between color1 and color2.
  8745. * If color2 is undefined then color1 will be used
  8746. * @param result defines the target Color4 to store the result in
  8747. */
  8748. ColorGradient.prototype.getColorToRef = function (result) {
  8749. if (!this.color2) {
  8750. result.copyFrom(this.color1);
  8751. return;
  8752. }
  8753. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8754. };
  8755. return ColorGradient;
  8756. }());
  8757. BABYLON.ColorGradient = ColorGradient;
  8758. /** Class used to store color 3 gradient */
  8759. var Color3Gradient = /** @class */ (function () {
  8760. function Color3Gradient() {
  8761. }
  8762. return Color3Gradient;
  8763. }());
  8764. BABYLON.Color3Gradient = Color3Gradient;
  8765. /** Class used to store factor gradient */
  8766. var FactorGradient = /** @class */ (function () {
  8767. function FactorGradient() {
  8768. }
  8769. /**
  8770. * Will get a number picked randomly between factor1 and factor2.
  8771. * If factor2 is undefined then factor1 will be used
  8772. * @returns the picked number
  8773. */
  8774. FactorGradient.prototype.getFactor = function () {
  8775. if (this.factor2 === undefined) {
  8776. return this.factor1;
  8777. }
  8778. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8779. };
  8780. return FactorGradient;
  8781. }());
  8782. BABYLON.FactorGradient = FactorGradient;
  8783. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8784. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8785. var LoadFileError = /** @class */ (function (_super) {
  8786. __extends(LoadFileError, _super);
  8787. function LoadFileError(message, request) {
  8788. var _this = _super.call(this, message) || this;
  8789. _this.request = request;
  8790. _this.name = "LoadFileError";
  8791. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8792. return _this;
  8793. }
  8794. // Polyfill for Object.setPrototypeOf if necessary.
  8795. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8796. return LoadFileError;
  8797. }(Error));
  8798. BABYLON.LoadFileError = LoadFileError;
  8799. var RetryStrategy = /** @class */ (function () {
  8800. function RetryStrategy() {
  8801. }
  8802. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8803. if (maxRetries === void 0) { maxRetries = 3; }
  8804. if (baseInterval === void 0) { baseInterval = 500; }
  8805. return function (url, request, retryIndex) {
  8806. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8807. return -1;
  8808. }
  8809. return Math.pow(2, retryIndex) * baseInterval;
  8810. };
  8811. };
  8812. return RetryStrategy;
  8813. }());
  8814. BABYLON.RetryStrategy = RetryStrategy;
  8815. // Screenshots
  8816. var screenshotCanvas;
  8817. var cloneValue = function (source, destinationObject) {
  8818. if (!source)
  8819. return null;
  8820. if (source instanceof BABYLON.Mesh) {
  8821. return null;
  8822. }
  8823. if (source instanceof BABYLON.SubMesh) {
  8824. return source.clone(destinationObject);
  8825. }
  8826. else if (source.clone) {
  8827. return source.clone();
  8828. }
  8829. return null;
  8830. };
  8831. var Tools = /** @class */ (function () {
  8832. function Tools() {
  8833. }
  8834. /**
  8835. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8836. * @param u defines the coordinate on X axis
  8837. * @param v defines the coordinate on Y axis
  8838. * @param width defines the width of the source data
  8839. * @param height defines the height of the source data
  8840. * @param pixels defines the source byte array
  8841. * @param color defines the output color
  8842. */
  8843. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8844. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8845. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8846. var position = (wrappedU + wrappedV * width) * 4;
  8847. color.r = pixels[position] / 255;
  8848. color.g = pixels[position + 1] / 255;
  8849. color.b = pixels[position + 2] / 255;
  8850. color.a = pixels[position + 3] / 255;
  8851. };
  8852. /**
  8853. * Interpolates between a and b via alpha
  8854. * @param a The lower value (returned when alpha = 0)
  8855. * @param b The upper value (returned when alpha = 1)
  8856. * @param alpha The interpolation-factor
  8857. * @return The mixed value
  8858. */
  8859. Tools.Mix = function (a, b, alpha) {
  8860. return a * (1 - alpha) + b * alpha;
  8861. };
  8862. Tools.Instantiate = function (className) {
  8863. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8864. return Tools.RegisteredExternalClasses[className];
  8865. }
  8866. var arr = className.split(".");
  8867. var fn = (window || this);
  8868. for (var i = 0, len = arr.length; i < len; i++) {
  8869. fn = fn[arr[i]];
  8870. }
  8871. if (typeof fn !== "function") {
  8872. return null;
  8873. }
  8874. return fn;
  8875. };
  8876. /**
  8877. * Provides a slice function that will work even on IE
  8878. * @param data defines the array to slice
  8879. * @param start defines the start of the data (optional)
  8880. * @param end defines the end of the data (optional)
  8881. * @returns the new sliced array
  8882. */
  8883. Tools.Slice = function (data, start, end) {
  8884. if (data.slice) {
  8885. return data.slice(start, end);
  8886. }
  8887. return Array.prototype.slice.call(data, start, end);
  8888. };
  8889. Tools.SetImmediate = function (action) {
  8890. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8891. window.setImmediate(action);
  8892. }
  8893. else {
  8894. setTimeout(action, 1);
  8895. }
  8896. };
  8897. Tools.IsExponentOfTwo = function (value) {
  8898. var count = 1;
  8899. do {
  8900. count *= 2;
  8901. } while (count < value);
  8902. return count === value;
  8903. };
  8904. /**
  8905. * Returns the nearest 32-bit single precision float representation of a Number
  8906. * @param value A Number. If the parameter is of a different type, it will get converted
  8907. * to a number or to NaN if it cannot be converted
  8908. * @returns number
  8909. */
  8910. Tools.FloatRound = function (value) {
  8911. if (Math.fround) {
  8912. return Math.fround(value);
  8913. }
  8914. return (Tools._tmpFloatArray[0] = value);
  8915. };
  8916. /**
  8917. * Find the next highest power of two.
  8918. * @param x Number to start search from.
  8919. * @return Next highest power of two.
  8920. */
  8921. Tools.CeilingPOT = function (x) {
  8922. x--;
  8923. x |= x >> 1;
  8924. x |= x >> 2;
  8925. x |= x >> 4;
  8926. x |= x >> 8;
  8927. x |= x >> 16;
  8928. x++;
  8929. return x;
  8930. };
  8931. /**
  8932. * Find the next lowest power of two.
  8933. * @param x Number to start search from.
  8934. * @return Next lowest power of two.
  8935. */
  8936. Tools.FloorPOT = function (x) {
  8937. x = x | (x >> 1);
  8938. x = x | (x >> 2);
  8939. x = x | (x >> 4);
  8940. x = x | (x >> 8);
  8941. x = x | (x >> 16);
  8942. return x - (x >> 1);
  8943. };
  8944. /**
  8945. * Find the nearest power of two.
  8946. * @param x Number to start search from.
  8947. * @return Next nearest power of two.
  8948. */
  8949. Tools.NearestPOT = function (x) {
  8950. var c = Tools.CeilingPOT(x);
  8951. var f = Tools.FloorPOT(x);
  8952. return (c - x) > (x - f) ? f : c;
  8953. };
  8954. Tools.GetExponentOfTwo = function (value, max, mode) {
  8955. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8956. var pot;
  8957. switch (mode) {
  8958. case BABYLON.Engine.SCALEMODE_FLOOR:
  8959. pot = Tools.FloorPOT(value);
  8960. break;
  8961. case BABYLON.Engine.SCALEMODE_NEAREST:
  8962. pot = Tools.NearestPOT(value);
  8963. break;
  8964. case BABYLON.Engine.SCALEMODE_CEILING:
  8965. default:
  8966. pot = Tools.CeilingPOT(value);
  8967. break;
  8968. }
  8969. return Math.min(pot, max);
  8970. };
  8971. Tools.GetFilename = function (path) {
  8972. var index = path.lastIndexOf("/");
  8973. if (index < 0)
  8974. return path;
  8975. return path.substring(index + 1);
  8976. };
  8977. /**
  8978. * Extracts the "folder" part of a path (everything before the filename).
  8979. * @param uri The URI to extract the info from
  8980. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8981. * @returns The "folder" part of the path
  8982. */
  8983. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8984. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8985. var index = uri.lastIndexOf("/");
  8986. if (index < 0) {
  8987. if (returnUnchangedIfNoSlash) {
  8988. return uri;
  8989. }
  8990. return "";
  8991. }
  8992. return uri.substring(0, index + 1);
  8993. };
  8994. Tools.GetDOMTextContent = function (element) {
  8995. var result = "";
  8996. var child = element.firstChild;
  8997. while (child) {
  8998. if (child.nodeType === 3) {
  8999. result += child.textContent;
  9000. }
  9001. child = child.nextSibling;
  9002. }
  9003. return result;
  9004. };
  9005. Tools.ToDegrees = function (angle) {
  9006. return angle * 180 / Math.PI;
  9007. };
  9008. Tools.ToRadians = function (angle) {
  9009. return angle * Math.PI / 180;
  9010. };
  9011. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9012. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9013. var output = "";
  9014. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9015. var i = 0;
  9016. var bytes = new Uint8Array(buffer);
  9017. while (i < bytes.length) {
  9018. chr1 = bytes[i++];
  9019. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9020. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9021. enc1 = chr1 >> 2;
  9022. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9023. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9024. enc4 = chr3 & 63;
  9025. if (isNaN(chr2)) {
  9026. enc3 = enc4 = 64;
  9027. }
  9028. else if (isNaN(chr3)) {
  9029. enc4 = 64;
  9030. }
  9031. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9032. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9033. }
  9034. return "data:image/png;base64," + output;
  9035. };
  9036. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9037. if (bias === void 0) { bias = null; }
  9038. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9039. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9040. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9041. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  9042. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9043. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9044. }
  9045. if (bias) {
  9046. minimum.x -= minimum.x * bias.x + bias.y;
  9047. minimum.y -= minimum.y * bias.x + bias.y;
  9048. minimum.z -= minimum.z * bias.x + bias.y;
  9049. maximum.x += maximum.x * bias.x + bias.y;
  9050. maximum.y += maximum.y * bias.x + bias.y;
  9051. maximum.z += maximum.z * bias.x + bias.y;
  9052. }
  9053. return {
  9054. minimum: minimum,
  9055. maximum: maximum
  9056. };
  9057. };
  9058. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9059. if (bias === void 0) { bias = null; }
  9060. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9061. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9062. if (!stride) {
  9063. stride = 3;
  9064. }
  9065. for (var index = start; index < start + count; index++) {
  9066. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  9067. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9068. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9069. }
  9070. if (bias) {
  9071. minimum.x -= minimum.x * bias.x + bias.y;
  9072. minimum.y -= minimum.y * bias.x + bias.y;
  9073. minimum.z -= minimum.z * bias.x + bias.y;
  9074. maximum.x += maximum.x * bias.x + bias.y;
  9075. maximum.y += maximum.y * bias.x + bias.y;
  9076. maximum.z += maximum.z * bias.x + bias.y;
  9077. }
  9078. return {
  9079. minimum: minimum,
  9080. maximum: maximum
  9081. };
  9082. };
  9083. Tools.Vector2ArrayFeeder = function (array) {
  9084. return function (index) {
  9085. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  9086. var length = isFloatArray ? array.length / 2 : array.length;
  9087. if (index >= length) {
  9088. return null;
  9089. }
  9090. if (isFloatArray) {
  9091. var fa = array;
  9092. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  9093. }
  9094. var a = array;
  9095. return a[index];
  9096. };
  9097. };
  9098. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9099. if (bias === void 0) { bias = null; }
  9100. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9101. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9102. var i = 0;
  9103. var cur = feeder(i++);
  9104. while (cur) {
  9105. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9106. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9107. cur = feeder(i++);
  9108. }
  9109. if (bias) {
  9110. minimum.x -= minimum.x * bias.x + bias.y;
  9111. minimum.y -= minimum.y * bias.x + bias.y;
  9112. maximum.x += maximum.x * bias.x + bias.y;
  9113. maximum.y += maximum.y * bias.x + bias.y;
  9114. }
  9115. return {
  9116. minimum: minimum,
  9117. maximum: maximum
  9118. };
  9119. };
  9120. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9121. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9122. return null;
  9123. return Array.isArray(obj) ? obj : [obj];
  9124. };
  9125. // Misc.
  9126. Tools.GetPointerPrefix = function () {
  9127. var eventPrefix = "pointer";
  9128. // Check if pointer events are supported
  9129. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9130. eventPrefix = "mouse";
  9131. }
  9132. return eventPrefix;
  9133. };
  9134. /**
  9135. * @param func - the function to be called
  9136. * @param requester - the object that will request the next frame. Falls back to window.
  9137. */
  9138. Tools.QueueNewFrame = function (func, requester) {
  9139. if (!Tools.IsWindowObjectExist()) {
  9140. return setTimeout(func, 16);
  9141. }
  9142. if (!requester) {
  9143. requester = window;
  9144. }
  9145. if (requester.requestAnimationFrame) {
  9146. return requester.requestAnimationFrame(func);
  9147. }
  9148. else if (requester.msRequestAnimationFrame) {
  9149. return requester.msRequestAnimationFrame(func);
  9150. }
  9151. else if (requester.webkitRequestAnimationFrame) {
  9152. return requester.webkitRequestAnimationFrame(func);
  9153. }
  9154. else if (requester.mozRequestAnimationFrame) {
  9155. return requester.mozRequestAnimationFrame(func);
  9156. }
  9157. else if (requester.oRequestAnimationFrame) {
  9158. return requester.oRequestAnimationFrame(func);
  9159. }
  9160. else {
  9161. return window.setTimeout(func, 16);
  9162. }
  9163. };
  9164. Tools.RequestFullscreen = function (element) {
  9165. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9166. if (!requestFunction)
  9167. return;
  9168. requestFunction.call(element);
  9169. };
  9170. Tools.ExitFullscreen = function () {
  9171. if (document.exitFullscreen) {
  9172. document.exitFullscreen();
  9173. }
  9174. else if (document.mozCancelFullScreen) {
  9175. document.mozCancelFullScreen();
  9176. }
  9177. else if (document.webkitCancelFullScreen) {
  9178. document.webkitCancelFullScreen();
  9179. }
  9180. else if (document.msCancelFullScreen) {
  9181. document.msCancelFullScreen();
  9182. }
  9183. };
  9184. /**
  9185. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9186. * @param url define the url we are trying
  9187. * @param element define the dom element where to configure the cors policy
  9188. */
  9189. Tools.SetCorsBehavior = function (url, element) {
  9190. if (url && url.indexOf("data:") === 0) {
  9191. return;
  9192. }
  9193. if (Tools.CorsBehavior) {
  9194. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9195. element.crossOrigin = Tools.CorsBehavior;
  9196. }
  9197. else {
  9198. var result = Tools.CorsBehavior(url);
  9199. if (result) {
  9200. element.crossOrigin = result;
  9201. }
  9202. }
  9203. }
  9204. };
  9205. // External files
  9206. Tools.CleanUrl = function (url) {
  9207. url = url.replace(/#/mg, "%23");
  9208. return url;
  9209. };
  9210. /**
  9211. * Loads an image as an HTMLImageElement.
  9212. * @param input url string, ArrayBuffer, or Blob to load
  9213. * @param onLoad callback called when the image successfully loads
  9214. * @param onError callback called when the image fails to load
  9215. * @param database database for caching
  9216. * @returns the HTMLImageElement of the loaded image
  9217. */
  9218. Tools.LoadImage = function (input, onLoad, onError, database) {
  9219. var url;
  9220. var usingObjectURL = false;
  9221. if (input instanceof ArrayBuffer) {
  9222. url = URL.createObjectURL(new Blob([input]));
  9223. usingObjectURL = true;
  9224. }
  9225. else if (input instanceof Blob) {
  9226. url = URL.createObjectURL(input);
  9227. usingObjectURL = true;
  9228. }
  9229. else {
  9230. url = Tools.CleanUrl(input);
  9231. url = Tools.PreprocessUrl(input);
  9232. }
  9233. var img = new Image();
  9234. Tools.SetCorsBehavior(url, img);
  9235. var loadHandler = function () {
  9236. if (usingObjectURL && img.src) {
  9237. URL.revokeObjectURL(img.src);
  9238. }
  9239. img.removeEventListener("load", loadHandler);
  9240. img.removeEventListener("error", errorHandler);
  9241. onLoad(img);
  9242. };
  9243. var errorHandler = function (err) {
  9244. if (usingObjectURL && img.src) {
  9245. URL.revokeObjectURL(img.src);
  9246. }
  9247. img.removeEventListener("load", loadHandler);
  9248. img.removeEventListener("error", errorHandler);
  9249. Tools.Error("Error while trying to load image: " + input);
  9250. if (onError) {
  9251. onError("Error while trying to load image: " + input, err);
  9252. }
  9253. };
  9254. img.addEventListener("load", loadHandler);
  9255. img.addEventListener("error", errorHandler);
  9256. var noIndexedDB = function () {
  9257. img.src = url;
  9258. };
  9259. var loadFromIndexedDB = function () {
  9260. if (database) {
  9261. database.loadImageFromDB(url, img);
  9262. }
  9263. };
  9264. //ANY database to do!
  9265. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9266. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9267. }
  9268. else {
  9269. if (url.indexOf("file:") !== -1) {
  9270. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9271. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9272. try {
  9273. var blobURL;
  9274. try {
  9275. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9276. }
  9277. catch (ex) {
  9278. // Chrome doesn't support oneTimeOnly parameter
  9279. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9280. }
  9281. img.src = blobURL;
  9282. usingObjectURL = true;
  9283. }
  9284. catch (e) {
  9285. img.src = "";
  9286. }
  9287. return img;
  9288. }
  9289. }
  9290. noIndexedDB();
  9291. }
  9292. return img;
  9293. };
  9294. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9295. url = Tools.CleanUrl(url);
  9296. url = Tools.PreprocessUrl(url);
  9297. // If file and file input are set
  9298. if (url.indexOf("file:") !== -1) {
  9299. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9300. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9301. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9302. }
  9303. }
  9304. var loadUrl = Tools.BaseUrl + url;
  9305. var aborted = false;
  9306. var fileRequest = {
  9307. onCompleteObservable: new BABYLON.Observable(),
  9308. abort: function () { return aborted = true; },
  9309. };
  9310. var requestFile = function () {
  9311. var request = new XMLHttpRequest();
  9312. var retryHandle = null;
  9313. fileRequest.abort = function () {
  9314. aborted = true;
  9315. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9316. request.abort();
  9317. }
  9318. if (retryHandle !== null) {
  9319. clearTimeout(retryHandle);
  9320. retryHandle = null;
  9321. }
  9322. };
  9323. var retryLoop = function (retryIndex) {
  9324. request.open('GET', loadUrl, true);
  9325. if (useArrayBuffer) {
  9326. request.responseType = "arraybuffer";
  9327. }
  9328. if (onProgress) {
  9329. request.addEventListener("progress", onProgress);
  9330. }
  9331. var onLoadEnd = function () {
  9332. request.removeEventListener("loadend", onLoadEnd);
  9333. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9334. fileRequest.onCompleteObservable.clear();
  9335. };
  9336. request.addEventListener("loadend", onLoadEnd);
  9337. var onReadyStateChange = function () {
  9338. if (aborted) {
  9339. return;
  9340. }
  9341. // In case of undefined state in some browsers.
  9342. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9343. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9344. request.removeEventListener("readystatechange", onReadyStateChange);
  9345. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9346. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9347. return;
  9348. }
  9349. var retryStrategy = Tools.DefaultRetryStrategy;
  9350. if (retryStrategy) {
  9351. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9352. if (waitTime !== -1) {
  9353. // Prevent the request from completing for retry.
  9354. request.removeEventListener("loadend", onLoadEnd);
  9355. request = new XMLHttpRequest();
  9356. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9357. return;
  9358. }
  9359. }
  9360. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9361. if (onError) {
  9362. onError(request, e);
  9363. }
  9364. else {
  9365. throw e;
  9366. }
  9367. }
  9368. };
  9369. request.addEventListener("readystatechange", onReadyStateChange);
  9370. request.send();
  9371. };
  9372. retryLoop(0);
  9373. };
  9374. // Caching all files
  9375. if (database && database.enableSceneOffline) {
  9376. var noIndexedDB_1 = function (request) {
  9377. if (request && request.status > 400) {
  9378. if (onError) {
  9379. onError(request);
  9380. }
  9381. }
  9382. else {
  9383. if (!aborted) {
  9384. requestFile();
  9385. }
  9386. }
  9387. };
  9388. var loadFromIndexedDB = function () {
  9389. // TODO: database needs to support aborting and should return a IFileRequest
  9390. if (aborted) {
  9391. return;
  9392. }
  9393. if (database) {
  9394. database.loadFileFromDB(url, function (data) {
  9395. if (!aborted) {
  9396. onSuccess(data);
  9397. }
  9398. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9399. }, onProgress ? function (event) {
  9400. if (!aborted) {
  9401. onProgress(event);
  9402. }
  9403. } : undefined, noIndexedDB_1, useArrayBuffer);
  9404. }
  9405. };
  9406. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9407. }
  9408. else {
  9409. requestFile();
  9410. }
  9411. return fileRequest;
  9412. };
  9413. /**
  9414. * Load a script (identified by an url). When the url returns, the
  9415. * content of this file is added into a new script element, attached to the DOM (body element)
  9416. */
  9417. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9418. if (!Tools.IsWindowObjectExist()) {
  9419. return;
  9420. }
  9421. var head = document.getElementsByTagName('head')[0];
  9422. var script = document.createElement('script');
  9423. script.type = 'text/javascript';
  9424. script.src = scriptUrl;
  9425. script.onload = function () {
  9426. if (onSuccess) {
  9427. onSuccess();
  9428. }
  9429. };
  9430. script.onerror = function (e) {
  9431. if (onError) {
  9432. onError("Unable to load script '" + scriptUrl + "'", e);
  9433. }
  9434. };
  9435. head.appendChild(script);
  9436. };
  9437. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9438. var reader = new FileReader();
  9439. var request = {
  9440. onCompleteObservable: new BABYLON.Observable(),
  9441. abort: function () { return reader.abort(); },
  9442. };
  9443. reader.onloadend = function (e) {
  9444. request.onCompleteObservable.notifyObservers(request);
  9445. };
  9446. reader.onload = function (e) {
  9447. //target doesn't have result from ts 1.3
  9448. callback(e.target['result']);
  9449. };
  9450. reader.onprogress = progressCallback;
  9451. reader.readAsDataURL(fileToLoad);
  9452. return request;
  9453. };
  9454. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9455. var reader = new FileReader();
  9456. var request = {
  9457. onCompleteObservable: new BABYLON.Observable(),
  9458. abort: function () { return reader.abort(); },
  9459. };
  9460. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9461. reader.onerror = function (e) {
  9462. Tools.Log("Error while reading file: " + fileToLoad.name);
  9463. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9464. };
  9465. reader.onload = function (e) {
  9466. //target doesn't have result from ts 1.3
  9467. callback(e.target['result']);
  9468. };
  9469. if (progressCallBack) {
  9470. reader.onprogress = progressCallBack;
  9471. }
  9472. if (!useArrayBuffer) {
  9473. // Asynchronous read
  9474. reader.readAsText(fileToLoad);
  9475. }
  9476. else {
  9477. reader.readAsArrayBuffer(fileToLoad);
  9478. }
  9479. return request;
  9480. };
  9481. //returns a downloadable url to a file content.
  9482. Tools.FileAsURL = function (content) {
  9483. var fileBlob = new Blob([content]);
  9484. var url = window.URL || window.webkitURL;
  9485. var link = url.createObjectURL(fileBlob);
  9486. return link;
  9487. };
  9488. // Misc.
  9489. Tools.Format = function (value, decimals) {
  9490. if (decimals === void 0) { decimals = 2; }
  9491. return value.toFixed(decimals);
  9492. };
  9493. Tools.CheckExtends = function (v, min, max) {
  9494. if (v.x < min.x)
  9495. min.x = v.x;
  9496. if (v.y < min.y)
  9497. min.y = v.y;
  9498. if (v.z < min.z)
  9499. min.z = v.z;
  9500. if (v.x > max.x)
  9501. max.x = v.x;
  9502. if (v.y > max.y)
  9503. max.y = v.y;
  9504. if (v.z > max.z)
  9505. max.z = v.z;
  9506. };
  9507. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9508. for (var prop in source) {
  9509. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9510. continue;
  9511. }
  9512. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9513. continue;
  9514. }
  9515. var sourceValue = source[prop];
  9516. var typeOfSourceValue = typeof sourceValue;
  9517. if (typeOfSourceValue === "function") {
  9518. continue;
  9519. }
  9520. try {
  9521. if (typeOfSourceValue === "object") {
  9522. if (sourceValue instanceof Array) {
  9523. destination[prop] = [];
  9524. if (sourceValue.length > 0) {
  9525. if (typeof sourceValue[0] == "object") {
  9526. for (var index = 0; index < sourceValue.length; index++) {
  9527. var clonedValue = cloneValue(sourceValue[index], destination);
  9528. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9529. destination[prop].push(clonedValue);
  9530. }
  9531. }
  9532. }
  9533. else {
  9534. destination[prop] = sourceValue.slice(0);
  9535. }
  9536. }
  9537. }
  9538. else {
  9539. destination[prop] = cloneValue(sourceValue, destination);
  9540. }
  9541. }
  9542. else {
  9543. destination[prop] = sourceValue;
  9544. }
  9545. }
  9546. catch (e) {
  9547. // Just ignore error (it could be because of a read-only property)
  9548. }
  9549. }
  9550. };
  9551. Tools.IsEmpty = function (obj) {
  9552. for (var i in obj) {
  9553. if (obj.hasOwnProperty(i)) {
  9554. return false;
  9555. }
  9556. }
  9557. return true;
  9558. };
  9559. Tools.RegisterTopRootEvents = function (events) {
  9560. for (var index = 0; index < events.length; index++) {
  9561. var event = events[index];
  9562. window.addEventListener(event.name, event.handler, false);
  9563. try {
  9564. if (window.parent) {
  9565. window.parent.addEventListener(event.name, event.handler, false);
  9566. }
  9567. }
  9568. catch (e) {
  9569. // Silently fails...
  9570. }
  9571. }
  9572. };
  9573. Tools.UnregisterTopRootEvents = function (events) {
  9574. for (var index = 0; index < events.length; index++) {
  9575. var event = events[index];
  9576. window.removeEventListener(event.name, event.handler);
  9577. try {
  9578. if (window.parent) {
  9579. window.parent.removeEventListener(event.name, event.handler);
  9580. }
  9581. }
  9582. catch (e) {
  9583. // Silently fails...
  9584. }
  9585. }
  9586. };
  9587. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9588. if (mimeType === void 0) { mimeType = "image/png"; }
  9589. // Read the contents of the framebuffer
  9590. var numberOfChannelsByLine = width * 4;
  9591. var halfHeight = height / 2;
  9592. //Reading datas from WebGL
  9593. var data = engine.readPixels(0, 0, width, height);
  9594. //To flip image on Y axis.
  9595. for (var i = 0; i < halfHeight; i++) {
  9596. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9597. var currentCell = j + i * numberOfChannelsByLine;
  9598. var targetLine = height - i - 1;
  9599. var targetCell = j + targetLine * numberOfChannelsByLine;
  9600. var temp = data[currentCell];
  9601. data[currentCell] = data[targetCell];
  9602. data[targetCell] = temp;
  9603. }
  9604. }
  9605. // Create a 2D canvas to store the result
  9606. if (!screenshotCanvas) {
  9607. screenshotCanvas = document.createElement('canvas');
  9608. }
  9609. screenshotCanvas.width = width;
  9610. screenshotCanvas.height = height;
  9611. var context = screenshotCanvas.getContext('2d');
  9612. if (context) {
  9613. // Copy the pixels to a 2D canvas
  9614. var imageData = context.createImageData(width, height);
  9615. var castData = (imageData.data);
  9616. castData.set(data);
  9617. context.putImageData(imageData, 0, 0);
  9618. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9619. }
  9620. };
  9621. /**
  9622. * Converts the canvas data to blob.
  9623. * This acts as a polyfill for browsers not supporting the to blob function.
  9624. * @param canvas Defines the canvas to extract the data from
  9625. * @param successCallback Defines the callback triggered once the data are available
  9626. * @param mimeType Defines the mime type of the result
  9627. */
  9628. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9629. if (mimeType === void 0) { mimeType = "image/png"; }
  9630. // We need HTMLCanvasElement.toBlob for HD screenshots
  9631. if (!canvas.toBlob) {
  9632. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9633. canvas.toBlob = function (callback, type, quality) {
  9634. var _this = this;
  9635. setTimeout(function () {
  9636. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9637. for (var i = 0; i < len; i++) {
  9638. arr[i] = binStr.charCodeAt(i);
  9639. }
  9640. callback(new Blob([arr]));
  9641. });
  9642. };
  9643. }
  9644. canvas.toBlob(function (blob) {
  9645. successCallback(blob);
  9646. }, mimeType);
  9647. };
  9648. /**
  9649. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9650. * @param successCallback Defines the callback triggered once the data are available
  9651. * @param mimeType Defines the mime type of the result
  9652. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9653. */
  9654. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9655. if (mimeType === void 0) { mimeType = "image/png"; }
  9656. if (successCallback) {
  9657. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9658. successCallback(base64Image);
  9659. }
  9660. else {
  9661. this.ToBlob(screenshotCanvas, function (blob) {
  9662. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9663. if (("download" in document.createElement("a"))) {
  9664. if (!fileName) {
  9665. var date = new Date();
  9666. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9667. fileName = "screenshot_" + stringDate + ".png";
  9668. }
  9669. Tools.Download(blob, fileName);
  9670. }
  9671. else {
  9672. var url = URL.createObjectURL(blob);
  9673. var newWindow = window.open("");
  9674. if (!newWindow)
  9675. return;
  9676. var img = newWindow.document.createElement("img");
  9677. img.onload = function () {
  9678. // no longer need to read the blob so it's revoked
  9679. URL.revokeObjectURL(url);
  9680. };
  9681. img.src = url;
  9682. newWindow.document.body.appendChild(img);
  9683. }
  9684. }, mimeType);
  9685. }
  9686. };
  9687. /**
  9688. * Downloads a blob in the browser
  9689. * @param blob defines the blob to download
  9690. * @param fileName defines the name of the downloaded file
  9691. */
  9692. Tools.Download = function (blob, fileName) {
  9693. if (navigator && navigator.msSaveBlob) {
  9694. navigator.msSaveBlob(blob, fileName);
  9695. return;
  9696. }
  9697. var url = window.URL.createObjectURL(blob);
  9698. var a = document.createElement("a");
  9699. document.body.appendChild(a);
  9700. a.style.display = "none";
  9701. a.href = url;
  9702. a.download = fileName;
  9703. a.addEventListener("click", function () {
  9704. if (a.parentElement) {
  9705. a.parentElement.removeChild(a);
  9706. }
  9707. });
  9708. a.click();
  9709. window.URL.revokeObjectURL(url);
  9710. };
  9711. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9712. if (mimeType === void 0) { mimeType = "image/png"; }
  9713. var width;
  9714. var height;
  9715. // If a precision value is specified
  9716. if (size.precision) {
  9717. width = Math.round(engine.getRenderWidth() * size.precision);
  9718. height = Math.round(width / engine.getAspectRatio(camera));
  9719. }
  9720. else if (size.width && size.height) {
  9721. width = size.width;
  9722. height = size.height;
  9723. }
  9724. //If passing only width, computing height to keep display canvas ratio.
  9725. else if (size.width && !size.height) {
  9726. width = size.width;
  9727. height = Math.round(width / engine.getAspectRatio(camera));
  9728. }
  9729. //If passing only height, computing width to keep display canvas ratio.
  9730. else if (size.height && !size.width) {
  9731. height = size.height;
  9732. width = Math.round(height * engine.getAspectRatio(camera));
  9733. }
  9734. //Assuming here that "size" parameter is a number
  9735. else if (!isNaN(size)) {
  9736. height = size;
  9737. width = size;
  9738. }
  9739. else {
  9740. Tools.Error("Invalid 'size' parameter !");
  9741. return;
  9742. }
  9743. if (!screenshotCanvas) {
  9744. screenshotCanvas = document.createElement('canvas');
  9745. }
  9746. screenshotCanvas.width = width;
  9747. screenshotCanvas.height = height;
  9748. var renderContext = screenshotCanvas.getContext("2d");
  9749. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9750. var newWidth = width;
  9751. var newHeight = newWidth / ratio;
  9752. if (newHeight > height) {
  9753. newHeight = height;
  9754. newWidth = newHeight * ratio;
  9755. }
  9756. var offsetX = Math.max(0, width - newWidth) / 2;
  9757. var offsetY = Math.max(0, height - newHeight) / 2;
  9758. var renderingCanvas = engine.getRenderingCanvas();
  9759. if (renderContext && renderingCanvas) {
  9760. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9761. }
  9762. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9763. };
  9764. /**
  9765. * Generates an image screenshot from the specified camera.
  9766. *
  9767. * @param engine The engine to use for rendering
  9768. * @param camera The camera to use for rendering
  9769. * @param size This parameter can be set to a single number or to an object with the
  9770. * following (optional) properties: precision, width, height. If a single number is passed,
  9771. * it will be used for both width and height. If an object is passed, the screenshot size
  9772. * will be derived from the parameters. The precision property is a multiplier allowing
  9773. * rendering at a higher or lower resolution.
  9774. * @param successCallback The callback receives a single parameter which contains the
  9775. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9776. * src parameter of an <img> to display it.
  9777. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9778. * Check your browser for supported MIME types.
  9779. * @param samples Texture samples (default: 1)
  9780. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9781. * @param fileName A name for for the downloaded file.
  9782. * @constructor
  9783. */
  9784. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9785. if (mimeType === void 0) { mimeType = "image/png"; }
  9786. if (samples === void 0) { samples = 1; }
  9787. if (antialiasing === void 0) { antialiasing = false; }
  9788. var width;
  9789. var height;
  9790. //If a precision value is specified
  9791. if (size.precision) {
  9792. width = Math.round(engine.getRenderWidth() * size.precision);
  9793. height = Math.round(width / engine.getAspectRatio(camera));
  9794. size = { width: width, height: height };
  9795. }
  9796. else if (size.width && size.height) {
  9797. width = size.width;
  9798. height = size.height;
  9799. }
  9800. //If passing only width, computing height to keep display canvas ratio.
  9801. else if (size.width && !size.height) {
  9802. width = size.width;
  9803. height = Math.round(width / engine.getAspectRatio(camera));
  9804. size = { width: width, height: height };
  9805. }
  9806. //If passing only height, computing width to keep display canvas ratio.
  9807. else if (size.height && !size.width) {
  9808. height = size.height;
  9809. width = Math.round(height * engine.getAspectRatio(camera));
  9810. size = { width: width, height: height };
  9811. }
  9812. //Assuming here that "size" parameter is a number
  9813. else if (!isNaN(size)) {
  9814. height = size;
  9815. width = size;
  9816. }
  9817. else {
  9818. Tools.Error("Invalid 'size' parameter !");
  9819. return;
  9820. }
  9821. var scene = camera.getScene();
  9822. var previousCamera = null;
  9823. if (scene.activeCamera !== camera) {
  9824. previousCamera = scene.activeCamera;
  9825. scene.activeCamera = camera;
  9826. }
  9827. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9828. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9829. texture.renderList = null;
  9830. texture.samples = samples;
  9831. if (antialiasing) {
  9832. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9833. }
  9834. texture.onAfterRenderObservable.add(function () {
  9835. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9836. });
  9837. scene.incrementRenderId();
  9838. scene.resetCachedMaterial();
  9839. texture.render(true);
  9840. texture.dispose();
  9841. if (previousCamera) {
  9842. scene.activeCamera = previousCamera;
  9843. }
  9844. camera.getProjectionMatrix(true); // Force cache refresh;
  9845. };
  9846. // XHR response validator for local file scenario
  9847. Tools.ValidateXHRData = function (xhr, dataType) {
  9848. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9849. if (dataType === void 0) { dataType = 7; }
  9850. try {
  9851. if (dataType & 1) {
  9852. if (xhr.responseText && xhr.responseText.length > 0) {
  9853. return true;
  9854. }
  9855. else if (dataType === 1) {
  9856. return false;
  9857. }
  9858. }
  9859. if (dataType & 2) {
  9860. // Check header width and height since there is no "TGA" magic number
  9861. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9862. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9863. return true;
  9864. }
  9865. else if (dataType === 2) {
  9866. return false;
  9867. }
  9868. }
  9869. if (dataType & 4) {
  9870. // Check for the "DDS" magic number
  9871. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9872. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9873. return true;
  9874. }
  9875. else {
  9876. return false;
  9877. }
  9878. }
  9879. }
  9880. catch (e) {
  9881. // Global protection
  9882. }
  9883. return false;
  9884. };
  9885. /**
  9886. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9887. * Be aware Math.random() could cause collisions, but:
  9888. * "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"
  9889. */
  9890. Tools.RandomId = function () {
  9891. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9892. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9893. return v.toString(16);
  9894. });
  9895. };
  9896. /**
  9897. * Test if the given uri is a base64 string.
  9898. * @param uri The uri to test
  9899. * @return True if the uri is a base64 string or false otherwise.
  9900. */
  9901. Tools.IsBase64 = function (uri) {
  9902. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9903. };
  9904. /**
  9905. * Decode the given base64 uri.
  9906. * @param uri The uri to decode
  9907. * @return The decoded base64 data.
  9908. */
  9909. Tools.DecodeBase64 = function (uri) {
  9910. var decodedString = atob(uri.split(",")[1]);
  9911. var bufferLength = decodedString.length;
  9912. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9913. for (var i = 0; i < bufferLength; i++) {
  9914. bufferView[i] = decodedString.charCodeAt(i);
  9915. }
  9916. return bufferView.buffer;
  9917. };
  9918. Object.defineProperty(Tools, "NoneLogLevel", {
  9919. get: function () {
  9920. return Tools._NoneLogLevel;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(Tools, "MessageLogLevel", {
  9926. get: function () {
  9927. return Tools._MessageLogLevel;
  9928. },
  9929. enumerable: true,
  9930. configurable: true
  9931. });
  9932. Object.defineProperty(Tools, "WarningLogLevel", {
  9933. get: function () {
  9934. return Tools._WarningLogLevel;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. Object.defineProperty(Tools, "ErrorLogLevel", {
  9940. get: function () {
  9941. return Tools._ErrorLogLevel;
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. Object.defineProperty(Tools, "AllLogLevel", {
  9947. get: function () {
  9948. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. Tools._AddLogEntry = function (entry) {
  9954. Tools._LogCache = entry + Tools._LogCache;
  9955. if (Tools.OnNewCacheEntry) {
  9956. Tools.OnNewCacheEntry(entry);
  9957. }
  9958. };
  9959. Tools._FormatMessage = function (message) {
  9960. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9961. var date = new Date();
  9962. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9963. };
  9964. Tools._LogDisabled = function (message) {
  9965. // nothing to do
  9966. };
  9967. Tools._LogEnabled = function (message) {
  9968. var formattedMessage = Tools._FormatMessage(message);
  9969. console.log("BJS - " + formattedMessage);
  9970. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9971. Tools._AddLogEntry(entry);
  9972. };
  9973. Tools._WarnDisabled = function (message) {
  9974. // nothing to do
  9975. };
  9976. Tools._WarnEnabled = function (message) {
  9977. var formattedMessage = Tools._FormatMessage(message);
  9978. console.warn("BJS - " + formattedMessage);
  9979. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9980. Tools._AddLogEntry(entry);
  9981. };
  9982. Tools._ErrorDisabled = function (message) {
  9983. // nothing to do
  9984. };
  9985. Tools._ErrorEnabled = function (message) {
  9986. Tools.errorsCount++;
  9987. var formattedMessage = Tools._FormatMessage(message);
  9988. console.error("BJS - " + formattedMessage);
  9989. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9990. Tools._AddLogEntry(entry);
  9991. };
  9992. Object.defineProperty(Tools, "LogCache", {
  9993. get: function () {
  9994. return Tools._LogCache;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. Tools.ClearLogCache = function () {
  10000. Tools._LogCache = "";
  10001. Tools.errorsCount = 0;
  10002. };
  10003. Object.defineProperty(Tools, "LogLevels", {
  10004. set: function (level) {
  10005. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10006. Tools.Log = Tools._LogEnabled;
  10007. }
  10008. else {
  10009. Tools.Log = Tools._LogDisabled;
  10010. }
  10011. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10012. Tools.Warn = Tools._WarnEnabled;
  10013. }
  10014. else {
  10015. Tools.Warn = Tools._WarnDisabled;
  10016. }
  10017. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10018. Tools.Error = Tools._ErrorEnabled;
  10019. }
  10020. else {
  10021. Tools.Error = Tools._ErrorDisabled;
  10022. }
  10023. },
  10024. enumerable: true,
  10025. configurable: true
  10026. });
  10027. /**
  10028. * Check if the loaded document was accessed via `file:`-Protocol.
  10029. * @returns boolean
  10030. */
  10031. Tools.IsFileURL = function () {
  10032. return location.protocol === "file:";
  10033. };
  10034. Tools.IsWindowObjectExist = function () {
  10035. return (typeof window) !== "undefined";
  10036. };
  10037. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  10038. get: function () {
  10039. return Tools._PerformanceNoneLogLevel;
  10040. },
  10041. enumerable: true,
  10042. configurable: true
  10043. });
  10044. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  10045. get: function () {
  10046. return Tools._PerformanceUserMarkLogLevel;
  10047. },
  10048. enumerable: true,
  10049. configurable: true
  10050. });
  10051. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  10052. get: function () {
  10053. return Tools._PerformanceConsoleLogLevel;
  10054. },
  10055. enumerable: true,
  10056. configurable: true
  10057. });
  10058. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10059. set: function (level) {
  10060. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10061. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10062. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10063. return;
  10064. }
  10065. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10066. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10067. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10068. return;
  10069. }
  10070. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10071. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10072. },
  10073. enumerable: true,
  10074. configurable: true
  10075. });
  10076. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10077. };
  10078. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10079. };
  10080. Tools._StartUserMark = function (counterName, condition) {
  10081. if (condition === void 0) { condition = true; }
  10082. if (!Tools._performance) {
  10083. if (!Tools.IsWindowObjectExist()) {
  10084. return;
  10085. }
  10086. Tools._performance = window.performance;
  10087. }
  10088. if (!condition || !Tools._performance.mark) {
  10089. return;
  10090. }
  10091. Tools._performance.mark(counterName + "-Begin");
  10092. };
  10093. Tools._EndUserMark = function (counterName, condition) {
  10094. if (condition === void 0) { condition = true; }
  10095. if (!condition || !Tools._performance.mark) {
  10096. return;
  10097. }
  10098. Tools._performance.mark(counterName + "-End");
  10099. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10100. };
  10101. Tools._StartPerformanceConsole = function (counterName, condition) {
  10102. if (condition === void 0) { condition = true; }
  10103. if (!condition) {
  10104. return;
  10105. }
  10106. Tools._StartUserMark(counterName, condition);
  10107. if (console.time) {
  10108. console.time(counterName);
  10109. }
  10110. };
  10111. Tools._EndPerformanceConsole = function (counterName, condition) {
  10112. if (condition === void 0) { condition = true; }
  10113. if (!condition) {
  10114. return;
  10115. }
  10116. Tools._EndUserMark(counterName, condition);
  10117. if (console.time) {
  10118. console.timeEnd(counterName);
  10119. }
  10120. };
  10121. Object.defineProperty(Tools, "Now", {
  10122. get: function () {
  10123. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10124. return window.performance.now();
  10125. }
  10126. return Date.now();
  10127. },
  10128. enumerable: true,
  10129. configurable: true
  10130. });
  10131. /**
  10132. * This method will return the name of the class used to create the instance of the given object.
  10133. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10134. * @param object the object to get the class name from
  10135. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10136. */
  10137. Tools.GetClassName = function (object, isType) {
  10138. if (isType === void 0) { isType = false; }
  10139. var name = null;
  10140. if (!isType && object.getClassName) {
  10141. name = object.getClassName();
  10142. }
  10143. else {
  10144. if (object instanceof Object) {
  10145. var classObj = isType ? object : Object.getPrototypeOf(object);
  10146. name = classObj.constructor["__bjsclassName__"];
  10147. }
  10148. if (!name) {
  10149. name = typeof object;
  10150. }
  10151. }
  10152. return name;
  10153. };
  10154. Tools.First = function (array, predicate) {
  10155. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10156. var el = array_1[_i];
  10157. if (predicate(el)) {
  10158. return el;
  10159. }
  10160. }
  10161. return null;
  10162. };
  10163. /**
  10164. * This method will return the name of the full name of the class, including its owning module (if any).
  10165. * 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).
  10166. * @param object the object to get the class name from
  10167. * @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.
  10168. */
  10169. Tools.getFullClassName = function (object, isType) {
  10170. if (isType === void 0) { isType = false; }
  10171. var className = null;
  10172. var moduleName = null;
  10173. if (!isType && object.getClassName) {
  10174. className = object.getClassName();
  10175. }
  10176. else {
  10177. if (object instanceof Object) {
  10178. var classObj = isType ? object : Object.getPrototypeOf(object);
  10179. className = classObj.constructor["__bjsclassName__"];
  10180. moduleName = classObj.constructor["__bjsmoduleName__"];
  10181. }
  10182. if (!className) {
  10183. className = typeof object;
  10184. }
  10185. }
  10186. if (!className) {
  10187. return null;
  10188. }
  10189. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10190. };
  10191. /**
  10192. * 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.
  10193. * @param array
  10194. */
  10195. Tools.arrayOrStringFeeder = function (array) {
  10196. return function (index) {
  10197. if (index >= array.length) {
  10198. return null;
  10199. }
  10200. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10201. if (val && val.getHashCode) {
  10202. val = val.getHashCode();
  10203. }
  10204. if (typeof val === "string") {
  10205. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10206. }
  10207. return val;
  10208. };
  10209. };
  10210. /**
  10211. * Compute the hashCode of a stream of number
  10212. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10213. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10214. * @return the hash code computed
  10215. */
  10216. Tools.hashCodeFromStream = function (feeder) {
  10217. // Based from here: http://stackoverflow.com/a/7616484/802124
  10218. var hash = 0;
  10219. var index = 0;
  10220. var chr = feeder(index++);
  10221. while (chr != null) {
  10222. hash = ((hash << 5) - hash) + chr;
  10223. hash |= 0; // Convert to 32bit integer
  10224. chr = feeder(index++);
  10225. }
  10226. return hash;
  10227. };
  10228. /**
  10229. * Returns a promise that resolves after the given amount of time.
  10230. * @param delay Number of milliseconds to delay
  10231. * @returns Promise that resolves after the given amount of time
  10232. */
  10233. Tools.DelayAsync = function (delay) {
  10234. return new Promise(function (resolve) {
  10235. setTimeout(function () {
  10236. resolve();
  10237. }, delay);
  10238. });
  10239. };
  10240. /**
  10241. * Gets the current gradient from an array of IValueGradient
  10242. * @param ratio defines the current ratio to get
  10243. * @param gradients defines the array of IValueGradient
  10244. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10245. */
  10246. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10247. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10248. var currentGradient = gradients[gradientIndex];
  10249. var nextGradient = gradients[gradientIndex + 1];
  10250. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10251. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10252. updateFunc(currentGradient, nextGradient, scale);
  10253. return;
  10254. }
  10255. }
  10256. // Use last index if over
  10257. var lastIndex = gradients.length - 1;
  10258. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10259. };
  10260. Tools.BaseUrl = "";
  10261. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10262. /**
  10263. * Default behaviour for cors in the application.
  10264. * It can be a string if the expected behavior is identical in the entire app.
  10265. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10266. */
  10267. Tools.CorsBehavior = "anonymous";
  10268. Tools.UseFallbackTexture = true;
  10269. /**
  10270. * Use this object to register external classes like custom textures or material
  10271. * to allow the laoders to instantiate them
  10272. */
  10273. Tools.RegisteredExternalClasses = {};
  10274. // Used in case of a texture loading problem
  10275. 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";
  10276. Tools._tmpFloatArray = new Float32Array(1);
  10277. Tools.PreprocessUrl = function (url) {
  10278. return url;
  10279. };
  10280. // Logs
  10281. Tools._NoneLogLevel = 0;
  10282. Tools._MessageLogLevel = 1;
  10283. Tools._WarningLogLevel = 2;
  10284. Tools._ErrorLogLevel = 4;
  10285. Tools._LogCache = "";
  10286. Tools.errorsCount = 0;
  10287. Tools.Log = Tools._LogEnabled;
  10288. Tools.Warn = Tools._WarnEnabled;
  10289. Tools.Error = Tools._ErrorEnabled;
  10290. // Performances
  10291. Tools._PerformanceNoneLogLevel = 0;
  10292. Tools._PerformanceUserMarkLogLevel = 1;
  10293. Tools._PerformanceConsoleLogLevel = 2;
  10294. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10295. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10296. return Tools;
  10297. }());
  10298. BABYLON.Tools = Tools;
  10299. /**
  10300. * This class is used to track a performance counter which is number based.
  10301. * The user has access to many properties which give statistics of different nature
  10302. *
  10303. * The implementer can track two kinds of Performance Counter: time and count
  10304. * 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.
  10305. * 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.
  10306. */
  10307. var PerfCounter = /** @class */ (function () {
  10308. function PerfCounter() {
  10309. this._startMonitoringTime = 0;
  10310. this._min = 0;
  10311. this._max = 0;
  10312. this._average = 0;
  10313. this._lastSecAverage = 0;
  10314. this._current = 0;
  10315. this._totalValueCount = 0;
  10316. this._totalAccumulated = 0;
  10317. this._lastSecAccumulated = 0;
  10318. this._lastSecTime = 0;
  10319. this._lastSecValueCount = 0;
  10320. }
  10321. Object.defineProperty(PerfCounter.prototype, "min", {
  10322. /**
  10323. * Returns the smallest value ever
  10324. */
  10325. get: function () {
  10326. return this._min;
  10327. },
  10328. enumerable: true,
  10329. configurable: true
  10330. });
  10331. Object.defineProperty(PerfCounter.prototype, "max", {
  10332. /**
  10333. * Returns the biggest value ever
  10334. */
  10335. get: function () {
  10336. return this._max;
  10337. },
  10338. enumerable: true,
  10339. configurable: true
  10340. });
  10341. Object.defineProperty(PerfCounter.prototype, "average", {
  10342. /**
  10343. * Returns the average value since the performance counter is running
  10344. */
  10345. get: function () {
  10346. return this._average;
  10347. },
  10348. enumerable: true,
  10349. configurable: true
  10350. });
  10351. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10352. /**
  10353. * Returns the average value of the last second the counter was monitored
  10354. */
  10355. get: function () {
  10356. return this._lastSecAverage;
  10357. },
  10358. enumerable: true,
  10359. configurable: true
  10360. });
  10361. Object.defineProperty(PerfCounter.prototype, "current", {
  10362. /**
  10363. * Returns the current value
  10364. */
  10365. get: function () {
  10366. return this._current;
  10367. },
  10368. enumerable: true,
  10369. configurable: true
  10370. });
  10371. Object.defineProperty(PerfCounter.prototype, "total", {
  10372. get: function () {
  10373. return this._totalAccumulated;
  10374. },
  10375. enumerable: true,
  10376. configurable: true
  10377. });
  10378. Object.defineProperty(PerfCounter.prototype, "count", {
  10379. get: function () {
  10380. return this._totalValueCount;
  10381. },
  10382. enumerable: true,
  10383. configurable: true
  10384. });
  10385. /**
  10386. * Call this method to start monitoring a new frame.
  10387. * 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.
  10388. */
  10389. PerfCounter.prototype.fetchNewFrame = function () {
  10390. this._totalValueCount++;
  10391. this._current = 0;
  10392. this._lastSecValueCount++;
  10393. };
  10394. /**
  10395. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10396. * @param newCount the count value to add to the monitored count
  10397. * @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.
  10398. */
  10399. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10400. if (!PerfCounter.Enabled) {
  10401. return;
  10402. }
  10403. this._current += newCount;
  10404. if (fetchResult) {
  10405. this._fetchResult();
  10406. }
  10407. };
  10408. /**
  10409. * Start monitoring this performance counter
  10410. */
  10411. PerfCounter.prototype.beginMonitoring = function () {
  10412. if (!PerfCounter.Enabled) {
  10413. return;
  10414. }
  10415. this._startMonitoringTime = Tools.Now;
  10416. };
  10417. /**
  10418. * Compute the time lapsed since the previous beginMonitoring() call.
  10419. * @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
  10420. */
  10421. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10422. if (newFrame === void 0) { newFrame = true; }
  10423. if (!PerfCounter.Enabled) {
  10424. return;
  10425. }
  10426. if (newFrame) {
  10427. this.fetchNewFrame();
  10428. }
  10429. var currentTime = Tools.Now;
  10430. this._current = currentTime - this._startMonitoringTime;
  10431. if (newFrame) {
  10432. this._fetchResult();
  10433. }
  10434. };
  10435. PerfCounter.prototype._fetchResult = function () {
  10436. this._totalAccumulated += this._current;
  10437. this._lastSecAccumulated += this._current;
  10438. // Min/Max update
  10439. this._min = Math.min(this._min, this._current);
  10440. this._max = Math.max(this._max, this._current);
  10441. this._average = this._totalAccumulated / this._totalValueCount;
  10442. // Reset last sec?
  10443. var now = Tools.Now;
  10444. if ((now - this._lastSecTime) > 1000) {
  10445. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10446. this._lastSecTime = now;
  10447. this._lastSecAccumulated = 0;
  10448. this._lastSecValueCount = 0;
  10449. }
  10450. };
  10451. PerfCounter.Enabled = true;
  10452. return PerfCounter;
  10453. }());
  10454. BABYLON.PerfCounter = PerfCounter;
  10455. /**
  10456. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10457. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10458. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10459. * @param name The name of the class, case should be preserved
  10460. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10461. */
  10462. function className(name, module) {
  10463. return function (target) {
  10464. target["__bjsclassName__"] = name;
  10465. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10466. };
  10467. }
  10468. BABYLON.className = className;
  10469. /**
  10470. * An implementation of a loop for asynchronous functions.
  10471. */
  10472. var AsyncLoop = /** @class */ (function () {
  10473. /**
  10474. * Constructor.
  10475. * @param iterations the number of iterations.
  10476. * @param func the function to run each iteration
  10477. * @param successCallback the callback that will be called upon succesful execution
  10478. * @param offset starting offset.
  10479. */
  10480. function AsyncLoop(
  10481. /**
  10482. * Defines the number of iterations for the loop
  10483. */
  10484. iterations, func, successCallback, offset) {
  10485. if (offset === void 0) { offset = 0; }
  10486. this.iterations = iterations;
  10487. this.index = offset - 1;
  10488. this._done = false;
  10489. this._fn = func;
  10490. this._successCallback = successCallback;
  10491. }
  10492. /**
  10493. * Execute the next iteration. Must be called after the last iteration was finished.
  10494. */
  10495. AsyncLoop.prototype.executeNext = function () {
  10496. if (!this._done) {
  10497. if (this.index + 1 < this.iterations) {
  10498. ++this.index;
  10499. this._fn(this);
  10500. }
  10501. else {
  10502. this.breakLoop();
  10503. }
  10504. }
  10505. };
  10506. /**
  10507. * Break the loop and run the success callback.
  10508. */
  10509. AsyncLoop.prototype.breakLoop = function () {
  10510. this._done = true;
  10511. this._successCallback();
  10512. };
  10513. /**
  10514. * Create and run an async loop.
  10515. * @param iterations the number of iterations.
  10516. * @param fn the function to run each iteration
  10517. * @param successCallback the callback that will be called upon succesful execution
  10518. * @param offset starting offset.
  10519. * @returns the created async loop object
  10520. */
  10521. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  10522. if (offset === void 0) { offset = 0; }
  10523. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  10524. loop.executeNext();
  10525. return loop;
  10526. };
  10527. /**
  10528. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10529. * @param iterations total number of iterations
  10530. * @param syncedIterations number of synchronous iterations in each async iteration.
  10531. * @param fn the function to call each iteration.
  10532. * @param callback a success call back that will be called when iterating stops.
  10533. * @param breakFunction a break condition (optional)
  10534. * @param timeout timeout settings for the setTimeout function. default - 0.
  10535. * @returns the created async loop object
  10536. */
  10537. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10538. if (timeout === void 0) { timeout = 0; }
  10539. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10540. if (breakFunction && breakFunction())
  10541. loop.breakLoop();
  10542. else {
  10543. setTimeout(function () {
  10544. for (var i = 0; i < syncedIterations; ++i) {
  10545. var iteration = (loop.index * syncedIterations) + i;
  10546. if (iteration >= iterations)
  10547. break;
  10548. fn(iteration);
  10549. if (breakFunction && breakFunction()) {
  10550. loop.breakLoop();
  10551. break;
  10552. }
  10553. }
  10554. loop.executeNext();
  10555. }, timeout);
  10556. }
  10557. }, callback);
  10558. };
  10559. return AsyncLoop;
  10560. }());
  10561. BABYLON.AsyncLoop = AsyncLoop;
  10562. })(BABYLON || (BABYLON = {}));
  10563. //# sourceMappingURL=babylon.tools.js.map
  10564. var BABYLON;
  10565. (function (BABYLON) {
  10566. var PromiseStates;
  10567. (function (PromiseStates) {
  10568. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10569. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10570. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10571. })(PromiseStates || (PromiseStates = {}));
  10572. var FulFillmentAgregator = /** @class */ (function () {
  10573. function FulFillmentAgregator() {
  10574. this.count = 0;
  10575. this.target = 0;
  10576. this.results = [];
  10577. }
  10578. return FulFillmentAgregator;
  10579. }());
  10580. var InternalPromise = /** @class */ (function () {
  10581. function InternalPromise(resolver) {
  10582. var _this = this;
  10583. this._state = PromiseStates.Pending;
  10584. this._children = new Array();
  10585. this._rejectWasConsumed = false;
  10586. if (!resolver) {
  10587. return;
  10588. }
  10589. try {
  10590. resolver(function (value) {
  10591. _this._resolve(value);
  10592. }, function (reason) {
  10593. _this._reject(reason);
  10594. });
  10595. }
  10596. catch (e) {
  10597. this._reject(e);
  10598. }
  10599. }
  10600. Object.defineProperty(InternalPromise.prototype, "_result", {
  10601. get: function () {
  10602. return this._resultValue;
  10603. },
  10604. set: function (value) {
  10605. this._resultValue = value;
  10606. if (this._parent && this._parent._result === undefined) {
  10607. this._parent._result = value;
  10608. }
  10609. },
  10610. enumerable: true,
  10611. configurable: true
  10612. });
  10613. InternalPromise.prototype.catch = function (onRejected) {
  10614. return this.then(undefined, onRejected);
  10615. };
  10616. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10617. var _this = this;
  10618. var newPromise = new InternalPromise();
  10619. newPromise._onFulfilled = onFulfilled;
  10620. newPromise._onRejected = onRejected;
  10621. // Composition
  10622. this._children.push(newPromise);
  10623. newPromise._parent = this;
  10624. if (this._state !== PromiseStates.Pending) {
  10625. BABYLON.Tools.SetImmediate(function () {
  10626. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10627. var returnedValue = newPromise._resolve(_this._result);
  10628. if (returnedValue !== undefined && returnedValue !== null) {
  10629. if (returnedValue._state !== undefined) {
  10630. var returnedPromise = returnedValue;
  10631. newPromise._children.push(returnedPromise);
  10632. returnedPromise._parent = newPromise;
  10633. newPromise = returnedPromise;
  10634. }
  10635. else {
  10636. newPromise._result = returnedValue;
  10637. }
  10638. }
  10639. }
  10640. else {
  10641. newPromise._reject(_this._reason);
  10642. }
  10643. });
  10644. }
  10645. return newPromise;
  10646. };
  10647. InternalPromise.prototype._moveChildren = function (children) {
  10648. var _this = this;
  10649. var _a;
  10650. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10651. this._children.forEach(function (child) {
  10652. child._parent = _this;
  10653. });
  10654. if (this._state === PromiseStates.Fulfilled) {
  10655. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10656. var child = _b[_i];
  10657. child._resolve(this._result);
  10658. }
  10659. }
  10660. else if (this._state === PromiseStates.Rejected) {
  10661. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10662. var child = _d[_c];
  10663. child._reject(this._reason);
  10664. }
  10665. }
  10666. };
  10667. InternalPromise.prototype._resolve = function (value) {
  10668. try {
  10669. this._state = PromiseStates.Fulfilled;
  10670. var returnedValue = null;
  10671. if (this._onFulfilled) {
  10672. returnedValue = this._onFulfilled(value);
  10673. }
  10674. if (returnedValue !== undefined && returnedValue !== null) {
  10675. if (returnedValue._state !== undefined) {
  10676. // Transmit children
  10677. var returnedPromise = returnedValue;
  10678. returnedPromise._parent = this;
  10679. returnedPromise._moveChildren(this._children);
  10680. value = returnedPromise._result;
  10681. }
  10682. else {
  10683. value = returnedValue;
  10684. }
  10685. }
  10686. this._result = value;
  10687. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10688. var child = _a[_i];
  10689. child._resolve(value);
  10690. }
  10691. this._children.length = 0;
  10692. delete this._onFulfilled;
  10693. delete this._onRejected;
  10694. }
  10695. catch (e) {
  10696. this._reject(e, true);
  10697. }
  10698. };
  10699. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10700. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10701. this._state = PromiseStates.Rejected;
  10702. this._reason = reason;
  10703. if (this._onRejected && !onLocalThrow) {
  10704. try {
  10705. this._onRejected(reason);
  10706. this._rejectWasConsumed = true;
  10707. }
  10708. catch (e) {
  10709. reason = e;
  10710. }
  10711. }
  10712. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10713. var child = _a[_i];
  10714. if (this._rejectWasConsumed) {
  10715. child._resolve(null);
  10716. }
  10717. else {
  10718. child._reject(reason);
  10719. }
  10720. }
  10721. this._children.length = 0;
  10722. delete this._onFulfilled;
  10723. delete this._onRejected;
  10724. };
  10725. InternalPromise.resolve = function (value) {
  10726. var newPromise = new InternalPromise();
  10727. newPromise._resolve(value);
  10728. return newPromise;
  10729. };
  10730. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10731. promise.then(function (value) {
  10732. agregator.results[index] = value;
  10733. agregator.count++;
  10734. if (agregator.count === agregator.target) {
  10735. agregator.rootPromise._resolve(agregator.results);
  10736. }
  10737. return null;
  10738. }, function (reason) {
  10739. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10740. agregator.rootPromise._reject(reason);
  10741. }
  10742. });
  10743. };
  10744. InternalPromise.all = function (promises) {
  10745. var newPromise = new InternalPromise();
  10746. var agregator = new FulFillmentAgregator();
  10747. agregator.target = promises.length;
  10748. agregator.rootPromise = newPromise;
  10749. if (promises.length) {
  10750. for (var index = 0; index < promises.length; index++) {
  10751. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10752. }
  10753. }
  10754. else {
  10755. newPromise._resolve([]);
  10756. }
  10757. return newPromise;
  10758. };
  10759. InternalPromise.race = function (promises) {
  10760. var newPromise = new InternalPromise();
  10761. if (promises.length) {
  10762. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10763. var promise = promises_1[_i];
  10764. promise.then(function (value) {
  10765. if (newPromise) {
  10766. newPromise._resolve(value);
  10767. newPromise = null;
  10768. }
  10769. return null;
  10770. }, function (reason) {
  10771. if (newPromise) {
  10772. newPromise._reject(reason);
  10773. newPromise = null;
  10774. }
  10775. });
  10776. }
  10777. }
  10778. return newPromise;
  10779. };
  10780. return InternalPromise;
  10781. }());
  10782. /**
  10783. * Helper class that provides a small promise polyfill
  10784. */
  10785. var PromisePolyfill = /** @class */ (function () {
  10786. function PromisePolyfill() {
  10787. }
  10788. /**
  10789. * Static function used to check if the polyfill is required
  10790. * If this is the case then the function will inject the polyfill to window.Promise
  10791. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10792. */
  10793. PromisePolyfill.Apply = function (force) {
  10794. if (force === void 0) { force = false; }
  10795. if (force || typeof Promise === 'undefined') {
  10796. var root = window;
  10797. root.Promise = InternalPromise;
  10798. }
  10799. };
  10800. return PromisePolyfill;
  10801. }());
  10802. BABYLON.PromisePolyfill = PromisePolyfill;
  10803. })(BABYLON || (BABYLON = {}));
  10804. //# sourceMappingURL=babylon.promise.js.map
  10805. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10806. var BABYLON;
  10807. (function (BABYLON) {
  10808. /**
  10809. * Helper class to push actions to a pool of workers.
  10810. */
  10811. var WorkerPool = /** @class */ (function () {
  10812. /**
  10813. * Constructor
  10814. * @param workers Array of workers to use for actions
  10815. */
  10816. function WorkerPool(workers) {
  10817. this._pendingActions = new Array();
  10818. this._workerInfos = workers.map(function (worker) { return ({
  10819. worker: worker,
  10820. active: false
  10821. }); });
  10822. }
  10823. /**
  10824. * Terminates all workers and clears any pending actions.
  10825. */
  10826. WorkerPool.prototype.dispose = function () {
  10827. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10828. var workerInfo = _a[_i];
  10829. workerInfo.worker.terminate();
  10830. }
  10831. delete this._workerInfos;
  10832. delete this._pendingActions;
  10833. };
  10834. /**
  10835. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10836. * pended until a worker has completed its action.
  10837. * @param action The action to perform. Call onComplete when the action is complete.
  10838. */
  10839. WorkerPool.prototype.push = function (action) {
  10840. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10841. var workerInfo = _a[_i];
  10842. if (!workerInfo.active) {
  10843. this._execute(workerInfo, action);
  10844. return;
  10845. }
  10846. }
  10847. this._pendingActions.push(action);
  10848. };
  10849. WorkerPool.prototype._execute = function (workerInfo, action) {
  10850. var _this = this;
  10851. workerInfo.active = true;
  10852. action(workerInfo.worker, function () {
  10853. workerInfo.active = false;
  10854. var nextAction = _this._pendingActions.shift();
  10855. if (nextAction) {
  10856. _this._execute(workerInfo, nextAction);
  10857. }
  10858. });
  10859. };
  10860. return WorkerPool;
  10861. }());
  10862. BABYLON.WorkerPool = WorkerPool;
  10863. })(BABYLON || (BABYLON = {}));
  10864. //# sourceMappingURL=babylon.workerPool.js.map
  10865. var BABYLON;
  10866. (function (BABYLON) {
  10867. /**
  10868. * @hidden
  10869. **/
  10870. var _AlphaState = /** @class */ (function () {
  10871. /**
  10872. * Initializes the state.
  10873. */
  10874. function _AlphaState() {
  10875. this._isAlphaBlendDirty = false;
  10876. this._isBlendFunctionParametersDirty = false;
  10877. this._isBlendEquationParametersDirty = false;
  10878. this._isBlendConstantsDirty = false;
  10879. this._alphaBlend = false;
  10880. this._blendFunctionParameters = new Array(4);
  10881. this._blendEquationParameters = new Array(2);
  10882. this._blendConstants = new Array(4);
  10883. this.reset();
  10884. }
  10885. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10886. get: function () {
  10887. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10893. get: function () {
  10894. return this._alphaBlend;
  10895. },
  10896. set: function (value) {
  10897. if (this._alphaBlend === value) {
  10898. return;
  10899. }
  10900. this._alphaBlend = value;
  10901. this._isAlphaBlendDirty = true;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10907. if (this._blendConstants[0] === r &&
  10908. this._blendConstants[1] === g &&
  10909. this._blendConstants[2] === b &&
  10910. this._blendConstants[3] === a) {
  10911. return;
  10912. }
  10913. this._blendConstants[0] = r;
  10914. this._blendConstants[1] = g;
  10915. this._blendConstants[2] = b;
  10916. this._blendConstants[3] = a;
  10917. this._isBlendConstantsDirty = true;
  10918. };
  10919. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10920. if (this._blendFunctionParameters[0] === value0 &&
  10921. this._blendFunctionParameters[1] === value1 &&
  10922. this._blendFunctionParameters[2] === value2 &&
  10923. this._blendFunctionParameters[3] === value3) {
  10924. return;
  10925. }
  10926. this._blendFunctionParameters[0] = value0;
  10927. this._blendFunctionParameters[1] = value1;
  10928. this._blendFunctionParameters[2] = value2;
  10929. this._blendFunctionParameters[3] = value3;
  10930. this._isBlendFunctionParametersDirty = true;
  10931. };
  10932. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10933. if (this._blendEquationParameters[0] === rgb &&
  10934. this._blendEquationParameters[1] === alpha) {
  10935. return;
  10936. }
  10937. this._blendEquationParameters[0] = rgb;
  10938. this._blendEquationParameters[1] = alpha;
  10939. this._isBlendEquationParametersDirty = true;
  10940. };
  10941. _AlphaState.prototype.reset = function () {
  10942. this._alphaBlend = false;
  10943. this._blendFunctionParameters[0] = null;
  10944. this._blendFunctionParameters[1] = null;
  10945. this._blendFunctionParameters[2] = null;
  10946. this._blendFunctionParameters[3] = null;
  10947. this._blendEquationParameters[0] = null;
  10948. this._blendEquationParameters[1] = null;
  10949. this._blendConstants[0] = null;
  10950. this._blendConstants[1] = null;
  10951. this._blendConstants[2] = null;
  10952. this._blendConstants[3] = null;
  10953. this._isAlphaBlendDirty = true;
  10954. this._isBlendFunctionParametersDirty = false;
  10955. this._isBlendEquationParametersDirty = false;
  10956. this._isBlendConstantsDirty = false;
  10957. };
  10958. _AlphaState.prototype.apply = function (gl) {
  10959. if (!this.isDirty) {
  10960. return;
  10961. }
  10962. // Alpha blend
  10963. if (this._isAlphaBlendDirty) {
  10964. if (this._alphaBlend) {
  10965. gl.enable(gl.BLEND);
  10966. }
  10967. else {
  10968. gl.disable(gl.BLEND);
  10969. }
  10970. this._isAlphaBlendDirty = false;
  10971. }
  10972. // Alpha function
  10973. if (this._isBlendFunctionParametersDirty) {
  10974. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10975. this._isBlendFunctionParametersDirty = false;
  10976. }
  10977. // Alpha equation
  10978. if (this._isBlendEquationParametersDirty) {
  10979. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  10980. this._isBlendEquationParametersDirty = false;
  10981. }
  10982. // Constants
  10983. if (this._isBlendConstantsDirty) {
  10984. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10985. this._isBlendConstantsDirty = false;
  10986. }
  10987. };
  10988. return _AlphaState;
  10989. }());
  10990. BABYLON._AlphaState = _AlphaState;
  10991. })(BABYLON || (BABYLON = {}));
  10992. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10993. var BABYLON;
  10994. (function (BABYLON) {
  10995. /**
  10996. * @hidden
  10997. **/
  10998. var _DepthCullingState = /** @class */ (function () {
  10999. /**
  11000. * Initializes the state.
  11001. */
  11002. function _DepthCullingState() {
  11003. this._isDepthTestDirty = false;
  11004. this._isDepthMaskDirty = false;
  11005. this._isDepthFuncDirty = false;
  11006. this._isCullFaceDirty = false;
  11007. this._isCullDirty = false;
  11008. this._isZOffsetDirty = false;
  11009. this._isFrontFaceDirty = false;
  11010. this.reset();
  11011. }
  11012. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11013. get: function () {
  11014. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11015. },
  11016. enumerable: true,
  11017. configurable: true
  11018. });
  11019. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11020. get: function () {
  11021. return this._zOffset;
  11022. },
  11023. set: function (value) {
  11024. if (this._zOffset === value) {
  11025. return;
  11026. }
  11027. this._zOffset = value;
  11028. this._isZOffsetDirty = true;
  11029. },
  11030. enumerable: true,
  11031. configurable: true
  11032. });
  11033. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11034. get: function () {
  11035. return this._cullFace;
  11036. },
  11037. set: function (value) {
  11038. if (this._cullFace === value) {
  11039. return;
  11040. }
  11041. this._cullFace = value;
  11042. this._isCullFaceDirty = true;
  11043. },
  11044. enumerable: true,
  11045. configurable: true
  11046. });
  11047. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11048. get: function () {
  11049. return this._cull;
  11050. },
  11051. set: function (value) {
  11052. if (this._cull === value) {
  11053. return;
  11054. }
  11055. this._cull = value;
  11056. this._isCullDirty = true;
  11057. },
  11058. enumerable: true,
  11059. configurable: true
  11060. });
  11061. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11062. get: function () {
  11063. return this._depthFunc;
  11064. },
  11065. set: function (value) {
  11066. if (this._depthFunc === value) {
  11067. return;
  11068. }
  11069. this._depthFunc = value;
  11070. this._isDepthFuncDirty = true;
  11071. },
  11072. enumerable: true,
  11073. configurable: true
  11074. });
  11075. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11076. get: function () {
  11077. return this._depthMask;
  11078. },
  11079. set: function (value) {
  11080. if (this._depthMask === value) {
  11081. return;
  11082. }
  11083. this._depthMask = value;
  11084. this._isDepthMaskDirty = true;
  11085. },
  11086. enumerable: true,
  11087. configurable: true
  11088. });
  11089. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11090. get: function () {
  11091. return this._depthTest;
  11092. },
  11093. set: function (value) {
  11094. if (this._depthTest === value) {
  11095. return;
  11096. }
  11097. this._depthTest = value;
  11098. this._isDepthTestDirty = true;
  11099. },
  11100. enumerable: true,
  11101. configurable: true
  11102. });
  11103. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11104. get: function () {
  11105. return this._frontFace;
  11106. },
  11107. set: function (value) {
  11108. if (this._frontFace === value) {
  11109. return;
  11110. }
  11111. this._frontFace = value;
  11112. this._isFrontFaceDirty = true;
  11113. },
  11114. enumerable: true,
  11115. configurable: true
  11116. });
  11117. _DepthCullingState.prototype.reset = function () {
  11118. this._depthMask = true;
  11119. this._depthTest = true;
  11120. this._depthFunc = null;
  11121. this._cullFace = null;
  11122. this._cull = null;
  11123. this._zOffset = 0;
  11124. this._frontFace = null;
  11125. this._isDepthTestDirty = true;
  11126. this._isDepthMaskDirty = true;
  11127. this._isDepthFuncDirty = false;
  11128. this._isCullFaceDirty = false;
  11129. this._isCullDirty = false;
  11130. this._isZOffsetDirty = false;
  11131. this._isFrontFaceDirty = false;
  11132. };
  11133. _DepthCullingState.prototype.apply = function (gl) {
  11134. if (!this.isDirty) {
  11135. return;
  11136. }
  11137. // Cull
  11138. if (this._isCullDirty) {
  11139. if (this.cull) {
  11140. gl.enable(gl.CULL_FACE);
  11141. }
  11142. else {
  11143. gl.disable(gl.CULL_FACE);
  11144. }
  11145. this._isCullDirty = false;
  11146. }
  11147. // Cull face
  11148. if (this._isCullFaceDirty) {
  11149. gl.cullFace(this.cullFace);
  11150. this._isCullFaceDirty = false;
  11151. }
  11152. // Depth mask
  11153. if (this._isDepthMaskDirty) {
  11154. gl.depthMask(this.depthMask);
  11155. this._isDepthMaskDirty = false;
  11156. }
  11157. // Depth test
  11158. if (this._isDepthTestDirty) {
  11159. if (this.depthTest) {
  11160. gl.enable(gl.DEPTH_TEST);
  11161. }
  11162. else {
  11163. gl.disable(gl.DEPTH_TEST);
  11164. }
  11165. this._isDepthTestDirty = false;
  11166. }
  11167. // Depth func
  11168. if (this._isDepthFuncDirty) {
  11169. gl.depthFunc(this.depthFunc);
  11170. this._isDepthFuncDirty = false;
  11171. }
  11172. // zOffset
  11173. if (this._isZOffsetDirty) {
  11174. if (this.zOffset) {
  11175. gl.enable(gl.POLYGON_OFFSET_FILL);
  11176. gl.polygonOffset(this.zOffset, 0);
  11177. }
  11178. else {
  11179. gl.disable(gl.POLYGON_OFFSET_FILL);
  11180. }
  11181. this._isZOffsetDirty = false;
  11182. }
  11183. // Front face
  11184. if (this._isFrontFaceDirty) {
  11185. gl.frontFace(this.frontFace);
  11186. this._isFrontFaceDirty = false;
  11187. }
  11188. };
  11189. return _DepthCullingState;
  11190. }());
  11191. BABYLON._DepthCullingState = _DepthCullingState;
  11192. })(BABYLON || (BABYLON = {}));
  11193. //# sourceMappingURL=babylon.depthCullingState.js.map
  11194. var BABYLON;
  11195. (function (BABYLON) {
  11196. /**
  11197. * @hidden
  11198. **/
  11199. var _StencilState = /** @class */ (function () {
  11200. function _StencilState() {
  11201. this._isStencilTestDirty = false;
  11202. this._isStencilMaskDirty = false;
  11203. this._isStencilFuncDirty = false;
  11204. this._isStencilOpDirty = false;
  11205. this.reset();
  11206. }
  11207. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11208. get: function () {
  11209. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11210. },
  11211. enumerable: true,
  11212. configurable: true
  11213. });
  11214. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11215. get: function () {
  11216. return this._stencilFunc;
  11217. },
  11218. set: function (value) {
  11219. if (this._stencilFunc === value) {
  11220. return;
  11221. }
  11222. this._stencilFunc = value;
  11223. this._isStencilFuncDirty = true;
  11224. },
  11225. enumerable: true,
  11226. configurable: true
  11227. });
  11228. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11229. get: function () {
  11230. return this._stencilFuncRef;
  11231. },
  11232. set: function (value) {
  11233. if (this._stencilFuncRef === value) {
  11234. return;
  11235. }
  11236. this._stencilFuncRef = value;
  11237. this._isStencilFuncDirty = true;
  11238. },
  11239. enumerable: true,
  11240. configurable: true
  11241. });
  11242. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11243. get: function () {
  11244. return this._stencilFuncMask;
  11245. },
  11246. set: function (value) {
  11247. if (this._stencilFuncMask === value) {
  11248. return;
  11249. }
  11250. this._stencilFuncMask = value;
  11251. this._isStencilFuncDirty = true;
  11252. },
  11253. enumerable: true,
  11254. configurable: true
  11255. });
  11256. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11257. get: function () {
  11258. return this._stencilOpStencilFail;
  11259. },
  11260. set: function (value) {
  11261. if (this._stencilOpStencilFail === value) {
  11262. return;
  11263. }
  11264. this._stencilOpStencilFail = value;
  11265. this._isStencilOpDirty = true;
  11266. },
  11267. enumerable: true,
  11268. configurable: true
  11269. });
  11270. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11271. get: function () {
  11272. return this._stencilOpDepthFail;
  11273. },
  11274. set: function (value) {
  11275. if (this._stencilOpDepthFail === value) {
  11276. return;
  11277. }
  11278. this._stencilOpDepthFail = value;
  11279. this._isStencilOpDirty = true;
  11280. },
  11281. enumerable: true,
  11282. configurable: true
  11283. });
  11284. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11285. get: function () {
  11286. return this._stencilOpStencilDepthPass;
  11287. },
  11288. set: function (value) {
  11289. if (this._stencilOpStencilDepthPass === value) {
  11290. return;
  11291. }
  11292. this._stencilOpStencilDepthPass = value;
  11293. this._isStencilOpDirty = true;
  11294. },
  11295. enumerable: true,
  11296. configurable: true
  11297. });
  11298. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11299. get: function () {
  11300. return this._stencilMask;
  11301. },
  11302. set: function (value) {
  11303. if (this._stencilMask === value) {
  11304. return;
  11305. }
  11306. this._stencilMask = value;
  11307. this._isStencilMaskDirty = true;
  11308. },
  11309. enumerable: true,
  11310. configurable: true
  11311. });
  11312. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11313. get: function () {
  11314. return this._stencilTest;
  11315. },
  11316. set: function (value) {
  11317. if (this._stencilTest === value) {
  11318. return;
  11319. }
  11320. this._stencilTest = value;
  11321. this._isStencilTestDirty = true;
  11322. },
  11323. enumerable: true,
  11324. configurable: true
  11325. });
  11326. _StencilState.prototype.reset = function () {
  11327. this._stencilTest = false;
  11328. this._stencilMask = 0xFF;
  11329. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11330. this._stencilFuncRef = 1;
  11331. this._stencilFuncMask = 0xFF;
  11332. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11333. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11334. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11335. this._isStencilTestDirty = true;
  11336. this._isStencilMaskDirty = true;
  11337. this._isStencilFuncDirty = true;
  11338. this._isStencilOpDirty = true;
  11339. };
  11340. _StencilState.prototype.apply = function (gl) {
  11341. if (!this.isDirty) {
  11342. return;
  11343. }
  11344. // Stencil test
  11345. if (this._isStencilTestDirty) {
  11346. if (this.stencilTest) {
  11347. gl.enable(gl.STENCIL_TEST);
  11348. }
  11349. else {
  11350. gl.disable(gl.STENCIL_TEST);
  11351. }
  11352. this._isStencilTestDirty = false;
  11353. }
  11354. // Stencil mask
  11355. if (this._isStencilMaskDirty) {
  11356. gl.stencilMask(this.stencilMask);
  11357. this._isStencilMaskDirty = false;
  11358. }
  11359. // Stencil func
  11360. if (this._isStencilFuncDirty) {
  11361. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11362. this._isStencilFuncDirty = false;
  11363. }
  11364. // Stencil op
  11365. if (this._isStencilOpDirty) {
  11366. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11367. this._isStencilOpDirty = false;
  11368. }
  11369. };
  11370. return _StencilState;
  11371. }());
  11372. BABYLON._StencilState = _StencilState;
  11373. })(BABYLON || (BABYLON = {}));
  11374. //# sourceMappingURL=babylon.stencilState.js.map
  11375. var __assign = (this && this.__assign) || function () {
  11376. __assign = Object.assign || function(t) {
  11377. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11378. s = arguments[i];
  11379. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11380. t[p] = s[p];
  11381. }
  11382. return t;
  11383. };
  11384. return __assign.apply(this, arguments);
  11385. };
  11386. var BABYLON;
  11387. (function (BABYLON) {
  11388. /**
  11389. * Keeps track of all the buffer info used in engine.
  11390. */
  11391. var BufferPointer = /** @class */ (function () {
  11392. function BufferPointer() {
  11393. }
  11394. return BufferPointer;
  11395. }());
  11396. /**
  11397. * Interface for attribute information associated with buffer instanciation
  11398. */
  11399. var InstancingAttributeInfo = /** @class */ (function () {
  11400. function InstancingAttributeInfo() {
  11401. }
  11402. return InstancingAttributeInfo;
  11403. }());
  11404. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11405. /**
  11406. * Define options used to create a render target texture
  11407. */
  11408. var RenderTargetCreationOptions = /** @class */ (function () {
  11409. function RenderTargetCreationOptions() {
  11410. }
  11411. return RenderTargetCreationOptions;
  11412. }());
  11413. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11414. /**
  11415. * Define options used to create a depth texture
  11416. */
  11417. var DepthTextureCreationOptions = /** @class */ (function () {
  11418. function DepthTextureCreationOptions() {
  11419. }
  11420. return DepthTextureCreationOptions;
  11421. }());
  11422. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11423. /**
  11424. * Class used to describe the capabilities of the engine relatively to the current browser
  11425. */
  11426. var EngineCapabilities = /** @class */ (function () {
  11427. function EngineCapabilities() {
  11428. }
  11429. return EngineCapabilities;
  11430. }());
  11431. BABYLON.EngineCapabilities = EngineCapabilities;
  11432. /**
  11433. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11434. */
  11435. var Engine = /** @class */ (function () {
  11436. /**
  11437. * Creates a new engine
  11438. * @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
  11439. * @param antialias defines enable antialiasing (default: false)
  11440. * @param options defines further options to be sent to the getContext() function
  11441. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11442. */
  11443. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11444. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11445. var _this = this;
  11446. // Public members
  11447. /**
  11448. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11449. */
  11450. this.forcePOTTextures = false;
  11451. /**
  11452. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11453. */
  11454. this.isFullscreen = false;
  11455. /**
  11456. * Gets a boolean indicating if the pointer is currently locked
  11457. */
  11458. this.isPointerLock = false;
  11459. /**
  11460. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11461. */
  11462. this.cullBackFaces = true;
  11463. /**
  11464. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11465. */
  11466. this.renderEvenInBackground = true;
  11467. /**
  11468. * Gets or sets a boolean indicating that cache can be kept between frames
  11469. */
  11470. this.preventCacheWipeBetweenFrames = false;
  11471. /**
  11472. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11473. **/
  11474. this.enableOfflineSupport = false;
  11475. /**
  11476. * 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)
  11477. **/
  11478. this.disableManifestCheck = false;
  11479. /**
  11480. * Gets the list of created scenes
  11481. */
  11482. this.scenes = new Array();
  11483. /**
  11484. * Gets the list of created postprocesses
  11485. */
  11486. this.postProcesses = new Array();
  11487. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11488. this.validateShaderPrograms = false;
  11489. // Observables
  11490. /**
  11491. * Observable event triggered each time the rendering canvas is resized
  11492. */
  11493. this.onResizeObservable = new BABYLON.Observable();
  11494. /**
  11495. * Observable event triggered each time the canvas loses focus
  11496. */
  11497. this.onCanvasBlurObservable = new BABYLON.Observable();
  11498. /**
  11499. * Observable event triggered each time the canvas gains focus
  11500. */
  11501. this.onCanvasFocusObservable = new BABYLON.Observable();
  11502. /**
  11503. * Observable event triggered each time the canvas receives pointerout event
  11504. */
  11505. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11506. /**
  11507. * Observable event triggered before each texture is initialized
  11508. */
  11509. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11510. //WebVR
  11511. this._vrDisplay = undefined;
  11512. this._vrSupported = false;
  11513. this._vrExclusivePointerMode = false;
  11514. // Uniform buffers list
  11515. /**
  11516. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11517. */
  11518. this.disableUniformBuffers = false;
  11519. /** @hidden */
  11520. this._uniformBuffers = new Array();
  11521. // Observables
  11522. /**
  11523. * Observable raised when the engine begins a new frame
  11524. */
  11525. this.onBeginFrameObservable = new BABYLON.Observable();
  11526. /**
  11527. * Observable raised when the engine ends the current frame
  11528. */
  11529. this.onEndFrameObservable = new BABYLON.Observable();
  11530. /**
  11531. * Observable raised when the engine is about to compile a shader
  11532. */
  11533. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11534. /**
  11535. * Observable raised when the engine has jsut compiled a shader
  11536. */
  11537. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11538. this._windowIsBackground = false;
  11539. this._webGLVersion = 1.0;
  11540. /** @hidden */
  11541. this._badOS = false;
  11542. /** @hidden */
  11543. this._badDesktopOS = false;
  11544. /**
  11545. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11546. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11547. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11548. */
  11549. this.disableTextureBindingOptimization = false;
  11550. /**
  11551. * Observable signaled when VR display mode changes
  11552. */
  11553. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11554. /**
  11555. * Observable signaled when VR request present is complete
  11556. */
  11557. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11558. /**
  11559. * Observable signaled when VR request present starts
  11560. */
  11561. this.onVRRequestPresentStart = new BABYLON.Observable();
  11562. this._colorWrite = true;
  11563. /** @hidden */
  11564. this._drawCalls = new BABYLON.PerfCounter();
  11565. /** @hidden */
  11566. this._textureCollisions = new BABYLON.PerfCounter();
  11567. this._renderingQueueLaunched = false;
  11568. this._activeRenderLoops = new Array();
  11569. // Deterministic lockstepMaxSteps
  11570. this._deterministicLockstep = false;
  11571. this._lockstepMaxSteps = 4;
  11572. // Lost context
  11573. /**
  11574. * Observable signaled when a context lost event is raised
  11575. */
  11576. this.onContextLostObservable = new BABYLON.Observable();
  11577. /**
  11578. * Observable signaled when a context restored event is raised
  11579. */
  11580. this.onContextRestoredObservable = new BABYLON.Observable();
  11581. this._contextWasLost = false;
  11582. this._doNotHandleContextLost = false;
  11583. // FPS
  11584. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11585. this._fps = 60;
  11586. this._deltaTime = 0;
  11587. /**
  11588. * Turn this value on if you want to pause FPS computation when in background
  11589. */
  11590. this.disablePerformanceMonitorInBackground = false;
  11591. // States
  11592. /** @hidden */
  11593. this._depthCullingState = new BABYLON._DepthCullingState();
  11594. /** @hidden */
  11595. this._stencilState = new BABYLON._StencilState();
  11596. /** @hidden */
  11597. this._alphaState = new BABYLON._AlphaState();
  11598. /** @hidden */
  11599. this._alphaMode = Engine.ALPHA_DISABLE;
  11600. // Cache
  11601. this._internalTexturesCache = new Array();
  11602. /** @hidden */
  11603. this._activeChannel = 0;
  11604. this._currentTextureChannel = -1;
  11605. /** @hidden */
  11606. this._boundTexturesCache = {};
  11607. this._compiledEffects = {};
  11608. this._vertexAttribArraysEnabled = [];
  11609. this._uintIndicesCurrentlySet = false;
  11610. this._currentBoundBuffer = new Array();
  11611. /** @hidden */
  11612. this._currentFramebuffer = null;
  11613. this._currentBufferPointers = new Array();
  11614. this._currentInstanceLocations = new Array();
  11615. this._currentInstanceBuffers = new Array();
  11616. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11617. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11618. this._vaoRecordInProgress = false;
  11619. this._mustWipeVertexAttributes = false;
  11620. this._nextFreeTextureSlots = new Array();
  11621. this._maxSimultaneousTextures = 0;
  11622. this._activeRequests = new Array();
  11623. // Hardware supported Compressed Textures
  11624. this._texturesSupported = new Array();
  11625. /**
  11626. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11627. */
  11628. this.premultipliedAlpha = true;
  11629. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11630. this._onVRFullScreenTriggered = function () {
  11631. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11632. //get the old size before we change
  11633. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11634. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11635. //get the width and height, change the render size
  11636. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11637. _this.setHardwareScalingLevel(1);
  11638. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11639. }
  11640. else {
  11641. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11642. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11643. }
  11644. };
  11645. this._unpackFlipYCached = null;
  11646. /**
  11647. * In case you are sharing the context with other applications, it might
  11648. * be interested to not cache the unpack flip y state to ensure a consistent
  11649. * value would be set.
  11650. */
  11651. this.enableUnpackFlipYCached = true;
  11652. this._boundUniforms = {};
  11653. // Register promises
  11654. BABYLON.PromisePolyfill.Apply();
  11655. var canvas = null;
  11656. Engine.Instances.push(this);
  11657. if (!canvasOrContext) {
  11658. return;
  11659. }
  11660. options = options || {};
  11661. if (canvasOrContext.getContext) {
  11662. canvas = canvasOrContext;
  11663. this._renderingCanvas = canvas;
  11664. if (antialias != null) {
  11665. options.antialias = antialias;
  11666. }
  11667. if (options.deterministicLockstep === undefined) {
  11668. options.deterministicLockstep = false;
  11669. }
  11670. if (options.lockstepMaxSteps === undefined) {
  11671. options.lockstepMaxSteps = 4;
  11672. }
  11673. if (options.preserveDrawingBuffer === undefined) {
  11674. options.preserveDrawingBuffer = false;
  11675. }
  11676. if (options.audioEngine === undefined) {
  11677. options.audioEngine = true;
  11678. }
  11679. if (options.stencil === undefined) {
  11680. options.stencil = true;
  11681. }
  11682. if (options.premultipliedAlpha === false) {
  11683. this.premultipliedAlpha = false;
  11684. }
  11685. this._deterministicLockstep = options.deterministicLockstep;
  11686. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11687. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11688. // Exceptions
  11689. if (navigator && navigator.userAgent) {
  11690. var ua = navigator.userAgent;
  11691. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11692. var exception = _a[_i];
  11693. var key = exception.key;
  11694. var targets = exception.targets;
  11695. if (ua.indexOf(key) > -1) {
  11696. if (exception.capture && exception.captureConstraint) {
  11697. var capture = exception.capture;
  11698. var constraint = exception.captureConstraint;
  11699. var regex = new RegExp(capture);
  11700. var matches = regex.exec(ua);
  11701. if (matches && matches.length > 0) {
  11702. var capturedValue = parseInt(matches[matches.length - 1]);
  11703. if (capturedValue >= constraint) {
  11704. continue;
  11705. }
  11706. }
  11707. }
  11708. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11709. var target = targets_1[_b];
  11710. switch (target) {
  11711. case "uniformBuffer":
  11712. this.disableUniformBuffers = true;
  11713. break;
  11714. case "textureBindingOptimization":
  11715. this.disableTextureBindingOptimization = true;
  11716. break;
  11717. }
  11718. }
  11719. }
  11720. }
  11721. }
  11722. // GL
  11723. if (!options.disableWebGL2Support) {
  11724. try {
  11725. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11726. if (this._gl) {
  11727. this._webGLVersion = 2.0;
  11728. }
  11729. }
  11730. catch (e) {
  11731. // Do nothing
  11732. }
  11733. }
  11734. if (!this._gl) {
  11735. if (!canvas) {
  11736. throw new Error("The provided canvas is null or undefined.");
  11737. }
  11738. try {
  11739. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11740. }
  11741. catch (e) {
  11742. throw new Error("WebGL not supported");
  11743. }
  11744. }
  11745. if (!this._gl) {
  11746. throw new Error("WebGL not supported");
  11747. }
  11748. this._onCanvasFocus = function () {
  11749. _this.onCanvasFocusObservable.notifyObservers(_this);
  11750. };
  11751. this._onCanvasBlur = function () {
  11752. _this.onCanvasBlurObservable.notifyObservers(_this);
  11753. };
  11754. canvas.addEventListener("focus", this._onCanvasFocus);
  11755. canvas.addEventListener("blur", this._onCanvasBlur);
  11756. this._onBlur = function () {
  11757. if (_this.disablePerformanceMonitorInBackground) {
  11758. _this._performanceMonitor.disable();
  11759. }
  11760. _this._windowIsBackground = true;
  11761. };
  11762. this._onFocus = function () {
  11763. if (_this.disablePerformanceMonitorInBackground) {
  11764. _this._performanceMonitor.enable();
  11765. }
  11766. _this._windowIsBackground = false;
  11767. };
  11768. this._onCanvasPointerOut = function (ev) {
  11769. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11770. };
  11771. window.addEventListener("blur", this._onBlur);
  11772. window.addEventListener("focus", this._onFocus);
  11773. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11774. // Context lost
  11775. if (!this._doNotHandleContextLost) {
  11776. this._onContextLost = function (evt) {
  11777. evt.preventDefault();
  11778. _this._contextWasLost = true;
  11779. BABYLON.Tools.Warn("WebGL context lost.");
  11780. _this.onContextLostObservable.notifyObservers(_this);
  11781. };
  11782. this._onContextRestored = function (evt) {
  11783. // Adding a timeout to avoid race condition at browser level
  11784. setTimeout(function () {
  11785. // Rebuild gl context
  11786. _this._initGLContext();
  11787. // Rebuild effects
  11788. _this._rebuildEffects();
  11789. // Rebuild textures
  11790. _this._rebuildInternalTextures();
  11791. // Rebuild buffers
  11792. _this._rebuildBuffers();
  11793. // Cache
  11794. _this.wipeCaches(true);
  11795. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11796. _this.onContextRestoredObservable.notifyObservers(_this);
  11797. _this._contextWasLost = false;
  11798. }, 0);
  11799. };
  11800. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11801. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11802. }
  11803. }
  11804. else {
  11805. this._gl = canvasOrContext;
  11806. this._renderingCanvas = this._gl.canvas;
  11807. if (this._gl.renderbufferStorageMultisample) {
  11808. this._webGLVersion = 2.0;
  11809. }
  11810. options.stencil = this._gl.getContextAttributes().stencil;
  11811. }
  11812. // Viewport
  11813. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11814. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11815. this.resize();
  11816. this._isStencilEnable = options.stencil ? true : false;
  11817. this._initGLContext();
  11818. if (canvas) {
  11819. // Fullscreen
  11820. this._onFullscreenChange = function () {
  11821. if (document.fullscreen !== undefined) {
  11822. _this.isFullscreen = document.fullscreen;
  11823. }
  11824. else if (document.mozFullScreen !== undefined) {
  11825. _this.isFullscreen = document.mozFullScreen;
  11826. }
  11827. else if (document.webkitIsFullScreen !== undefined) {
  11828. _this.isFullscreen = document.webkitIsFullScreen;
  11829. }
  11830. else if (document.msIsFullScreen !== undefined) {
  11831. _this.isFullscreen = document.msIsFullScreen;
  11832. }
  11833. // Pointer lock
  11834. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11835. canvas.requestPointerLock = canvas.requestPointerLock ||
  11836. canvas.msRequestPointerLock ||
  11837. canvas.mozRequestPointerLock ||
  11838. canvas.webkitRequestPointerLock;
  11839. if (canvas.requestPointerLock) {
  11840. canvas.requestPointerLock();
  11841. }
  11842. }
  11843. };
  11844. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11845. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11846. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11847. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11848. // Pointer lock
  11849. this._onPointerLockChange = function () {
  11850. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11851. document.webkitPointerLockElement === canvas ||
  11852. document.msPointerLockElement === canvas ||
  11853. document.pointerLockElement === canvas);
  11854. };
  11855. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11856. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11857. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11858. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11859. this._onVRDisplayPointerRestricted = function () {
  11860. if (canvas) {
  11861. canvas.requestPointerLock();
  11862. }
  11863. };
  11864. this._onVRDisplayPointerUnrestricted = function () {
  11865. document.exitPointerLock();
  11866. };
  11867. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11868. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11869. }
  11870. // Create Audio Engine if needed.
  11871. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  11872. Engine.audioEngine = Engine.AudioEngineFactory(this);
  11873. }
  11874. // Prepare buffer pointers
  11875. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11876. this._currentBufferPointers[i] = new BufferPointer();
  11877. }
  11878. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11879. // Load WebVR Devices
  11880. if (options.autoEnableWebVR) {
  11881. this.initWebVR();
  11882. }
  11883. // Detect if we are running on a faulty buggy OS.
  11884. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11885. // Detect if we are running on a faulty buggy desktop OS.
  11886. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11887. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11888. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11889. }
  11890. Object.defineProperty(Engine, "LastCreatedEngine", {
  11891. /**
  11892. * Gets the latest created engine
  11893. */
  11894. get: function () {
  11895. if (Engine.Instances.length === 0) {
  11896. return null;
  11897. }
  11898. return Engine.Instances[Engine.Instances.length - 1];
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(Engine, "LastCreatedScene", {
  11904. /**
  11905. * Gets the latest created scene
  11906. */
  11907. get: function () {
  11908. var lastCreatedEngine = Engine.LastCreatedEngine;
  11909. if (!lastCreatedEngine) {
  11910. return null;
  11911. }
  11912. if (lastCreatedEngine.scenes.length === 0) {
  11913. return null;
  11914. }
  11915. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11916. },
  11917. enumerable: true,
  11918. configurable: true
  11919. });
  11920. /**
  11921. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11922. * @param flag defines which part of the materials must be marked as dirty
  11923. * @param predicate defines a predicate used to filter which materials should be affected
  11924. */
  11925. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11926. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11927. var engine = Engine.Instances[engineIndex];
  11928. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11929. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11930. }
  11931. }
  11932. };
  11933. Object.defineProperty(Engine, "Version", {
  11934. /**
  11935. * Returns the current version of the framework
  11936. */
  11937. get: function () {
  11938. return "3.3.0-rc.1";
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11944. /**
  11945. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11946. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11947. */
  11948. get: function () {
  11949. return this._vrExclusivePointerMode;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11955. /**
  11956. * Gets a boolean indicating that the engine supports uniform buffers
  11957. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11958. */
  11959. get: function () {
  11960. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11966. /**
  11967. * Gets a boolean indicating that only power of 2 textures are supported
  11968. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11969. */
  11970. get: function () {
  11971. return this._webGLVersion < 2 || this.forcePOTTextures;
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11977. /**
  11978. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11979. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11980. */
  11981. get: function () {
  11982. return this._doNotHandleContextLost;
  11983. },
  11984. set: function (value) {
  11985. this._doNotHandleContextLost = value;
  11986. },
  11987. enumerable: true,
  11988. configurable: true
  11989. });
  11990. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11991. /**
  11992. * Gets the performance monitor attached to this engine
  11993. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11994. */
  11995. get: function () {
  11996. return this._performanceMonitor;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12002. /**
  12003. * Gets the list of texture formats supported
  12004. */
  12005. get: function () {
  12006. return this._texturesSupported;
  12007. },
  12008. enumerable: true,
  12009. configurable: true
  12010. });
  12011. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12012. /**
  12013. * Gets the list of texture formats in use
  12014. */
  12015. get: function () {
  12016. return this._textureFormatInUse;
  12017. },
  12018. enumerable: true,
  12019. configurable: true
  12020. });
  12021. Object.defineProperty(Engine.prototype, "currentViewport", {
  12022. /**
  12023. * Gets the current viewport
  12024. */
  12025. get: function () {
  12026. return this._cachedViewport;
  12027. },
  12028. enumerable: true,
  12029. configurable: true
  12030. });
  12031. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12032. /**
  12033. * Gets the default empty texture
  12034. */
  12035. get: function () {
  12036. if (!this._emptyTexture) {
  12037. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12038. }
  12039. return this._emptyTexture;
  12040. },
  12041. enumerable: true,
  12042. configurable: true
  12043. });
  12044. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12045. /**
  12046. * Gets the default empty 3D texture
  12047. */
  12048. get: function () {
  12049. if (!this._emptyTexture3D) {
  12050. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12051. }
  12052. return this._emptyTexture3D;
  12053. },
  12054. enumerable: true,
  12055. configurable: true
  12056. });
  12057. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12058. /**
  12059. * Gets the default empty cube texture
  12060. */
  12061. get: function () {
  12062. if (!this._emptyCubeTexture) {
  12063. var faceData = new Uint8Array(4);
  12064. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12065. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12066. }
  12067. return this._emptyCubeTexture;
  12068. },
  12069. enumerable: true,
  12070. configurable: true
  12071. });
  12072. Engine.prototype._rebuildInternalTextures = function () {
  12073. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12074. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12075. var internalTexture = currentState_1[_i];
  12076. internalTexture._rebuild();
  12077. }
  12078. };
  12079. Engine.prototype._rebuildEffects = function () {
  12080. for (var key in this._compiledEffects) {
  12081. var effect = this._compiledEffects[key];
  12082. effect._prepareEffect();
  12083. }
  12084. BABYLON.Effect.ResetCache();
  12085. };
  12086. Engine.prototype._rebuildBuffers = function () {
  12087. // Index / Vertex
  12088. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12089. var scene = _a[_i];
  12090. scene.resetCachedMaterial();
  12091. scene._rebuildGeometries();
  12092. scene._rebuildTextures();
  12093. }
  12094. // Uniforms
  12095. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12096. var uniformBuffer = _c[_b];
  12097. uniformBuffer._rebuild();
  12098. }
  12099. };
  12100. Engine.prototype._initGLContext = function () {
  12101. // Caps
  12102. this._caps = new EngineCapabilities();
  12103. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12104. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12105. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12106. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12107. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12108. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12109. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12110. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12111. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12112. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12113. // Infos
  12114. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12115. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12116. if (rendererInfo != null) {
  12117. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12118. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12119. }
  12120. if (!this._glVendor) {
  12121. this._glVendor = "Unknown vendor";
  12122. }
  12123. if (!this._glRenderer) {
  12124. this._glRenderer = "Unknown renderer";
  12125. }
  12126. // Constants
  12127. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12128. if (this._gl.RGBA16F !== 0x881A) {
  12129. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12130. }
  12131. if (this._gl.RGBA32F !== 0x8814) {
  12132. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12133. }
  12134. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12135. this._gl.DEPTH24_STENCIL8 = 35056;
  12136. }
  12137. // Extensions
  12138. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12139. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12140. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12141. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12142. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12143. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12144. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12145. 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');
  12146. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12147. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12148. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12149. this._caps.highPrecisionShaderSupported = true;
  12150. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12151. if (this._caps.timerQuery) {
  12152. if (this._webGLVersion === 1) {
  12153. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12154. }
  12155. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12156. }
  12157. // Checks if some of the format renders first to allow the use of webgl inspector.
  12158. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12159. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12160. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12161. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12162. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12163. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12164. if (this._webGLVersion > 1) {
  12165. this._gl.HALF_FLOAT_OES = 0x140B;
  12166. }
  12167. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12168. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12169. // Draw buffers
  12170. if (this._webGLVersion > 1) {
  12171. this._caps.drawBuffersExtension = true;
  12172. }
  12173. else {
  12174. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12175. if (drawBuffersExtension !== null) {
  12176. this._caps.drawBuffersExtension = true;
  12177. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12178. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12179. for (var i = 0; i < 16; i++) {
  12180. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12181. }
  12182. }
  12183. else {
  12184. this._caps.drawBuffersExtension = false;
  12185. }
  12186. }
  12187. // Depth Texture
  12188. if (this._webGLVersion > 1) {
  12189. this._caps.depthTextureExtension = true;
  12190. }
  12191. else {
  12192. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12193. if (depthTextureExtension != null) {
  12194. this._caps.depthTextureExtension = true;
  12195. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12196. }
  12197. }
  12198. // Vertex array object
  12199. if (this._webGLVersion > 1) {
  12200. this._caps.vertexArrayObject = true;
  12201. }
  12202. else {
  12203. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12204. if (vertexArrayObjectExtension != null) {
  12205. this._caps.vertexArrayObject = true;
  12206. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12207. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12208. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12209. }
  12210. else {
  12211. this._caps.vertexArrayObject = false;
  12212. }
  12213. }
  12214. // Instances count
  12215. if (this._webGLVersion > 1) {
  12216. this._caps.instancedArrays = true;
  12217. }
  12218. else {
  12219. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12220. if (instanceExtension != null) {
  12221. this._caps.instancedArrays = true;
  12222. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12223. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12224. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12225. }
  12226. else {
  12227. this._caps.instancedArrays = false;
  12228. }
  12229. }
  12230. // Intelligently add supported compressed formats in order to check for.
  12231. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12232. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12233. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12234. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12235. if (this._caps.astc)
  12236. this.texturesSupported.push('-astc.ktx');
  12237. if (this._caps.s3tc)
  12238. this.texturesSupported.push('-dxt.ktx');
  12239. if (this._caps.pvrtc)
  12240. this.texturesSupported.push('-pvrtc.ktx');
  12241. if (this._caps.etc2)
  12242. this.texturesSupported.push('-etc2.ktx');
  12243. if (this._caps.etc1)
  12244. this.texturesSupported.push('-etc1.ktx');
  12245. if (this._gl.getShaderPrecisionFormat) {
  12246. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12247. if (highp) {
  12248. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12249. }
  12250. }
  12251. // Depth buffer
  12252. this.setDepthBuffer(true);
  12253. this.setDepthFunctionToLessOrEqual();
  12254. this.setDepthWrite(true);
  12255. // Texture maps
  12256. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12257. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12258. this._nextFreeTextureSlots.push(slot);
  12259. }
  12260. };
  12261. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12262. /**
  12263. * Gets version of the current webGL context
  12264. */
  12265. get: function () {
  12266. return this._webGLVersion;
  12267. },
  12268. enumerable: true,
  12269. configurable: true
  12270. });
  12271. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12272. /**
  12273. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12274. */
  12275. get: function () {
  12276. return this._isStencilEnable;
  12277. },
  12278. enumerable: true,
  12279. configurable: true
  12280. });
  12281. Engine.prototype._prepareWorkingCanvas = function () {
  12282. if (this._workingCanvas) {
  12283. return;
  12284. }
  12285. this._workingCanvas = document.createElement("canvas");
  12286. var context = this._workingCanvas.getContext("2d");
  12287. if (context) {
  12288. this._workingContext = context;
  12289. }
  12290. };
  12291. /**
  12292. * Reset the texture cache to empty state
  12293. */
  12294. Engine.prototype.resetTextureCache = function () {
  12295. for (var key in this._boundTexturesCache) {
  12296. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12297. continue;
  12298. }
  12299. var boundTexture = this._boundTexturesCache[key];
  12300. if (boundTexture) {
  12301. this._removeDesignatedSlot(boundTexture);
  12302. }
  12303. this._boundTexturesCache[key] = null;
  12304. }
  12305. if (!this.disableTextureBindingOptimization) {
  12306. this._nextFreeTextureSlots = [];
  12307. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12308. this._nextFreeTextureSlots.push(slot);
  12309. }
  12310. }
  12311. this._currentTextureChannel = -1;
  12312. };
  12313. /**
  12314. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12315. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12316. * @returns true if engine is in deterministic lock step mode
  12317. */
  12318. Engine.prototype.isDeterministicLockStep = function () {
  12319. return this._deterministicLockstep;
  12320. };
  12321. /**
  12322. * Gets the max steps when engine is running in deterministic lock step
  12323. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12324. * @returns the max steps
  12325. */
  12326. Engine.prototype.getLockstepMaxSteps = function () {
  12327. return this._lockstepMaxSteps;
  12328. };
  12329. /**
  12330. * Gets an object containing information about the current webGL context
  12331. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12332. */
  12333. Engine.prototype.getGlInfo = function () {
  12334. return {
  12335. vendor: this._glVendor,
  12336. renderer: this._glRenderer,
  12337. version: this._glVersion
  12338. };
  12339. };
  12340. /**
  12341. * Gets current aspect ratio
  12342. * @param camera defines the camera to use to get the aspect ratio
  12343. * @param useScreen defines if screen size must be used (or the current render target if any)
  12344. * @returns a number defining the aspect ratio
  12345. */
  12346. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12347. if (useScreen === void 0) { useScreen = false; }
  12348. var viewport = camera.viewport;
  12349. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12350. };
  12351. /**
  12352. * Gets current screen aspect ratio
  12353. * @returns a number defining the aspect ratio
  12354. */
  12355. Engine.prototype.getScreenAspectRatio = function () {
  12356. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12357. };
  12358. /**
  12359. * Gets the current render width
  12360. * @param useScreen defines if screen size must be used (or the current render target if any)
  12361. * @returns a number defining the current render width
  12362. */
  12363. Engine.prototype.getRenderWidth = function (useScreen) {
  12364. if (useScreen === void 0) { useScreen = false; }
  12365. if (!useScreen && this._currentRenderTarget) {
  12366. return this._currentRenderTarget.width;
  12367. }
  12368. return this._gl.drawingBufferWidth;
  12369. };
  12370. /**
  12371. * Gets the current render height
  12372. * @param useScreen defines if screen size must be used (or the current render target if any)
  12373. * @returns a number defining the current render height
  12374. */
  12375. Engine.prototype.getRenderHeight = function (useScreen) {
  12376. if (useScreen === void 0) { useScreen = false; }
  12377. if (!useScreen && this._currentRenderTarget) {
  12378. return this._currentRenderTarget.height;
  12379. }
  12380. return this._gl.drawingBufferHeight;
  12381. };
  12382. /**
  12383. * Gets the HTML canvas attached with the current webGL context
  12384. * @returns a HTML canvas
  12385. */
  12386. Engine.prototype.getRenderingCanvas = function () {
  12387. return this._renderingCanvas;
  12388. };
  12389. /**
  12390. * Gets the client rect of the HTML canvas attached with the current webGL context
  12391. * @returns a client rectanglee
  12392. */
  12393. Engine.prototype.getRenderingCanvasClientRect = function () {
  12394. if (!this._renderingCanvas) {
  12395. return null;
  12396. }
  12397. return this._renderingCanvas.getBoundingClientRect();
  12398. };
  12399. /**
  12400. * Defines the hardware scaling level.
  12401. * By default the hardware scaling level is computed from the window device ratio.
  12402. * 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.
  12403. * @param level defines the level to use
  12404. */
  12405. Engine.prototype.setHardwareScalingLevel = function (level) {
  12406. this._hardwareScalingLevel = level;
  12407. this.resize();
  12408. };
  12409. /**
  12410. * Gets the current hardware scaling level.
  12411. * By default the hardware scaling level is computed from the window device ratio.
  12412. * 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.
  12413. * @returns a number indicating the current hardware scaling level
  12414. */
  12415. Engine.prototype.getHardwareScalingLevel = function () {
  12416. return this._hardwareScalingLevel;
  12417. };
  12418. /**
  12419. * Gets the list of loaded textures
  12420. * @returns an array containing all loaded textures
  12421. */
  12422. Engine.prototype.getLoadedTexturesCache = function () {
  12423. return this._internalTexturesCache;
  12424. };
  12425. /**
  12426. * Gets the object containing all engine capabilities
  12427. * @returns the EngineCapabilities object
  12428. */
  12429. Engine.prototype.getCaps = function () {
  12430. return this._caps;
  12431. };
  12432. Object.defineProperty(Engine.prototype, "drawCalls", {
  12433. /** @hidden */
  12434. get: function () {
  12435. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12436. return 0;
  12437. },
  12438. enumerable: true,
  12439. configurable: true
  12440. });
  12441. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12442. /** @hidden */
  12443. get: function () {
  12444. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12445. return null;
  12446. },
  12447. enumerable: true,
  12448. configurable: true
  12449. });
  12450. /**
  12451. * Gets the current depth function
  12452. * @returns a number defining the depth function
  12453. */
  12454. Engine.prototype.getDepthFunction = function () {
  12455. return this._depthCullingState.depthFunc;
  12456. };
  12457. /**
  12458. * Sets the current depth function
  12459. * @param depthFunc defines the function to use
  12460. */
  12461. Engine.prototype.setDepthFunction = function (depthFunc) {
  12462. this._depthCullingState.depthFunc = depthFunc;
  12463. };
  12464. /**
  12465. * Sets the current depth function to GREATER
  12466. */
  12467. Engine.prototype.setDepthFunctionToGreater = function () {
  12468. this._depthCullingState.depthFunc = this._gl.GREATER;
  12469. };
  12470. /**
  12471. * Sets the current depth function to GEQUAL
  12472. */
  12473. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12474. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12475. };
  12476. /**
  12477. * Sets the current depth function to LESS
  12478. */
  12479. Engine.prototype.setDepthFunctionToLess = function () {
  12480. this._depthCullingState.depthFunc = this._gl.LESS;
  12481. };
  12482. /**
  12483. * Sets the current depth function to LEQUAL
  12484. */
  12485. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12486. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12487. };
  12488. /**
  12489. * Gets a boolean indicating if stencil buffer is enabled
  12490. * @returns the current stencil buffer state
  12491. */
  12492. Engine.prototype.getStencilBuffer = function () {
  12493. return this._stencilState.stencilTest;
  12494. };
  12495. /**
  12496. * Enable or disable the stencil buffer
  12497. * @param enable defines if the stencil buffer must be enabled or disabled
  12498. */
  12499. Engine.prototype.setStencilBuffer = function (enable) {
  12500. this._stencilState.stencilTest = enable;
  12501. };
  12502. /**
  12503. * Gets the current stencil mask
  12504. * @returns a number defining the new stencil mask to use
  12505. */
  12506. Engine.prototype.getStencilMask = function () {
  12507. return this._stencilState.stencilMask;
  12508. };
  12509. /**
  12510. * Sets the current stencil mask
  12511. * @param mask defines the new stencil mask to use
  12512. */
  12513. Engine.prototype.setStencilMask = function (mask) {
  12514. this._stencilState.stencilMask = mask;
  12515. };
  12516. /**
  12517. * Gets the current stencil function
  12518. * @returns a number defining the stencil function to use
  12519. */
  12520. Engine.prototype.getStencilFunction = function () {
  12521. return this._stencilState.stencilFunc;
  12522. };
  12523. /**
  12524. * Gets the current stencil reference value
  12525. * @returns a number defining the stencil reference value to use
  12526. */
  12527. Engine.prototype.getStencilFunctionReference = function () {
  12528. return this._stencilState.stencilFuncRef;
  12529. };
  12530. /**
  12531. * Gets the current stencil mask
  12532. * @returns a number defining the stencil mask to use
  12533. */
  12534. Engine.prototype.getStencilFunctionMask = function () {
  12535. return this._stencilState.stencilFuncMask;
  12536. };
  12537. /**
  12538. * Sets the current stencil function
  12539. * @param stencilFunc defines the new stencil function to use
  12540. */
  12541. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12542. this._stencilState.stencilFunc = stencilFunc;
  12543. };
  12544. /**
  12545. * Sets the current stencil reference
  12546. * @param reference defines the new stencil reference to use
  12547. */
  12548. Engine.prototype.setStencilFunctionReference = function (reference) {
  12549. this._stencilState.stencilFuncRef = reference;
  12550. };
  12551. /**
  12552. * Sets the current stencil mask
  12553. * @param mask defines the new stencil mask to use
  12554. */
  12555. Engine.prototype.setStencilFunctionMask = function (mask) {
  12556. this._stencilState.stencilFuncMask = mask;
  12557. };
  12558. /**
  12559. * Gets the current stencil operation when stencil fails
  12560. * @returns a number defining stencil operation to use when stencil fails
  12561. */
  12562. Engine.prototype.getStencilOperationFail = function () {
  12563. return this._stencilState.stencilOpStencilFail;
  12564. };
  12565. /**
  12566. * Gets the current stencil operation when depth fails
  12567. * @returns a number defining stencil operation to use when depth fails
  12568. */
  12569. Engine.prototype.getStencilOperationDepthFail = function () {
  12570. return this._stencilState.stencilOpDepthFail;
  12571. };
  12572. /**
  12573. * Gets the current stencil operation when stencil passes
  12574. * @returns a number defining stencil operation to use when stencil passes
  12575. */
  12576. Engine.prototype.getStencilOperationPass = function () {
  12577. return this._stencilState.stencilOpStencilDepthPass;
  12578. };
  12579. /**
  12580. * Sets the stencil operation to use when stencil fails
  12581. * @param operation defines the stencil operation to use when stencil fails
  12582. */
  12583. Engine.prototype.setStencilOperationFail = function (operation) {
  12584. this._stencilState.stencilOpStencilFail = operation;
  12585. };
  12586. /**
  12587. * Sets the stencil operation to use when depth fails
  12588. * @param operation defines the stencil operation to use when depth fails
  12589. */
  12590. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12591. this._stencilState.stencilOpDepthFail = operation;
  12592. };
  12593. /**
  12594. * Sets the stencil operation to use when stencil passes
  12595. * @param operation defines the stencil operation to use when stencil passes
  12596. */
  12597. Engine.prototype.setStencilOperationPass = function (operation) {
  12598. this._stencilState.stencilOpStencilDepthPass = operation;
  12599. };
  12600. /**
  12601. * Sets a boolean indicating if the dithering state is enabled or disabled
  12602. * @param value defines the dithering state
  12603. */
  12604. Engine.prototype.setDitheringState = function (value) {
  12605. if (value) {
  12606. this._gl.enable(this._gl.DITHER);
  12607. }
  12608. else {
  12609. this._gl.disable(this._gl.DITHER);
  12610. }
  12611. };
  12612. /**
  12613. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12614. * @param value defines the rasterizer state
  12615. */
  12616. Engine.prototype.setRasterizerState = function (value) {
  12617. if (value) {
  12618. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12619. }
  12620. else {
  12621. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12622. }
  12623. };
  12624. /**
  12625. * stop executing a render loop function and remove it from the execution array
  12626. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12627. */
  12628. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12629. if (!renderFunction) {
  12630. this._activeRenderLoops = [];
  12631. return;
  12632. }
  12633. var index = this._activeRenderLoops.indexOf(renderFunction);
  12634. if (index >= 0) {
  12635. this._activeRenderLoops.splice(index, 1);
  12636. }
  12637. };
  12638. /** @hidden */
  12639. Engine.prototype._renderLoop = function () {
  12640. if (!this._contextWasLost) {
  12641. var shouldRender = true;
  12642. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12643. shouldRender = false;
  12644. }
  12645. if (shouldRender) {
  12646. // Start new frame
  12647. this.beginFrame();
  12648. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12649. var renderFunction = this._activeRenderLoops[index];
  12650. renderFunction();
  12651. }
  12652. // Present
  12653. this.endFrame();
  12654. }
  12655. }
  12656. if (this._activeRenderLoops.length > 0) {
  12657. // Register new frame
  12658. var requester = null;
  12659. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12660. requester = this._vrDisplay;
  12661. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12662. }
  12663. else {
  12664. this._renderingQueueLaunched = false;
  12665. }
  12666. };
  12667. /**
  12668. * Register and execute a render loop. The engine can have more than one render function
  12669. * @param renderFunction defines the function to continuously execute
  12670. */
  12671. Engine.prototype.runRenderLoop = function (renderFunction) {
  12672. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12673. return;
  12674. }
  12675. this._activeRenderLoops.push(renderFunction);
  12676. if (!this._renderingQueueLaunched) {
  12677. this._renderingQueueLaunched = true;
  12678. this._bindedRenderFunction = this._renderLoop.bind(this);
  12679. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12680. }
  12681. };
  12682. /**
  12683. * Toggle full screen mode
  12684. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12685. */
  12686. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12687. if (this.isFullscreen) {
  12688. BABYLON.Tools.ExitFullscreen();
  12689. }
  12690. else {
  12691. this._pointerLockRequested = requestPointerLock;
  12692. if (this._renderingCanvas) {
  12693. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12694. }
  12695. }
  12696. };
  12697. /**
  12698. * Clear the current render buffer or the current render target (if any is set up)
  12699. * @param color defines the color to use
  12700. * @param backBuffer defines if the back buffer must be cleared
  12701. * @param depth defines if the depth buffer must be cleared
  12702. * @param stencil defines if the stencil buffer must be cleared
  12703. */
  12704. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12705. if (stencil === void 0) { stencil = false; }
  12706. this.applyStates();
  12707. var mode = 0;
  12708. if (backBuffer && color) {
  12709. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12710. mode |= this._gl.COLOR_BUFFER_BIT;
  12711. }
  12712. if (depth) {
  12713. this._gl.clearDepth(1.0);
  12714. mode |= this._gl.DEPTH_BUFFER_BIT;
  12715. }
  12716. if (stencil) {
  12717. this._gl.clearStencil(0);
  12718. mode |= this._gl.STENCIL_BUFFER_BIT;
  12719. }
  12720. this._gl.clear(mode);
  12721. };
  12722. /**
  12723. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12724. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12725. * @param y defines the y-coordinate of the corner of the clear rectangle
  12726. * @param width defines the width of the clear rectangle
  12727. * @param height defines the height of the clear rectangle
  12728. * @param clearColor defines the clear color
  12729. */
  12730. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12731. var gl = this._gl;
  12732. // Save state
  12733. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12734. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12735. // Change state
  12736. gl.enable(gl.SCISSOR_TEST);
  12737. gl.scissor(x, y, width, height);
  12738. // Clear
  12739. this.clear(clearColor, true, true, true);
  12740. // Restore state
  12741. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12742. if (curScissor === true) {
  12743. gl.enable(gl.SCISSOR_TEST);
  12744. }
  12745. else {
  12746. gl.disable(gl.SCISSOR_TEST);
  12747. }
  12748. };
  12749. /** @hidden */
  12750. Engine.prototype._viewport = function (x, y, width, height) {
  12751. if (x !== this._viewportCached.x ||
  12752. y !== this._viewportCached.y ||
  12753. width !== this._viewportCached.z ||
  12754. height !== this._viewportCached.w) {
  12755. this._viewportCached.x = x;
  12756. this._viewportCached.y = y;
  12757. this._viewportCached.z = width;
  12758. this._viewportCached.w = height;
  12759. this._gl.viewport(x, y, width, height);
  12760. }
  12761. };
  12762. /**
  12763. * Set the WebGL's viewport
  12764. * @param viewport defines the viewport element to be used
  12765. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12766. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12767. */
  12768. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12769. var width = requiredWidth || this.getRenderWidth();
  12770. var height = requiredHeight || this.getRenderHeight();
  12771. var x = viewport.x || 0;
  12772. var y = viewport.y || 0;
  12773. this._cachedViewport = viewport;
  12774. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12775. };
  12776. /**
  12777. * Directly set the WebGL Viewport
  12778. * @param x defines the x coordinate of the viewport (in screen space)
  12779. * @param y defines the y coordinate of the viewport (in screen space)
  12780. * @param width defines the width of the viewport (in screen space)
  12781. * @param height defines the height of the viewport (in screen space)
  12782. * @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
  12783. */
  12784. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12785. var currentViewport = this._cachedViewport;
  12786. this._cachedViewport = null;
  12787. this._viewport(x, y, width, height);
  12788. return currentViewport;
  12789. };
  12790. /**
  12791. * Begin a new frame
  12792. */
  12793. Engine.prototype.beginFrame = function () {
  12794. this.onBeginFrameObservable.notifyObservers(this);
  12795. this._measureFps();
  12796. };
  12797. /**
  12798. * Enf the current frame
  12799. */
  12800. Engine.prototype.endFrame = function () {
  12801. // Force a flush in case we are using a bad OS.
  12802. if (this._badOS) {
  12803. this.flushFramebuffer();
  12804. }
  12805. // Submit frame to the vr device, if enabled
  12806. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12807. // TODO: We should only submit the frame if we read frameData successfully.
  12808. this._vrDisplay.submitFrame();
  12809. }
  12810. this.onEndFrameObservable.notifyObservers(this);
  12811. };
  12812. /**
  12813. * Resize the view according to the canvas' size
  12814. */
  12815. Engine.prototype.resize = function () {
  12816. // We're not resizing the size of the canvas while in VR mode & presenting
  12817. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12818. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12819. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12820. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12821. }
  12822. };
  12823. /**
  12824. * Force a specific size of the canvas
  12825. * @param width defines the new canvas' width
  12826. * @param height defines the new canvas' height
  12827. */
  12828. Engine.prototype.setSize = function (width, height) {
  12829. if (!this._renderingCanvas) {
  12830. return;
  12831. }
  12832. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12833. return;
  12834. }
  12835. this._renderingCanvas.width = width;
  12836. this._renderingCanvas.height = height;
  12837. for (var index = 0; index < this.scenes.length; index++) {
  12838. var scene = this.scenes[index];
  12839. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12840. var cam = scene.cameras[camIndex];
  12841. cam._currentRenderId = 0;
  12842. }
  12843. }
  12844. if (this.onResizeObservable.hasObservers) {
  12845. this.onResizeObservable.notifyObservers(this);
  12846. }
  12847. };
  12848. // WebVR functions
  12849. /**
  12850. * Gets a boolean indicating if a webVR device was detected
  12851. * @returns true if a webVR device was detected
  12852. */
  12853. Engine.prototype.isVRDevicePresent = function () {
  12854. return !!this._vrDisplay;
  12855. };
  12856. /**
  12857. * Gets the current webVR device
  12858. * @returns the current webVR device (or null)
  12859. */
  12860. Engine.prototype.getVRDevice = function () {
  12861. return this._vrDisplay;
  12862. };
  12863. /**
  12864. * Initializes a webVR display and starts listening to display change events
  12865. * The onVRDisplayChangedObservable will be notified upon these changes
  12866. * @returns The onVRDisplayChangedObservable
  12867. */
  12868. Engine.prototype.initWebVR = function () {
  12869. this.initWebVRAsync();
  12870. return this.onVRDisplayChangedObservable;
  12871. };
  12872. /**
  12873. * Initializes a webVR display and starts listening to display change events
  12874. * The onVRDisplayChangedObservable will be notified upon these changes
  12875. * @returns A promise containing a VRDisplay and if vr is supported
  12876. */
  12877. Engine.prototype.initWebVRAsync = function () {
  12878. var _this = this;
  12879. var notifyObservers = function () {
  12880. var eventArgs = {
  12881. vrDisplay: _this._vrDisplay,
  12882. vrSupported: _this._vrSupported
  12883. };
  12884. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12885. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12886. };
  12887. if (!this._onVrDisplayConnect) {
  12888. this._onVrDisplayConnect = function (event) {
  12889. _this._vrDisplay = event.display;
  12890. notifyObservers();
  12891. };
  12892. this._onVrDisplayDisconnect = function () {
  12893. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12894. _this._vrDisplay = undefined;
  12895. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12896. notifyObservers();
  12897. };
  12898. this._onVrDisplayPresentChange = function () {
  12899. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12900. };
  12901. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12902. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12903. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12904. }
  12905. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12906. this._webVRInitPromise.then(notifyObservers);
  12907. return this._webVRInitPromise;
  12908. };
  12909. /**
  12910. * Call this function to switch to webVR mode
  12911. * Will do nothing if webVR is not supported or if there is no webVR device
  12912. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12913. */
  12914. Engine.prototype.enableVR = function () {
  12915. var _this = this;
  12916. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12917. var onResolved = function () {
  12918. _this.onVRRequestPresentComplete.notifyObservers(true);
  12919. _this._onVRFullScreenTriggered();
  12920. };
  12921. var onRejected = function () {
  12922. _this.onVRRequestPresentComplete.notifyObservers(false);
  12923. };
  12924. this.onVRRequestPresentStart.notifyObservers(this);
  12925. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12926. }
  12927. };
  12928. /**
  12929. * Call this function to leave webVR mode
  12930. * Will do nothing if webVR is not supported or if there is no webVR device
  12931. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12932. */
  12933. Engine.prototype.disableVR = function () {
  12934. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12935. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12936. }
  12937. };
  12938. Engine.prototype._getVRDisplaysAsync = function () {
  12939. var _this = this;
  12940. return new Promise(function (res, rej) {
  12941. if (navigator.getVRDisplays) {
  12942. navigator.getVRDisplays().then(function (devices) {
  12943. _this._vrSupported = true;
  12944. // note that devices may actually be an empty array. This is fine;
  12945. // we expect this._vrDisplay to be undefined in this case.
  12946. _this._vrDisplay = devices[0];
  12947. res({
  12948. vrDisplay: _this._vrDisplay,
  12949. vrSupported: _this._vrSupported
  12950. });
  12951. });
  12952. }
  12953. else {
  12954. _this._vrDisplay = undefined;
  12955. _this._vrSupported = false;
  12956. res({
  12957. vrDisplay: _this._vrDisplay,
  12958. vrSupported: _this._vrSupported
  12959. });
  12960. }
  12961. });
  12962. };
  12963. /**
  12964. * Binds the frame buffer to the specified texture.
  12965. * @param texture The texture to render to or null for the default canvas
  12966. * @param faceIndex The face of the texture to render to in case of cube texture
  12967. * @param requiredWidth The width of the target to render to
  12968. * @param requiredHeight The height of the target to render to
  12969. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12970. * @param depthStencilTexture The depth stencil texture to use to render
  12971. * @param lodLevel defines le lod level to bind to the frame buffer
  12972. */
  12973. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12974. if (lodLevel === void 0) { lodLevel = 0; }
  12975. if (this._currentRenderTarget) {
  12976. this.unBindFramebuffer(this._currentRenderTarget);
  12977. }
  12978. this._currentRenderTarget = texture;
  12979. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12980. var gl = this._gl;
  12981. if (texture.isCube) {
  12982. if (faceIndex === undefined) {
  12983. faceIndex = 0;
  12984. }
  12985. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12986. if (depthStencilTexture) {
  12987. if (depthStencilTexture._generateStencilBuffer) {
  12988. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12989. }
  12990. else {
  12991. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12992. }
  12993. }
  12994. }
  12995. if (this._cachedViewport && !forceFullscreenViewport) {
  12996. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12997. }
  12998. else {
  12999. if (!requiredWidth) {
  13000. requiredWidth = texture.width;
  13001. if (lodLevel) {
  13002. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13003. }
  13004. }
  13005. if (!requiredHeight) {
  13006. requiredHeight = texture.height;
  13007. if (lodLevel) {
  13008. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13009. }
  13010. }
  13011. this._viewport(0, 0, requiredWidth, requiredHeight);
  13012. }
  13013. this.wipeCaches();
  13014. };
  13015. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13016. if (this._currentFramebuffer !== framebuffer) {
  13017. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13018. this._currentFramebuffer = framebuffer;
  13019. }
  13020. };
  13021. /**
  13022. * Unbind the current render target texture from the webGL context
  13023. * @param texture defines the render target texture to unbind
  13024. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13025. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13026. */
  13027. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13028. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13029. this._currentRenderTarget = null;
  13030. // If MSAA, we need to bitblt back to main texture
  13031. var gl = this._gl;
  13032. if (texture._MSAAFramebuffer) {
  13033. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13034. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13035. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13036. }
  13037. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13038. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13039. gl.generateMipmap(gl.TEXTURE_2D);
  13040. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13041. }
  13042. if (onBeforeUnbind) {
  13043. if (texture._MSAAFramebuffer) {
  13044. // Bind the correct framebuffer
  13045. this.bindUnboundFramebuffer(texture._framebuffer);
  13046. }
  13047. onBeforeUnbind();
  13048. }
  13049. this.bindUnboundFramebuffer(null);
  13050. };
  13051. /**
  13052. * Unbind a list of render target textures from the webGL context
  13053. * This is used only when drawBuffer extension or webGL2 are active
  13054. * @param textures defines the render target textures to unbind
  13055. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13056. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13057. */
  13058. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13059. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13060. this._currentRenderTarget = null;
  13061. // If MSAA, we need to bitblt back to main texture
  13062. var gl = this._gl;
  13063. if (textures[0]._MSAAFramebuffer) {
  13064. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13065. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13066. var attachments = textures[0]._attachments;
  13067. if (!attachments) {
  13068. attachments = new Array(textures.length);
  13069. textures[0]._attachments = attachments;
  13070. }
  13071. for (var i = 0; i < textures.length; i++) {
  13072. var texture = textures[i];
  13073. for (var j = 0; j < attachments.length; j++) {
  13074. attachments[j] = gl.NONE;
  13075. }
  13076. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13077. gl.readBuffer(attachments[i]);
  13078. gl.drawBuffers(attachments);
  13079. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13080. }
  13081. for (var i = 0; i < attachments.length; i++) {
  13082. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13083. }
  13084. gl.drawBuffers(attachments);
  13085. }
  13086. for (var i = 0; i < textures.length; i++) {
  13087. var texture = textures[i];
  13088. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13089. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13090. gl.generateMipmap(gl.TEXTURE_2D);
  13091. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13092. }
  13093. }
  13094. if (onBeforeUnbind) {
  13095. if (textures[0]._MSAAFramebuffer) {
  13096. // Bind the correct framebuffer
  13097. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13098. }
  13099. onBeforeUnbind();
  13100. }
  13101. this.bindUnboundFramebuffer(null);
  13102. };
  13103. /**
  13104. * Force the mipmap generation for the given render target texture
  13105. * @param texture defines the render target texture to use
  13106. */
  13107. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13108. if (texture.generateMipMaps) {
  13109. var gl = this._gl;
  13110. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13111. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13112. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13113. }
  13114. };
  13115. /**
  13116. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13117. */
  13118. Engine.prototype.flushFramebuffer = function () {
  13119. this._gl.flush();
  13120. };
  13121. /**
  13122. * Unbind the current render target and bind the default framebuffer
  13123. */
  13124. Engine.prototype.restoreDefaultFramebuffer = function () {
  13125. if (this._currentRenderTarget) {
  13126. this.unBindFramebuffer(this._currentRenderTarget);
  13127. }
  13128. else {
  13129. this.bindUnboundFramebuffer(null);
  13130. }
  13131. if (this._cachedViewport) {
  13132. this.setViewport(this._cachedViewport);
  13133. }
  13134. this.wipeCaches();
  13135. };
  13136. // UBOs
  13137. /**
  13138. * Create an uniform buffer
  13139. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13140. * @param elements defines the content of the uniform buffer
  13141. * @returns the webGL uniform buffer
  13142. */
  13143. Engine.prototype.createUniformBuffer = function (elements) {
  13144. var ubo = this._gl.createBuffer();
  13145. if (!ubo) {
  13146. throw new Error("Unable to create uniform buffer");
  13147. }
  13148. this.bindUniformBuffer(ubo);
  13149. if (elements instanceof Float32Array) {
  13150. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13151. }
  13152. else {
  13153. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13154. }
  13155. this.bindUniformBuffer(null);
  13156. ubo.references = 1;
  13157. return ubo;
  13158. };
  13159. /**
  13160. * Create a dynamic uniform buffer
  13161. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13162. * @param elements defines the content of the uniform buffer
  13163. * @returns the webGL uniform buffer
  13164. */
  13165. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13166. var ubo = this._gl.createBuffer();
  13167. if (!ubo) {
  13168. throw new Error("Unable to create dynamic uniform buffer");
  13169. }
  13170. this.bindUniformBuffer(ubo);
  13171. if (elements instanceof Float32Array) {
  13172. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13173. }
  13174. else {
  13175. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13176. }
  13177. this.bindUniformBuffer(null);
  13178. ubo.references = 1;
  13179. return ubo;
  13180. };
  13181. /**
  13182. * Update an existing uniform buffer
  13183. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13184. * @param uniformBuffer defines the target uniform buffer
  13185. * @param elements defines the content to update
  13186. * @param offset defines the offset in the uniform buffer where update should start
  13187. * @param count defines the size of the data to update
  13188. */
  13189. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13190. this.bindUniformBuffer(uniformBuffer);
  13191. if (offset === undefined) {
  13192. offset = 0;
  13193. }
  13194. if (count === undefined) {
  13195. if (elements instanceof Float32Array) {
  13196. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13197. }
  13198. else {
  13199. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13200. }
  13201. }
  13202. else {
  13203. if (elements instanceof Float32Array) {
  13204. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13205. }
  13206. else {
  13207. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13208. }
  13209. }
  13210. this.bindUniformBuffer(null);
  13211. };
  13212. // VBOs
  13213. Engine.prototype._resetVertexBufferBinding = function () {
  13214. this.bindArrayBuffer(null);
  13215. this._cachedVertexBuffers = null;
  13216. };
  13217. /**
  13218. * Creates a vertex buffer
  13219. * @param data the data for the vertex buffer
  13220. * @returns the new WebGL static buffer
  13221. */
  13222. Engine.prototype.createVertexBuffer = function (data) {
  13223. var vbo = this._gl.createBuffer();
  13224. if (!vbo) {
  13225. throw new Error("Unable to create vertex buffer");
  13226. }
  13227. this.bindArrayBuffer(vbo);
  13228. if (data instanceof Array) {
  13229. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13230. }
  13231. else {
  13232. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13233. }
  13234. this._resetVertexBufferBinding();
  13235. vbo.references = 1;
  13236. return vbo;
  13237. };
  13238. /**
  13239. * Creates a dynamic vertex buffer
  13240. * @param data the data for the dynamic vertex buffer
  13241. * @returns the new WebGL dynamic buffer
  13242. */
  13243. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13244. var vbo = this._gl.createBuffer();
  13245. if (!vbo) {
  13246. throw new Error("Unable to create dynamic vertex buffer");
  13247. }
  13248. this.bindArrayBuffer(vbo);
  13249. if (data instanceof Array) {
  13250. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13251. }
  13252. else {
  13253. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13254. }
  13255. this._resetVertexBufferBinding();
  13256. vbo.references = 1;
  13257. return vbo;
  13258. };
  13259. /**
  13260. * Update a dynamic index buffer
  13261. * @param indexBuffer defines the target index buffer
  13262. * @param indices defines the data to update
  13263. * @param offset defines the offset in the target index buffer where update should start
  13264. */
  13265. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13266. if (offset === void 0) { offset = 0; }
  13267. // Force cache update
  13268. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13269. this.bindIndexBuffer(indexBuffer);
  13270. var arrayBuffer;
  13271. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13272. arrayBuffer = indices;
  13273. }
  13274. else {
  13275. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13276. }
  13277. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13278. this._resetIndexBufferBinding();
  13279. };
  13280. /**
  13281. * Updates a dynamic vertex buffer.
  13282. * @param vertexBuffer the vertex buffer to update
  13283. * @param data the data used to update the vertex buffer
  13284. * @param byteOffset the byte offset of the data
  13285. * @param byteLength the byte length of the data
  13286. */
  13287. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13288. this.bindArrayBuffer(vertexBuffer);
  13289. if (byteOffset === undefined) {
  13290. byteOffset = 0;
  13291. }
  13292. if (byteLength === undefined) {
  13293. if (data instanceof Array) {
  13294. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13295. }
  13296. else {
  13297. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13298. }
  13299. }
  13300. else {
  13301. if (data instanceof Array) {
  13302. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13303. }
  13304. else {
  13305. if (data instanceof ArrayBuffer) {
  13306. data = new Uint8Array(data, byteOffset, byteLength);
  13307. }
  13308. else {
  13309. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13310. }
  13311. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13312. }
  13313. }
  13314. this._resetVertexBufferBinding();
  13315. };
  13316. Engine.prototype._resetIndexBufferBinding = function () {
  13317. this.bindIndexBuffer(null);
  13318. this._cachedIndexBuffer = null;
  13319. };
  13320. /**
  13321. * Creates a new index buffer
  13322. * @param indices defines the content of the index buffer
  13323. * @param updatable defines if the index buffer must be updatable
  13324. * @returns a new webGL buffer
  13325. */
  13326. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13327. var vbo = this._gl.createBuffer();
  13328. if (!vbo) {
  13329. throw new Error("Unable to create index buffer");
  13330. }
  13331. this.bindIndexBuffer(vbo);
  13332. // Check for 32 bits indices
  13333. var arrayBuffer;
  13334. var need32Bits = false;
  13335. if (indices instanceof Uint16Array) {
  13336. arrayBuffer = indices;
  13337. }
  13338. else {
  13339. //check 32 bit support
  13340. if (this._caps.uintIndices) {
  13341. if (indices instanceof Uint32Array) {
  13342. arrayBuffer = indices;
  13343. need32Bits = true;
  13344. }
  13345. else {
  13346. //number[] or Int32Array, check if 32 bit is necessary
  13347. for (var index = 0; index < indices.length; index++) {
  13348. if (indices[index] > 65535) {
  13349. need32Bits = true;
  13350. break;
  13351. }
  13352. }
  13353. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13354. }
  13355. }
  13356. else {
  13357. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13358. arrayBuffer = new Uint16Array(indices);
  13359. }
  13360. }
  13361. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13362. this._resetIndexBufferBinding();
  13363. vbo.references = 1;
  13364. vbo.is32Bits = need32Bits;
  13365. return vbo;
  13366. };
  13367. /**
  13368. * Bind a webGL buffer to the webGL context
  13369. * @param buffer defines the buffer to bind
  13370. */
  13371. Engine.prototype.bindArrayBuffer = function (buffer) {
  13372. if (!this._vaoRecordInProgress) {
  13373. this._unbindVertexArrayObject();
  13374. }
  13375. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13376. };
  13377. /**
  13378. * Bind an uniform buffer to the current webGL context
  13379. * @param buffer defines the buffer to bind
  13380. */
  13381. Engine.prototype.bindUniformBuffer = function (buffer) {
  13382. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13383. };
  13384. /**
  13385. * Bind a buffer to the current webGL context at a given location
  13386. * @param buffer defines the buffer to bind
  13387. * @param location defines the index where to bind the buffer
  13388. */
  13389. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13390. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13391. };
  13392. /**
  13393. * Bind a specific block at a given index in a specific shader program
  13394. * @param shaderProgram defines the shader program
  13395. * @param blockName defines the block name
  13396. * @param index defines the index where to bind the block
  13397. */
  13398. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13399. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13400. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13401. };
  13402. ;
  13403. Engine.prototype.bindIndexBuffer = function (buffer) {
  13404. if (!this._vaoRecordInProgress) {
  13405. this._unbindVertexArrayObject();
  13406. }
  13407. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13408. };
  13409. Engine.prototype.bindBuffer = function (buffer, target) {
  13410. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13411. this._gl.bindBuffer(target, buffer);
  13412. this._currentBoundBuffer[target] = buffer;
  13413. }
  13414. };
  13415. /**
  13416. * update the bound buffer with the given data
  13417. * @param data defines the data to update
  13418. */
  13419. Engine.prototype.updateArrayBuffer = function (data) {
  13420. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13421. };
  13422. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13423. var pointer = this._currentBufferPointers[indx];
  13424. var changed = false;
  13425. if (!pointer.active) {
  13426. changed = true;
  13427. pointer.active = true;
  13428. pointer.index = indx;
  13429. pointer.size = size;
  13430. pointer.type = type;
  13431. pointer.normalized = normalized;
  13432. pointer.stride = stride;
  13433. pointer.offset = offset;
  13434. pointer.buffer = buffer;
  13435. }
  13436. else {
  13437. if (pointer.buffer !== buffer) {
  13438. pointer.buffer = buffer;
  13439. changed = true;
  13440. }
  13441. if (pointer.size !== size) {
  13442. pointer.size = size;
  13443. changed = true;
  13444. }
  13445. if (pointer.type !== type) {
  13446. pointer.type = type;
  13447. changed = true;
  13448. }
  13449. if (pointer.normalized !== normalized) {
  13450. pointer.normalized = normalized;
  13451. changed = true;
  13452. }
  13453. if (pointer.stride !== stride) {
  13454. pointer.stride = stride;
  13455. changed = true;
  13456. }
  13457. if (pointer.offset !== offset) {
  13458. pointer.offset = offset;
  13459. changed = true;
  13460. }
  13461. }
  13462. if (changed || this._vaoRecordInProgress) {
  13463. this.bindArrayBuffer(buffer);
  13464. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13465. }
  13466. };
  13467. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13468. if (indexBuffer == null) {
  13469. return;
  13470. }
  13471. if (this._cachedIndexBuffer !== indexBuffer) {
  13472. this._cachedIndexBuffer = indexBuffer;
  13473. this.bindIndexBuffer(indexBuffer);
  13474. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13475. }
  13476. };
  13477. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13478. var attributes = effect.getAttributesNames();
  13479. if (!this._vaoRecordInProgress) {
  13480. this._unbindVertexArrayObject();
  13481. }
  13482. this.unbindAllAttributes();
  13483. for (var index = 0; index < attributes.length; index++) {
  13484. var order = effect.getAttributeLocation(index);
  13485. if (order >= 0) {
  13486. var vertexBuffer = vertexBuffers[attributes[index]];
  13487. if (!vertexBuffer) {
  13488. continue;
  13489. }
  13490. this._gl.enableVertexAttribArray(order);
  13491. if (!this._vaoRecordInProgress) {
  13492. this._vertexAttribArraysEnabled[order] = true;
  13493. }
  13494. var buffer = vertexBuffer.getBuffer();
  13495. if (buffer) {
  13496. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13497. if (vertexBuffer.getIsInstanced()) {
  13498. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13499. if (!this._vaoRecordInProgress) {
  13500. this._currentInstanceLocations.push(order);
  13501. this._currentInstanceBuffers.push(buffer);
  13502. }
  13503. }
  13504. }
  13505. }
  13506. }
  13507. };
  13508. /**
  13509. * Records a vertex array object
  13510. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13511. * @param vertexBuffers defines the list of vertex buffers to store
  13512. * @param indexBuffer defines the index buffer to store
  13513. * @param effect defines the effect to store
  13514. * @returns the new vertex array object
  13515. */
  13516. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13517. var vao = this._gl.createVertexArray();
  13518. this._vaoRecordInProgress = true;
  13519. this._gl.bindVertexArray(vao);
  13520. this._mustWipeVertexAttributes = true;
  13521. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13522. this.bindIndexBuffer(indexBuffer);
  13523. this._vaoRecordInProgress = false;
  13524. this._gl.bindVertexArray(null);
  13525. return vao;
  13526. };
  13527. /**
  13528. * Bind a specific vertex array object
  13529. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13530. * @param vertexArrayObject defines the vertex array object to bind
  13531. * @param indexBuffer defines the index buffer to bind
  13532. */
  13533. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13534. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13535. this._cachedVertexArrayObject = vertexArrayObject;
  13536. this._gl.bindVertexArray(vertexArrayObject);
  13537. this._cachedVertexBuffers = null;
  13538. this._cachedIndexBuffer = null;
  13539. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13540. this._mustWipeVertexAttributes = true;
  13541. }
  13542. };
  13543. /**
  13544. * Bind webGl buffers directly to the webGL context
  13545. * @param vertexBuffer defines the vertex buffer to bind
  13546. * @param indexBuffer defines the index buffer to bind
  13547. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13548. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13549. * @param effect defines the effect associated with the vertex buffer
  13550. */
  13551. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13552. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13553. this._cachedVertexBuffers = vertexBuffer;
  13554. this._cachedEffectForVertexBuffers = effect;
  13555. var attributesCount = effect.getAttributesCount();
  13556. this._unbindVertexArrayObject();
  13557. this.unbindAllAttributes();
  13558. var offset = 0;
  13559. for (var index = 0; index < attributesCount; index++) {
  13560. if (index < vertexDeclaration.length) {
  13561. var order = effect.getAttributeLocation(index);
  13562. if (order >= 0) {
  13563. this._gl.enableVertexAttribArray(order);
  13564. this._vertexAttribArraysEnabled[order] = true;
  13565. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13566. }
  13567. offset += vertexDeclaration[index] * 4;
  13568. }
  13569. }
  13570. }
  13571. this._bindIndexBufferWithCache(indexBuffer);
  13572. };
  13573. Engine.prototype._unbindVertexArrayObject = function () {
  13574. if (!this._cachedVertexArrayObject) {
  13575. return;
  13576. }
  13577. this._cachedVertexArrayObject = null;
  13578. this._gl.bindVertexArray(null);
  13579. };
  13580. /**
  13581. * Bind a list of vertex buffers to the webGL context
  13582. * @param vertexBuffers defines the list of vertex buffers to bind
  13583. * @param indexBuffer defines the index buffer to bind
  13584. * @param effect defines the effect associated with the vertex buffers
  13585. */
  13586. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13587. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13588. this._cachedVertexBuffers = vertexBuffers;
  13589. this._cachedEffectForVertexBuffers = effect;
  13590. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13591. }
  13592. this._bindIndexBufferWithCache(indexBuffer);
  13593. };
  13594. /**
  13595. * Unbind all instance attributes
  13596. */
  13597. Engine.prototype.unbindInstanceAttributes = function () {
  13598. var boundBuffer;
  13599. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13600. var instancesBuffer = this._currentInstanceBuffers[i];
  13601. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13602. boundBuffer = instancesBuffer;
  13603. this.bindArrayBuffer(instancesBuffer);
  13604. }
  13605. var offsetLocation = this._currentInstanceLocations[i];
  13606. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13607. }
  13608. this._currentInstanceBuffers.length = 0;
  13609. this._currentInstanceLocations.length = 0;
  13610. };
  13611. /**
  13612. * Release and free the memory of a vertex array object
  13613. * @param vao defines the vertex array object to delete
  13614. */
  13615. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13616. this._gl.deleteVertexArray(vao);
  13617. };
  13618. /** @hidden */
  13619. Engine.prototype._releaseBuffer = function (buffer) {
  13620. buffer.references--;
  13621. if (buffer.references === 0) {
  13622. this._gl.deleteBuffer(buffer);
  13623. return true;
  13624. }
  13625. return false;
  13626. };
  13627. /**
  13628. * Creates a webGL buffer to use with instanciation
  13629. * @param capacity defines the size of the buffer
  13630. * @returns the webGL buffer
  13631. */
  13632. Engine.prototype.createInstancesBuffer = function (capacity) {
  13633. var buffer = this._gl.createBuffer();
  13634. if (!buffer) {
  13635. throw new Error("Unable to create instance buffer");
  13636. }
  13637. buffer.capacity = capacity;
  13638. this.bindArrayBuffer(buffer);
  13639. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13640. return buffer;
  13641. };
  13642. /**
  13643. * Delete a webGL buffer used with instanciation
  13644. * @param buffer defines the webGL buffer to delete
  13645. */
  13646. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13647. this._gl.deleteBuffer(buffer);
  13648. };
  13649. /**
  13650. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13651. * @param instancesBuffer defines the webGL buffer to update and bind
  13652. * @param data defines the data to store in the buffer
  13653. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13654. */
  13655. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13656. this.bindArrayBuffer(instancesBuffer);
  13657. if (data) {
  13658. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13659. }
  13660. if (offsetLocations[0].index !== undefined) {
  13661. var stride = 0;
  13662. for (var i = 0; i < offsetLocations.length; i++) {
  13663. var ai = offsetLocations[i];
  13664. stride += ai.attributeSize * 4;
  13665. }
  13666. for (var i = 0; i < offsetLocations.length; i++) {
  13667. var ai = offsetLocations[i];
  13668. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13669. this._gl.enableVertexAttribArray(ai.index);
  13670. this._vertexAttribArraysEnabled[ai.index] = true;
  13671. }
  13672. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13673. this._gl.vertexAttribDivisor(ai.index, 1);
  13674. this._currentInstanceLocations.push(ai.index);
  13675. this._currentInstanceBuffers.push(instancesBuffer);
  13676. }
  13677. }
  13678. else {
  13679. for (var index = 0; index < 4; index++) {
  13680. var offsetLocation = offsetLocations[index];
  13681. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13682. this._gl.enableVertexAttribArray(offsetLocation);
  13683. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13684. }
  13685. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13686. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13687. this._currentInstanceLocations.push(offsetLocation);
  13688. this._currentInstanceBuffers.push(instancesBuffer);
  13689. }
  13690. }
  13691. };
  13692. /**
  13693. * Apply all cached states (depth, culling, stencil and alpha)
  13694. */
  13695. Engine.prototype.applyStates = function () {
  13696. this._depthCullingState.apply(this._gl);
  13697. this._stencilState.apply(this._gl);
  13698. this._alphaState.apply(this._gl);
  13699. };
  13700. /**
  13701. * Send a draw order
  13702. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13703. * @param indexStart defines the starting index
  13704. * @param indexCount defines the number of index to draw
  13705. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13706. */
  13707. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13708. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13709. };
  13710. /**
  13711. * Draw a list of points
  13712. * @param verticesStart defines the index of first vertex to draw
  13713. * @param verticesCount defines the count of vertices to draw
  13714. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13715. */
  13716. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13717. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13718. };
  13719. /**
  13720. * Draw a list of unindexed primitives
  13721. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13722. * @param verticesStart defines the index of first vertex to draw
  13723. * @param verticesCount defines the count of vertices to draw
  13724. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13725. */
  13726. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13727. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13728. };
  13729. /**
  13730. * Draw a list of indexed primitives
  13731. * @param fillMode defines the primitive to use
  13732. * @param indexStart defines the starting index
  13733. * @param indexCount defines the number of index to draw
  13734. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13735. */
  13736. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13737. // Apply states
  13738. this.applyStates();
  13739. this._drawCalls.addCount(1, false);
  13740. // Render
  13741. var drawMode = this._drawMode(fillMode);
  13742. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13743. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13744. if (instancesCount) {
  13745. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13746. }
  13747. else {
  13748. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13749. }
  13750. };
  13751. /**
  13752. * Draw a list of unindexed primitives
  13753. * @param fillMode defines the primitive to use
  13754. * @param verticesStart defines the index of first vertex to draw
  13755. * @param verticesCount defines the count of vertices to draw
  13756. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13757. */
  13758. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13759. // Apply states
  13760. this.applyStates();
  13761. this._drawCalls.addCount(1, false);
  13762. var drawMode = this._drawMode(fillMode);
  13763. if (instancesCount) {
  13764. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13765. }
  13766. else {
  13767. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13768. }
  13769. };
  13770. Engine.prototype._drawMode = function (fillMode) {
  13771. switch (fillMode) {
  13772. // Triangle views
  13773. case BABYLON.Material.TriangleFillMode:
  13774. return this._gl.TRIANGLES;
  13775. case BABYLON.Material.PointFillMode:
  13776. return this._gl.POINTS;
  13777. case BABYLON.Material.WireFrameFillMode:
  13778. return this._gl.LINES;
  13779. // Draw modes
  13780. case BABYLON.Material.PointListDrawMode:
  13781. return this._gl.POINTS;
  13782. case BABYLON.Material.LineListDrawMode:
  13783. return this._gl.LINES;
  13784. case BABYLON.Material.LineLoopDrawMode:
  13785. return this._gl.LINE_LOOP;
  13786. case BABYLON.Material.LineStripDrawMode:
  13787. return this._gl.LINE_STRIP;
  13788. case BABYLON.Material.TriangleStripDrawMode:
  13789. return this._gl.TRIANGLE_STRIP;
  13790. case BABYLON.Material.TriangleFanDrawMode:
  13791. return this._gl.TRIANGLE_FAN;
  13792. default:
  13793. return this._gl.TRIANGLES;
  13794. }
  13795. };
  13796. // Shaders
  13797. /** @hidden */
  13798. Engine.prototype._releaseEffect = function (effect) {
  13799. if (this._compiledEffects[effect._key]) {
  13800. delete this._compiledEffects[effect._key];
  13801. this._deleteProgram(effect.getProgram());
  13802. }
  13803. };
  13804. /** @hidden */
  13805. Engine.prototype._deleteProgram = function (program) {
  13806. if (program) {
  13807. program.__SPECTOR_rebuildProgram = null;
  13808. if (program.transformFeedback) {
  13809. this.deleteTransformFeedback(program.transformFeedback);
  13810. program.transformFeedback = null;
  13811. }
  13812. this._gl.deleteProgram(program);
  13813. }
  13814. };
  13815. /**
  13816. * Create a new effect (used to store vertex/fragment shaders)
  13817. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13818. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13819. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13820. * @param samplers defines an array of string used to represent textures
  13821. * @param defines defines the string containing the defines to use to compile the shaders
  13822. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13823. * @param onCompiled defines a function to call when the effect creation is successful
  13824. * @param onError defines a function to call when the effect creation has failed
  13825. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13826. * @returns the new Effect
  13827. */
  13828. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13829. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13830. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13831. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13832. if (this._compiledEffects[name]) {
  13833. var compiledEffect = this._compiledEffects[name];
  13834. if (onCompiled && compiledEffect.isReady()) {
  13835. onCompiled(compiledEffect);
  13836. }
  13837. return compiledEffect;
  13838. }
  13839. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13840. effect._key = name;
  13841. this._compiledEffects[name] = effect;
  13842. return effect;
  13843. };
  13844. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13845. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13846. };
  13847. ;
  13848. Engine.prototype._compileRawShader = function (source, type) {
  13849. var gl = this._gl;
  13850. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13851. gl.shaderSource(shader, source);
  13852. gl.compileShader(shader);
  13853. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13854. var log = gl.getShaderInfoLog(shader);
  13855. if (log) {
  13856. throw new Error(log);
  13857. }
  13858. }
  13859. if (!shader) {
  13860. throw new Error("Something went wrong while compile the shader.");
  13861. }
  13862. return shader;
  13863. };
  13864. ;
  13865. /**
  13866. * Directly creates a webGL program
  13867. * @param vertexCode defines the vertex shader code to use
  13868. * @param fragmentCode defines the fragment shader code to use
  13869. * @param context defines the webGL context to use (if not set, the current one will be used)
  13870. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13871. * @returns the new webGL program
  13872. */
  13873. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13874. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13875. context = context || this._gl;
  13876. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13877. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13878. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13879. };
  13880. /**
  13881. * Creates a webGL program
  13882. * @param vertexCode defines the vertex shader code to use
  13883. * @param fragmentCode defines the fragment shader code to use
  13884. * @param defines defines the string containing the defines to use to compile the shaders
  13885. * @param context defines the webGL context to use (if not set, the current one will be used)
  13886. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13887. * @returns the new webGL program
  13888. */
  13889. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13890. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13891. context = context || this._gl;
  13892. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13893. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13894. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13895. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13896. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13897. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13898. return program;
  13899. };
  13900. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13901. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13902. var shaderProgram = context.createProgram();
  13903. if (!shaderProgram) {
  13904. throw new Error("Unable to create program");
  13905. }
  13906. context.attachShader(shaderProgram, vertexShader);
  13907. context.attachShader(shaderProgram, fragmentShader);
  13908. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13909. var transformFeedback = this.createTransformFeedback();
  13910. this.bindTransformFeedback(transformFeedback);
  13911. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13912. shaderProgram.transformFeedback = transformFeedback;
  13913. }
  13914. context.linkProgram(shaderProgram);
  13915. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13916. this.bindTransformFeedback(null);
  13917. }
  13918. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13919. if (!linked) {
  13920. var error = context.getProgramInfoLog(shaderProgram);
  13921. if (error) {
  13922. throw new Error(error);
  13923. }
  13924. }
  13925. if (this.validateShaderPrograms) {
  13926. context.validateProgram(shaderProgram);
  13927. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13928. if (!validated) {
  13929. var error = context.getProgramInfoLog(shaderProgram);
  13930. if (error) {
  13931. throw new Error(error);
  13932. }
  13933. }
  13934. }
  13935. context.deleteShader(vertexShader);
  13936. context.deleteShader(fragmentShader);
  13937. return shaderProgram;
  13938. };
  13939. /**
  13940. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13941. * @param shaderProgram defines the webGL program to use
  13942. * @param uniformsNames defines the list of uniform names
  13943. * @returns an array of webGL uniform locations
  13944. */
  13945. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13946. var results = new Array();
  13947. for (var index = 0; index < uniformsNames.length; index++) {
  13948. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13949. }
  13950. return results;
  13951. };
  13952. /**
  13953. * Gets the lsit of active attributes for a given webGL program
  13954. * @param shaderProgram defines the webGL program to use
  13955. * @param attributesNames defines the list of attribute names to get
  13956. * @returns an array of indices indicating the offset of each attribute
  13957. */
  13958. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13959. var results = [];
  13960. for (var index = 0; index < attributesNames.length; index++) {
  13961. try {
  13962. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13963. }
  13964. catch (e) {
  13965. results.push(-1);
  13966. }
  13967. }
  13968. return results;
  13969. };
  13970. /**
  13971. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13972. * @param effect defines the effect to activate
  13973. */
  13974. Engine.prototype.enableEffect = function (effect) {
  13975. if (!effect || effect === this._currentEffect) {
  13976. return;
  13977. }
  13978. // Use program
  13979. this.bindSamplers(effect);
  13980. this._currentEffect = effect;
  13981. if (effect.onBind) {
  13982. effect.onBind(effect);
  13983. }
  13984. if (effect._onBindObservable) {
  13985. effect._onBindObservable.notifyObservers(effect);
  13986. }
  13987. };
  13988. /**
  13989. * Set the value of an uniform to an array of int32
  13990. * @param uniform defines the webGL uniform location where to store the value
  13991. * @param array defines the array of int32 to store
  13992. */
  13993. Engine.prototype.setIntArray = function (uniform, array) {
  13994. if (!uniform)
  13995. return;
  13996. this._gl.uniform1iv(uniform, array);
  13997. };
  13998. /**
  13999. * Set the value of an uniform to an array of int32 (stored as vec2)
  14000. * @param uniform defines the webGL uniform location where to store the value
  14001. * @param array defines the array of int32 to store
  14002. */
  14003. Engine.prototype.setIntArray2 = function (uniform, array) {
  14004. if (!uniform || array.length % 2 !== 0)
  14005. return;
  14006. this._gl.uniform2iv(uniform, array);
  14007. };
  14008. /**
  14009. * Set the value of an uniform to an array of int32 (stored as vec3)
  14010. * @param uniform defines the webGL uniform location where to store the value
  14011. * @param array defines the array of int32 to store
  14012. */
  14013. Engine.prototype.setIntArray3 = function (uniform, array) {
  14014. if (!uniform || array.length % 3 !== 0)
  14015. return;
  14016. this._gl.uniform3iv(uniform, array);
  14017. };
  14018. /**
  14019. * Set the value of an uniform to an array of int32 (stored as vec4)
  14020. * @param uniform defines the webGL uniform location where to store the value
  14021. * @param array defines the array of int32 to store
  14022. */
  14023. Engine.prototype.setIntArray4 = function (uniform, array) {
  14024. if (!uniform || array.length % 4 !== 0)
  14025. return;
  14026. this._gl.uniform4iv(uniform, array);
  14027. };
  14028. /**
  14029. * Set the value of an uniform to an array of float32
  14030. * @param uniform defines the webGL uniform location where to store the value
  14031. * @param array defines the array of float32 to store
  14032. */
  14033. Engine.prototype.setFloatArray = function (uniform, array) {
  14034. if (!uniform)
  14035. return;
  14036. this._gl.uniform1fv(uniform, array);
  14037. };
  14038. /**
  14039. * Set the value of an uniform to an array of float32 (stored as vec2)
  14040. * @param uniform defines the webGL uniform location where to store the value
  14041. * @param array defines the array of float32 to store
  14042. */
  14043. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14044. if (!uniform || array.length % 2 !== 0)
  14045. return;
  14046. this._gl.uniform2fv(uniform, array);
  14047. };
  14048. /**
  14049. * Set the value of an uniform to an array of float32 (stored as vec3)
  14050. * @param uniform defines the webGL uniform location where to store the value
  14051. * @param array defines the array of float32 to store
  14052. */
  14053. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14054. if (!uniform || array.length % 3 !== 0)
  14055. return;
  14056. this._gl.uniform3fv(uniform, array);
  14057. };
  14058. /**
  14059. * Set the value of an uniform to an array of float32 (stored as vec4)
  14060. * @param uniform defines the webGL uniform location where to store the value
  14061. * @param array defines the array of float32 to store
  14062. */
  14063. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14064. if (!uniform || array.length % 4 !== 0)
  14065. return;
  14066. this._gl.uniform4fv(uniform, array);
  14067. };
  14068. /**
  14069. * Set the value of an uniform to an array of number
  14070. * @param uniform defines the webGL uniform location where to store the value
  14071. * @param array defines the array of number to store
  14072. */
  14073. Engine.prototype.setArray = function (uniform, array) {
  14074. if (!uniform)
  14075. return;
  14076. this._gl.uniform1fv(uniform, array);
  14077. };
  14078. /**
  14079. * Set the value of an uniform to an array of number (stored as vec2)
  14080. * @param uniform defines the webGL uniform location where to store the value
  14081. * @param array defines the array of number to store
  14082. */
  14083. Engine.prototype.setArray2 = function (uniform, array) {
  14084. if (!uniform || array.length % 2 !== 0)
  14085. return;
  14086. this._gl.uniform2fv(uniform, array);
  14087. };
  14088. /**
  14089. * Set the value of an uniform to an array of number (stored as vec3)
  14090. * @param uniform defines the webGL uniform location where to store the value
  14091. * @param array defines the array of number to store
  14092. */
  14093. Engine.prototype.setArray3 = function (uniform, array) {
  14094. if (!uniform || array.length % 3 !== 0)
  14095. return;
  14096. this._gl.uniform3fv(uniform, array);
  14097. };
  14098. /**
  14099. * Set the value of an uniform to an array of number (stored as vec4)
  14100. * @param uniform defines the webGL uniform location where to store the value
  14101. * @param array defines the array of number to store
  14102. */
  14103. Engine.prototype.setArray4 = function (uniform, array) {
  14104. if (!uniform || array.length % 4 !== 0)
  14105. return;
  14106. this._gl.uniform4fv(uniform, array);
  14107. };
  14108. /**
  14109. * Set the value of an uniform to an array of float32 (stored as matrices)
  14110. * @param uniform defines the webGL uniform location where to store the value
  14111. * @param matrices defines the array of float32 to store
  14112. */
  14113. Engine.prototype.setMatrices = function (uniform, matrices) {
  14114. if (!uniform)
  14115. return;
  14116. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14117. };
  14118. /**
  14119. * Set the value of an uniform to a matrix
  14120. * @param uniform defines the webGL uniform location where to store the value
  14121. * @param matrix defines the matrix to store
  14122. */
  14123. Engine.prototype.setMatrix = function (uniform, matrix) {
  14124. if (!uniform)
  14125. return;
  14126. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14127. };
  14128. /**
  14129. * Set the value of an uniform to a matrix (3x3)
  14130. * @param uniform defines the webGL uniform location where to store the value
  14131. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14132. */
  14133. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14134. if (!uniform)
  14135. return;
  14136. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14137. };
  14138. /**
  14139. * Set the value of an uniform to a matrix (2x2)
  14140. * @param uniform defines the webGL uniform location where to store the value
  14141. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14142. */
  14143. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14144. if (!uniform)
  14145. return;
  14146. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14147. };
  14148. /**
  14149. * Set the value of an uniform to a number (int)
  14150. * @param uniform defines the webGL uniform location where to store the value
  14151. * @param value defines the int number to store
  14152. */
  14153. Engine.prototype.setInt = function (uniform, value) {
  14154. if (!uniform)
  14155. return;
  14156. this._gl.uniform1i(uniform, value);
  14157. };
  14158. /**
  14159. * Set the value of an uniform to a number (float)
  14160. * @param uniform defines the webGL uniform location where to store the value
  14161. * @param value defines the float number to store
  14162. */
  14163. Engine.prototype.setFloat = function (uniform, value) {
  14164. if (!uniform)
  14165. return;
  14166. this._gl.uniform1f(uniform, value);
  14167. };
  14168. /**
  14169. * Set the value of an uniform to a vec2
  14170. * @param uniform defines the webGL uniform location where to store the value
  14171. * @param x defines the 1st component of the value
  14172. * @param y defines the 2nd component of the value
  14173. */
  14174. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14175. if (!uniform)
  14176. return;
  14177. this._gl.uniform2f(uniform, x, y);
  14178. };
  14179. /**
  14180. * Set the value of an uniform to a vec3
  14181. * @param uniform defines the webGL uniform location where to store the value
  14182. * @param x defines the 1st component of the value
  14183. * @param y defines the 2nd component of the value
  14184. * @param z defines the 3rd component of the value
  14185. */
  14186. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14187. if (!uniform)
  14188. return;
  14189. this._gl.uniform3f(uniform, x, y, z);
  14190. };
  14191. /**
  14192. * Set the value of an uniform to a boolean
  14193. * @param uniform defines the webGL uniform location where to store the value
  14194. * @param bool defines the boolean to store
  14195. */
  14196. Engine.prototype.setBool = function (uniform, bool) {
  14197. if (!uniform)
  14198. return;
  14199. this._gl.uniform1i(uniform, bool);
  14200. };
  14201. /**
  14202. * Set the value of an uniform to a vec4
  14203. * @param uniform defines the webGL uniform location where to store the value
  14204. * @param x defines the 1st component of the value
  14205. * @param y defines the 2nd component of the value
  14206. * @param z defines the 3rd component of the value
  14207. * @param w defines the 4th component of the value
  14208. */
  14209. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14210. if (!uniform)
  14211. return;
  14212. this._gl.uniform4f(uniform, x, y, z, w);
  14213. };
  14214. /**
  14215. * Set the value of an uniform to a Color3
  14216. * @param uniform defines the webGL uniform location where to store the value
  14217. * @param color3 defines the color to store
  14218. */
  14219. Engine.prototype.setColor3 = function (uniform, color3) {
  14220. if (!uniform)
  14221. return;
  14222. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14223. };
  14224. /**
  14225. * Set the value of an uniform to a Color3 and an alpha value
  14226. * @param uniform defines the webGL uniform location where to store the value
  14227. * @param color3 defines the color to store
  14228. * @param alpha defines the alpha component to store
  14229. */
  14230. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14231. if (!uniform)
  14232. return;
  14233. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14234. };
  14235. /**
  14236. * Sets a Color4 on a uniform variable
  14237. * @param uniform defines the uniform location
  14238. * @param color4 defines the value to be set
  14239. */
  14240. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14241. if (!uniform)
  14242. return;
  14243. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14244. };
  14245. // States
  14246. /**
  14247. * Set various states to the webGL context
  14248. * @param culling defines backface culling state
  14249. * @param zOffset defines the value to apply to zOffset (0 by default)
  14250. * @param force defines if states must be applied even if cache is up to date
  14251. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14252. */
  14253. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14254. if (zOffset === void 0) { zOffset = 0; }
  14255. if (reverseSide === void 0) { reverseSide = false; }
  14256. // Culling
  14257. if (this._depthCullingState.cull !== culling || force) {
  14258. this._depthCullingState.cull = culling;
  14259. }
  14260. // Cull face
  14261. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14262. if (this._depthCullingState.cullFace !== cullFace || force) {
  14263. this._depthCullingState.cullFace = cullFace;
  14264. }
  14265. // Z offset
  14266. this.setZOffset(zOffset);
  14267. // Front face
  14268. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14269. if (this._depthCullingState.frontFace !== frontFace || force) {
  14270. this._depthCullingState.frontFace = frontFace;
  14271. }
  14272. };
  14273. /**
  14274. * Set the z offset to apply to current rendering
  14275. * @param value defines the offset to apply
  14276. */
  14277. Engine.prototype.setZOffset = function (value) {
  14278. this._depthCullingState.zOffset = value;
  14279. };
  14280. /**
  14281. * Gets the current value of the zOffset
  14282. * @returns the current zOffset state
  14283. */
  14284. Engine.prototype.getZOffset = function () {
  14285. return this._depthCullingState.zOffset;
  14286. };
  14287. /**
  14288. * Enable or disable depth buffering
  14289. * @param enable defines the state to set
  14290. */
  14291. Engine.prototype.setDepthBuffer = function (enable) {
  14292. this._depthCullingState.depthTest = enable;
  14293. };
  14294. /**
  14295. * Gets a boolean indicating if depth writing is enabled
  14296. * @returns the current depth writing state
  14297. */
  14298. Engine.prototype.getDepthWrite = function () {
  14299. return this._depthCullingState.depthMask;
  14300. };
  14301. /**
  14302. * Enable or disable depth writing
  14303. * @param enable defines the state to set
  14304. */
  14305. Engine.prototype.setDepthWrite = function (enable) {
  14306. this._depthCullingState.depthMask = enable;
  14307. };
  14308. /**
  14309. * Enable or disable color writing
  14310. * @param enable defines the state to set
  14311. */
  14312. Engine.prototype.setColorWrite = function (enable) {
  14313. this._gl.colorMask(enable, enable, enable, enable);
  14314. this._colorWrite = enable;
  14315. };
  14316. /**
  14317. * Gets a boolean indicating if color writing is enabled
  14318. * @returns the current color writing state
  14319. */
  14320. Engine.prototype.getColorWrite = function () {
  14321. return this._colorWrite;
  14322. };
  14323. /**
  14324. * Sets alpha constants used by some alpha blending modes
  14325. * @param r defines the red component
  14326. * @param g defines the green component
  14327. * @param b defines the blue component
  14328. * @param a defines the alpha component
  14329. */
  14330. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14331. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14332. };
  14333. /**
  14334. * Sets the current alpha mode
  14335. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14336. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14337. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14338. */
  14339. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14340. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14341. if (this._alphaMode === mode) {
  14342. return;
  14343. }
  14344. switch (mode) {
  14345. case Engine.ALPHA_DISABLE:
  14346. this._alphaState.alphaBlend = false;
  14347. break;
  14348. case Engine.ALPHA_PREMULTIPLIED:
  14349. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14350. this._alphaState.alphaBlend = true;
  14351. break;
  14352. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14353. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14354. this._alphaState.alphaBlend = true;
  14355. break;
  14356. case Engine.ALPHA_COMBINE:
  14357. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14358. this._alphaState.alphaBlend = true;
  14359. break;
  14360. case Engine.ALPHA_ONEONE:
  14361. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14362. this._alphaState.alphaBlend = true;
  14363. break;
  14364. case Engine.ALPHA_ADD:
  14365. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14366. this._alphaState.alphaBlend = true;
  14367. break;
  14368. case Engine.ALPHA_SUBTRACT:
  14369. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14370. this._alphaState.alphaBlend = true;
  14371. break;
  14372. case Engine.ALPHA_MULTIPLY:
  14373. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14374. this._alphaState.alphaBlend = true;
  14375. break;
  14376. case Engine.ALPHA_MAXIMIZED:
  14377. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14378. this._alphaState.alphaBlend = true;
  14379. break;
  14380. case Engine.ALPHA_INTERPOLATE:
  14381. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14382. this._alphaState.alphaBlend = true;
  14383. break;
  14384. case Engine.ALPHA_SCREENMODE:
  14385. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14386. this._alphaState.alphaBlend = true;
  14387. break;
  14388. }
  14389. if (!noDepthWriteChange) {
  14390. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14391. }
  14392. this._alphaMode = mode;
  14393. };
  14394. /**
  14395. * Gets the current alpha mode
  14396. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14397. * @returns the current alpha mode
  14398. */
  14399. Engine.prototype.getAlphaMode = function () {
  14400. return this._alphaMode;
  14401. };
  14402. // Textures
  14403. /**
  14404. * Clears the list of texture accessible through engine.
  14405. * This can help preventing texture load conflict due to name collision.
  14406. */
  14407. Engine.prototype.clearInternalTexturesCache = function () {
  14408. this._internalTexturesCache = [];
  14409. };
  14410. /**
  14411. * Force the entire cache to be cleared
  14412. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14413. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14414. */
  14415. Engine.prototype.wipeCaches = function (bruteForce) {
  14416. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14417. return;
  14418. }
  14419. this._currentEffect = null;
  14420. this._viewportCached.x = 0;
  14421. this._viewportCached.y = 0;
  14422. this._viewportCached.z = 0;
  14423. this._viewportCached.w = 0;
  14424. if (bruteForce) {
  14425. this.resetTextureCache();
  14426. this._currentProgram = null;
  14427. this._stencilState.reset();
  14428. this._depthCullingState.reset();
  14429. this.setDepthFunctionToLessOrEqual();
  14430. this._alphaState.reset();
  14431. this._unpackFlipYCached = null;
  14432. }
  14433. this._resetVertexBufferBinding();
  14434. this._cachedIndexBuffer = null;
  14435. this._cachedEffectForVertexBuffers = null;
  14436. this._unbindVertexArrayObject();
  14437. this.bindIndexBuffer(null);
  14438. };
  14439. /**
  14440. * Set the compressed texture format to use, based on the formats you have, and the formats
  14441. * supported by the hardware / browser.
  14442. *
  14443. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14444. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14445. * to API arguments needed to compressed textures. This puts the burden on the container
  14446. * generator to house the arcane code for determining these for current & future formats.
  14447. *
  14448. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14449. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14450. *
  14451. * Note: The result of this call is not taken into account when a texture is base64.
  14452. *
  14453. * @param formatsAvailable defines the list of those format families you have created
  14454. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14455. *
  14456. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14457. * @returns The extension selected.
  14458. */
  14459. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14460. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14461. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14462. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14463. return this._textureFormatInUse = this._texturesSupported[i];
  14464. }
  14465. }
  14466. }
  14467. // actively set format to nothing, to allow this to be called more than once
  14468. // and possibly fail the 2nd time
  14469. this._textureFormatInUse = null;
  14470. return null;
  14471. };
  14472. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14473. var gl = this._gl;
  14474. var magFilter = gl.NEAREST;
  14475. var minFilter = gl.NEAREST;
  14476. switch (samplingMode) {
  14477. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14478. magFilter = gl.LINEAR;
  14479. if (generateMipMaps) {
  14480. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14481. }
  14482. else {
  14483. minFilter = gl.LINEAR;
  14484. }
  14485. break;
  14486. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14487. magFilter = gl.LINEAR;
  14488. if (generateMipMaps) {
  14489. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14490. }
  14491. else {
  14492. minFilter = gl.LINEAR;
  14493. }
  14494. break;
  14495. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14496. magFilter = gl.NEAREST;
  14497. if (generateMipMaps) {
  14498. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14499. }
  14500. else {
  14501. minFilter = gl.NEAREST;
  14502. }
  14503. break;
  14504. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14505. magFilter = gl.NEAREST;
  14506. if (generateMipMaps) {
  14507. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14508. }
  14509. else {
  14510. minFilter = gl.NEAREST;
  14511. }
  14512. break;
  14513. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14514. magFilter = gl.NEAREST;
  14515. if (generateMipMaps) {
  14516. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14517. }
  14518. else {
  14519. minFilter = gl.LINEAR;
  14520. }
  14521. break;
  14522. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14523. magFilter = gl.NEAREST;
  14524. if (generateMipMaps) {
  14525. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14526. }
  14527. else {
  14528. minFilter = gl.LINEAR;
  14529. }
  14530. break;
  14531. case Engine.TEXTURE_NEAREST_LINEAR:
  14532. magFilter = gl.NEAREST;
  14533. minFilter = gl.LINEAR;
  14534. break;
  14535. case Engine.TEXTURE_NEAREST_NEAREST:
  14536. magFilter = gl.NEAREST;
  14537. minFilter = gl.NEAREST;
  14538. break;
  14539. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14540. magFilter = gl.LINEAR;
  14541. if (generateMipMaps) {
  14542. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14543. }
  14544. else {
  14545. minFilter = gl.NEAREST;
  14546. }
  14547. break;
  14548. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14549. magFilter = gl.LINEAR;
  14550. if (generateMipMaps) {
  14551. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14552. }
  14553. else {
  14554. minFilter = gl.NEAREST;
  14555. }
  14556. break;
  14557. case Engine.TEXTURE_LINEAR_LINEAR:
  14558. magFilter = gl.LINEAR;
  14559. minFilter = gl.LINEAR;
  14560. break;
  14561. case Engine.TEXTURE_LINEAR_NEAREST:
  14562. magFilter = gl.LINEAR;
  14563. minFilter = gl.NEAREST;
  14564. break;
  14565. }
  14566. return {
  14567. min: minFilter,
  14568. mag: magFilter
  14569. };
  14570. };
  14571. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14572. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14573. var img;
  14574. var onload = function () {
  14575. loadedImages[index] = img;
  14576. loadedImages._internalCount++;
  14577. if (scene) {
  14578. scene._removePendingData(img);
  14579. }
  14580. if (loadedImages._internalCount === 6) {
  14581. onfinish(loadedImages);
  14582. }
  14583. };
  14584. var onerror = function (message, exception) {
  14585. if (scene) {
  14586. scene._removePendingData(img);
  14587. }
  14588. if (onErrorCallBack) {
  14589. onErrorCallBack(message, exception);
  14590. }
  14591. };
  14592. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14593. if (scene) {
  14594. scene._addPendingData(img);
  14595. }
  14596. };
  14597. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14598. if (onError === void 0) { onError = null; }
  14599. var loadedImages = [];
  14600. loadedImages._internalCount = 0;
  14601. for (var index = 0; index < 6; index++) {
  14602. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14603. }
  14604. };
  14605. ;
  14606. /** @hidden */
  14607. Engine.prototype._createTexture = function () {
  14608. var texture = this._gl.createTexture();
  14609. if (!texture) {
  14610. throw new Error("Unable to create texture");
  14611. }
  14612. return texture;
  14613. };
  14614. /**
  14615. * Usually called from BABYLON.Texture.ts.
  14616. * Passed information to create a WebGLTexture
  14617. * @param urlArg defines a value which contains one of the following:
  14618. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14619. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14620. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14621. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14622. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14623. * @param scene needed for loading to the correct scene
  14624. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14625. * @param onLoad optional callback to be called upon successful completion
  14626. * @param onError optional callback to be called upon failure
  14627. * @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
  14628. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14629. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14630. * @param forcedExtension defines the extension to use to pick the right loader
  14631. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14632. */
  14633. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14634. var _this = this;
  14635. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14636. if (onLoad === void 0) { onLoad = null; }
  14637. if (onError === void 0) { onError = null; }
  14638. if (buffer === void 0) { buffer = null; }
  14639. if (fallback === void 0) { fallback = null; }
  14640. if (format === void 0) { format = null; }
  14641. if (forcedExtension === void 0) { forcedExtension = null; }
  14642. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14643. var fromData = url.substr(0, 5) === "data:";
  14644. var fromBlob = url.substr(0, 5) === "blob:";
  14645. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  14646. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14647. // establish the file extension, if possible
  14648. var lastDot = url.lastIndexOf('.');
  14649. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14650. var loader = null;
  14651. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14652. var availableLoader = _a[_i];
  14653. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14654. loader = availableLoader;
  14655. break;
  14656. }
  14657. }
  14658. if (loader) {
  14659. url = loader.transformUrl(url, this._textureFormatInUse);
  14660. }
  14661. if (scene) {
  14662. scene._addPendingData(texture);
  14663. }
  14664. texture.url = url;
  14665. texture.generateMipMaps = !noMipmap;
  14666. texture.samplingMode = samplingMode;
  14667. texture.invertY = invertY;
  14668. if (!this._doNotHandleContextLost) {
  14669. // Keep a link to the buffer only if we plan to handle context lost
  14670. texture._buffer = buffer;
  14671. }
  14672. var onLoadObserver = null;
  14673. if (onLoad && !fallback) {
  14674. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14675. }
  14676. if (!fallback)
  14677. this._internalTexturesCache.push(texture);
  14678. var onInternalError = function (message, exception) {
  14679. if (scene) {
  14680. scene._removePendingData(texture);
  14681. }
  14682. var customFallback = false;
  14683. if (loader) {
  14684. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14685. if (fallbackUrl) {
  14686. // Add Back
  14687. customFallback = true;
  14688. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14689. }
  14690. }
  14691. if (!customFallback) {
  14692. if (onLoadObserver) {
  14693. texture.onLoadedObservable.remove(onLoadObserver);
  14694. }
  14695. if (BABYLON.Tools.UseFallbackTexture) {
  14696. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14697. }
  14698. }
  14699. if (onError) {
  14700. onError(message || "Unknown error", exception);
  14701. }
  14702. };
  14703. // processing for non-image formats
  14704. if (loader) {
  14705. var callback = function (data) {
  14706. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14707. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14708. done();
  14709. return false;
  14710. }, samplingMode);
  14711. });
  14712. };
  14713. if (!buffer) {
  14714. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14715. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14716. });
  14717. }
  14718. else {
  14719. callback(buffer);
  14720. }
  14721. }
  14722. else {
  14723. var onload = function (img) {
  14724. if (fromBlob && !_this._doNotHandleContextLost) {
  14725. // We need to store the image if we need to rebuild the texture
  14726. // in case of a webgl context lost
  14727. texture._buffer = img;
  14728. }
  14729. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14730. var gl = _this._gl;
  14731. var isPot = (img.width === potWidth && img.height === potHeight);
  14732. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14733. if (isPot) {
  14734. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14735. return false;
  14736. }
  14737. var maxTextureSize = _this._caps.maxTextureSize;
  14738. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14739. _this._prepareWorkingCanvas();
  14740. if (!_this._workingCanvas || !_this._workingContext) {
  14741. return false;
  14742. }
  14743. _this._workingCanvas.width = potWidth;
  14744. _this._workingCanvas.height = potHeight;
  14745. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14746. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14747. texture.width = potWidth;
  14748. texture.height = potHeight;
  14749. return false;
  14750. }
  14751. else {
  14752. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14753. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14754. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14755. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14756. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14757. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14758. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14759. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14760. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14761. _this._releaseTexture(source_1);
  14762. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14763. continuationCallback();
  14764. });
  14765. }
  14766. return true;
  14767. }, samplingMode);
  14768. };
  14769. if (!fromData || isBase64) {
  14770. if (buffer instanceof HTMLImageElement) {
  14771. onload(buffer);
  14772. }
  14773. else {
  14774. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14775. }
  14776. }
  14777. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14778. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14779. }
  14780. else {
  14781. onload(buffer);
  14782. }
  14783. }
  14784. return texture;
  14785. };
  14786. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14787. var _this = this;
  14788. var rtt = this.createRenderTargetTexture({
  14789. width: destination.width,
  14790. height: destination.height,
  14791. }, {
  14792. generateMipMaps: false,
  14793. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14794. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14795. generateDepthBuffer: false,
  14796. generateStencilBuffer: false
  14797. });
  14798. if (!this._rescalePostProcess) {
  14799. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14800. }
  14801. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14802. _this._rescalePostProcess.onApply = function (effect) {
  14803. effect._bindTexture("textureSampler", source);
  14804. };
  14805. var hostingScene = scene;
  14806. if (!hostingScene) {
  14807. hostingScene = _this.scenes[_this.scenes.length - 1];
  14808. }
  14809. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14810. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14811. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14812. _this.unBindFramebuffer(rtt);
  14813. _this._releaseTexture(rtt);
  14814. if (onComplete) {
  14815. onComplete();
  14816. }
  14817. });
  14818. };
  14819. /**
  14820. * Update a raw texture
  14821. * @param texture defines the texture to update
  14822. * @param data defines the data to store in the texture
  14823. * @param format defines the format of the data
  14824. * @param invertY defines if data must be stored with Y axis inverted
  14825. * @param compression defines the compression used (null by default)
  14826. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14827. */
  14828. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14829. if (compression === void 0) { compression = null; }
  14830. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14831. if (!texture) {
  14832. return;
  14833. }
  14834. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14835. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14836. // babylon's internalFormat but gl's texImage2D format
  14837. var internalFormat = this._getInternalFormat(format);
  14838. var textureType = this._getWebGLTextureType(type);
  14839. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14840. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14841. if (!this._doNotHandleContextLost) {
  14842. texture._bufferView = data;
  14843. texture.format = format;
  14844. texture.type = type;
  14845. texture.invertY = invertY;
  14846. texture._compression = compression;
  14847. }
  14848. if (texture.width % 4 !== 0) {
  14849. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14850. }
  14851. if (compression && data) {
  14852. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14853. }
  14854. else {
  14855. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14856. }
  14857. if (texture.generateMipMaps) {
  14858. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14859. }
  14860. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14861. // this.resetTextureCache();
  14862. texture.isReady = true;
  14863. };
  14864. /**
  14865. * Creates a raw texture
  14866. * @param data defines the data to store in the texture
  14867. * @param width defines the width of the texture
  14868. * @param height defines the height of the texture
  14869. * @param format defines the format of the data
  14870. * @param generateMipMaps defines if the engine should generate the mip levels
  14871. * @param invertY defines if data must be stored with Y axis inverted
  14872. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14873. * @param compression defines the compression used (null by default)
  14874. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14875. * @returns the raw texture inside an InternalTexture
  14876. */
  14877. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14878. if (compression === void 0) { compression = null; }
  14879. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14880. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14881. texture.baseWidth = width;
  14882. texture.baseHeight = height;
  14883. texture.width = width;
  14884. texture.height = height;
  14885. texture.format = format;
  14886. texture.generateMipMaps = generateMipMaps;
  14887. texture.samplingMode = samplingMode;
  14888. texture.invertY = invertY;
  14889. texture._compression = compression;
  14890. texture.type = type;
  14891. if (!this._doNotHandleContextLost) {
  14892. texture._bufferView = data;
  14893. }
  14894. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14895. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14896. // Filters
  14897. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14898. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14899. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14900. if (generateMipMaps) {
  14901. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14902. }
  14903. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14904. this._internalTexturesCache.push(texture);
  14905. return texture;
  14906. };
  14907. /** @hidden */
  14908. Engine.prototype._unpackFlipY = function (value) {
  14909. if (this._unpackFlipYCached !== value) {
  14910. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14911. if (this.enableUnpackFlipYCached) {
  14912. this._unpackFlipYCached = value;
  14913. }
  14914. }
  14915. };
  14916. /** @hidden */
  14917. Engine.prototype._getUnpackAlignement = function () {
  14918. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14919. };
  14920. /**
  14921. * Creates a dynamic texture
  14922. * @param width defines the width of the texture
  14923. * @param height defines the height of the texture
  14924. * @param generateMipMaps defines if the engine should generate the mip levels
  14925. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14926. * @returns the dynamic texture inside an InternalTexture
  14927. */
  14928. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14929. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14930. texture.baseWidth = width;
  14931. texture.baseHeight = height;
  14932. if (generateMipMaps) {
  14933. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14934. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14935. }
  14936. // this.resetTextureCache();
  14937. texture.width = width;
  14938. texture.height = height;
  14939. texture.isReady = false;
  14940. texture.generateMipMaps = generateMipMaps;
  14941. texture.samplingMode = samplingMode;
  14942. this.updateTextureSamplingMode(samplingMode, texture);
  14943. this._internalTexturesCache.push(texture);
  14944. return texture;
  14945. };
  14946. /**
  14947. * Update the sampling mode of a given texture
  14948. * @param samplingMode defines the required sampling mode
  14949. * @param texture defines the texture to update
  14950. */
  14951. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14952. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14953. if (texture.isCube) {
  14954. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14955. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14956. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14957. }
  14958. else if (texture.is3D) {
  14959. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14960. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14961. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14962. }
  14963. else {
  14964. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14965. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14966. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14967. }
  14968. texture.samplingMode = samplingMode;
  14969. };
  14970. /**
  14971. * Update the content of a dynamic texture
  14972. * @param texture defines the texture to update
  14973. * @param canvas defines the canvas containing the source
  14974. * @param invertY defines if data must be stored with Y axis inverted
  14975. * @param premulAlpha defines if alpha is stored as premultiplied
  14976. * @param format defines the format of the data
  14977. */
  14978. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14979. if (premulAlpha === void 0) { premulAlpha = false; }
  14980. if (!texture) {
  14981. return;
  14982. }
  14983. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14984. this._unpackFlipY(invertY);
  14985. if (premulAlpha) {
  14986. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14987. }
  14988. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14989. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14990. if (texture.generateMipMaps) {
  14991. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14992. }
  14993. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14994. if (premulAlpha) {
  14995. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14996. }
  14997. texture.isReady = true;
  14998. };
  14999. /**
  15000. * Update a video texture
  15001. * @param texture defines the texture to update
  15002. * @param video defines the video element to use
  15003. * @param invertY defines if data must be stored with Y axis inverted
  15004. */
  15005. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15006. if (!texture || texture._isDisabled) {
  15007. return;
  15008. }
  15009. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15010. this._unpackFlipY(!invertY); // Video are upside down by default
  15011. try {
  15012. // Testing video texture support
  15013. if (this._videoTextureSupported === undefined) {
  15014. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15015. if (this._gl.getError() !== 0) {
  15016. this._videoTextureSupported = false;
  15017. }
  15018. else {
  15019. this._videoTextureSupported = true;
  15020. }
  15021. }
  15022. // Copy video through the current working canvas if video texture is not supported
  15023. if (!this._videoTextureSupported) {
  15024. if (!texture._workingCanvas) {
  15025. texture._workingCanvas = document.createElement("canvas");
  15026. var context = texture._workingCanvas.getContext("2d");
  15027. if (!context) {
  15028. throw new Error("Unable to get 2d context");
  15029. }
  15030. texture._workingContext = context;
  15031. texture._workingCanvas.width = texture.width;
  15032. texture._workingCanvas.height = texture.height;
  15033. }
  15034. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15035. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15036. }
  15037. else {
  15038. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15039. }
  15040. if (texture.generateMipMaps) {
  15041. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15042. }
  15043. if (!wasPreviouslyBound) {
  15044. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15045. }
  15046. // this.resetTextureCache();
  15047. texture.isReady = true;
  15048. }
  15049. catch (ex) {
  15050. // Something unexpected
  15051. // Let's disable the texture
  15052. texture._isDisabled = true;
  15053. }
  15054. };
  15055. /**
  15056. * Updates a depth texture Comparison Mode and Function.
  15057. * If the comparison Function is equal to 0, the mode will be set to none.
  15058. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15059. * @param texture The texture to set the comparison function for
  15060. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15061. */
  15062. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15063. if (this.webGLVersion === 1) {
  15064. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15065. return;
  15066. }
  15067. var gl = this._gl;
  15068. if (texture.isCube) {
  15069. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15070. if (comparisonFunction === 0) {
  15071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15072. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15073. }
  15074. else {
  15075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15076. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15077. }
  15078. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15079. }
  15080. else {
  15081. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15082. if (comparisonFunction === 0) {
  15083. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15084. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15085. }
  15086. else {
  15087. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15088. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15089. }
  15090. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15091. }
  15092. texture._comparisonFunction = comparisonFunction;
  15093. };
  15094. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15095. var width = size.width || size;
  15096. var height = size.height || size;
  15097. internalTexture.baseWidth = width;
  15098. internalTexture.baseHeight = height;
  15099. internalTexture.width = width;
  15100. internalTexture.height = height;
  15101. internalTexture.isReady = true;
  15102. internalTexture.samples = 1;
  15103. internalTexture.generateMipMaps = false;
  15104. internalTexture._generateDepthBuffer = true;
  15105. internalTexture._generateStencilBuffer = generateStencil;
  15106. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15107. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15108. internalTexture._comparisonFunction = comparisonFunction;
  15109. var gl = this._gl;
  15110. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15111. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15112. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15113. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15114. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15115. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15116. if (comparisonFunction === 0) {
  15117. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15118. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15119. }
  15120. else {
  15121. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15122. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15123. }
  15124. };
  15125. /**
  15126. * Creates a depth stencil texture.
  15127. * This is only available in WebGL 2 or with the depth texture extension available.
  15128. * @param size The size of face edge in the texture.
  15129. * @param options The options defining the texture.
  15130. * @returns The texture
  15131. */
  15132. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15133. if (options.isCube) {
  15134. var width = size.width || size;
  15135. return this._createDepthStencilCubeTexture(width, options);
  15136. }
  15137. else {
  15138. return this._createDepthStencilTexture(size, options);
  15139. }
  15140. };
  15141. /**
  15142. * Creates a depth stencil texture.
  15143. * This is only available in WebGL 2 or with the depth texture extension available.
  15144. * @param size The size of face edge in the texture.
  15145. * @param options The options defining the texture.
  15146. * @returns The texture
  15147. */
  15148. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15149. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15150. if (!this._caps.depthTextureExtension) {
  15151. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15152. return internalTexture;
  15153. }
  15154. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15155. var gl = this._gl;
  15156. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15157. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15158. if (this.webGLVersion > 1) {
  15159. if (internalOptions.generateStencil) {
  15160. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15161. }
  15162. else {
  15163. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15164. }
  15165. }
  15166. else {
  15167. if (internalOptions.generateStencil) {
  15168. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15169. }
  15170. else {
  15171. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15172. }
  15173. }
  15174. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15175. return internalTexture;
  15176. };
  15177. /**
  15178. * Creates a depth stencil cube texture.
  15179. * This is only available in WebGL 2.
  15180. * @param size The size of face edge in the cube texture.
  15181. * @param options The options defining the cube texture.
  15182. * @returns The cube texture
  15183. */
  15184. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15185. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15186. internalTexture.isCube = true;
  15187. if (this.webGLVersion === 1) {
  15188. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15189. return internalTexture;
  15190. }
  15191. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15192. var gl = this._gl;
  15193. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15194. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15195. // Create the depth/stencil buffer
  15196. for (var face = 0; face < 6; face++) {
  15197. if (internalOptions.generateStencil) {
  15198. 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);
  15199. }
  15200. else {
  15201. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15202. }
  15203. }
  15204. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15205. return internalTexture;
  15206. };
  15207. /**
  15208. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15209. * @param renderTarget The render target to set the frame buffer for
  15210. */
  15211. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15212. // Create the framebuffer
  15213. var internalTexture = renderTarget.getInternalTexture();
  15214. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15215. return;
  15216. }
  15217. var gl = this._gl;
  15218. var depthStencilTexture = renderTarget.depthStencilTexture;
  15219. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15220. if (depthStencilTexture.isCube) {
  15221. if (depthStencilTexture._generateStencilBuffer) {
  15222. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15223. }
  15224. else {
  15225. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15226. }
  15227. }
  15228. else {
  15229. if (depthStencilTexture._generateStencilBuffer) {
  15230. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15231. }
  15232. else {
  15233. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15234. }
  15235. }
  15236. this.bindUnboundFramebuffer(null);
  15237. };
  15238. /**
  15239. * Creates a new render target texture
  15240. * @param size defines the size of the texture
  15241. * @param options defines the options used to create the texture
  15242. * @returns a new render target texture stored in an InternalTexture
  15243. */
  15244. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15245. var fullOptions = new RenderTargetCreationOptions();
  15246. if (options !== undefined && typeof options === "object") {
  15247. fullOptions.generateMipMaps = options.generateMipMaps;
  15248. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15249. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15250. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15251. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15252. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15253. }
  15254. else {
  15255. fullOptions.generateMipMaps = options;
  15256. fullOptions.generateDepthBuffer = true;
  15257. fullOptions.generateStencilBuffer = false;
  15258. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15259. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15260. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15261. }
  15262. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15263. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15264. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15265. }
  15266. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15267. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15268. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15269. }
  15270. var gl = this._gl;
  15271. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15272. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15273. var width = size.width || size;
  15274. var height = size.height || size;
  15275. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15276. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15277. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15278. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15279. }
  15280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15281. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15284. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15285. // Create the framebuffer
  15286. var currentFrameBuffer = this._currentFramebuffer;
  15287. var framebuffer = gl.createFramebuffer();
  15288. this.bindUnboundFramebuffer(framebuffer);
  15289. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15290. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15291. if (fullOptions.generateMipMaps) {
  15292. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15293. }
  15294. // Unbind
  15295. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15296. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15297. this.bindUnboundFramebuffer(currentFrameBuffer);
  15298. texture._framebuffer = framebuffer;
  15299. texture.baseWidth = width;
  15300. texture.baseHeight = height;
  15301. texture.width = width;
  15302. texture.height = height;
  15303. texture.isReady = true;
  15304. texture.samples = 1;
  15305. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15306. texture.samplingMode = fullOptions.samplingMode;
  15307. texture.type = fullOptions.type;
  15308. texture.format = fullOptions.format;
  15309. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15310. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15311. // this.resetTextureCache();
  15312. this._internalTexturesCache.push(texture);
  15313. return texture;
  15314. };
  15315. /**
  15316. * Create a multi render target texture
  15317. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15318. * @param size defines the size of the texture
  15319. * @param options defines the creation options
  15320. * @returns the cube texture as an InternalTexture
  15321. */
  15322. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15323. var generateMipMaps = false;
  15324. var generateDepthBuffer = true;
  15325. var generateStencilBuffer = false;
  15326. var generateDepthTexture = false;
  15327. var textureCount = 1;
  15328. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15329. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15330. var types = new Array();
  15331. var samplingModes = new Array();
  15332. if (options !== undefined) {
  15333. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15334. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15335. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15336. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15337. textureCount = options.textureCount || 1;
  15338. if (options.types) {
  15339. types = options.types;
  15340. }
  15341. if (options.samplingModes) {
  15342. samplingModes = options.samplingModes;
  15343. }
  15344. }
  15345. var gl = this._gl;
  15346. // Create the framebuffer
  15347. var framebuffer = gl.createFramebuffer();
  15348. this.bindUnboundFramebuffer(framebuffer);
  15349. var width = size.width || size;
  15350. var height = size.height || size;
  15351. var textures = [];
  15352. var attachments = [];
  15353. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15354. for (var i = 0; i < textureCount; i++) {
  15355. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15356. var type = types[i] || defaultType;
  15357. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15358. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15359. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15360. }
  15361. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15362. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15363. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15364. }
  15365. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15366. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15367. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15368. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15369. }
  15370. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15371. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15372. textures.push(texture);
  15373. attachments.push(attachment);
  15374. gl.activeTexture(gl["TEXTURE" + i]);
  15375. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15376. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15377. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15378. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15379. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15380. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15381. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15382. if (generateMipMaps) {
  15383. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15384. }
  15385. // Unbind
  15386. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15387. texture._framebuffer = framebuffer;
  15388. texture._depthStencilBuffer = depthStencilBuffer;
  15389. texture.baseWidth = width;
  15390. texture.baseHeight = height;
  15391. texture.width = width;
  15392. texture.height = height;
  15393. texture.isReady = true;
  15394. texture.samples = 1;
  15395. texture.generateMipMaps = generateMipMaps;
  15396. texture.samplingMode = samplingMode;
  15397. texture.type = type;
  15398. texture._generateDepthBuffer = generateDepthBuffer;
  15399. texture._generateStencilBuffer = generateStencilBuffer;
  15400. texture._attachments = attachments;
  15401. this._internalTexturesCache.push(texture);
  15402. }
  15403. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15404. // Depth texture
  15405. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15406. gl.activeTexture(gl.TEXTURE0);
  15407. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15408. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15410. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15411. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15412. 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);
  15413. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15414. depthTexture._framebuffer = framebuffer;
  15415. depthTexture.baseWidth = width;
  15416. depthTexture.baseHeight = height;
  15417. depthTexture.width = width;
  15418. depthTexture.height = height;
  15419. depthTexture.isReady = true;
  15420. depthTexture.samples = 1;
  15421. depthTexture.generateMipMaps = generateMipMaps;
  15422. depthTexture.samplingMode = gl.NEAREST;
  15423. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15424. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15425. textures.push(depthTexture);
  15426. this._internalTexturesCache.push(depthTexture);
  15427. }
  15428. gl.drawBuffers(attachments);
  15429. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15430. this.bindUnboundFramebuffer(null);
  15431. this.resetTextureCache();
  15432. return textures;
  15433. };
  15434. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15435. if (samples === void 0) { samples = 1; }
  15436. var depthStencilBuffer = null;
  15437. var gl = this._gl;
  15438. // Create the depth/stencil buffer
  15439. if (generateStencilBuffer) {
  15440. depthStencilBuffer = gl.createRenderbuffer();
  15441. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15442. if (samples > 1) {
  15443. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15444. }
  15445. else {
  15446. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15447. }
  15448. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15449. }
  15450. else if (generateDepthBuffer) {
  15451. depthStencilBuffer = gl.createRenderbuffer();
  15452. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15453. if (samples > 1) {
  15454. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15455. }
  15456. else {
  15457. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15458. }
  15459. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15460. }
  15461. return depthStencilBuffer;
  15462. };
  15463. /**
  15464. * Updates the sample count of a render target texture
  15465. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15466. * @param texture defines the texture to update
  15467. * @param samples defines the sample count to set
  15468. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15469. */
  15470. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15471. if (this.webGLVersion < 2 || !texture) {
  15472. return 1;
  15473. }
  15474. if (texture.samples === samples) {
  15475. return samples;
  15476. }
  15477. var gl = this._gl;
  15478. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15479. // Dispose previous render buffers
  15480. if (texture._depthStencilBuffer) {
  15481. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15482. texture._depthStencilBuffer = null;
  15483. }
  15484. if (texture._MSAAFramebuffer) {
  15485. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15486. texture._MSAAFramebuffer = null;
  15487. }
  15488. if (texture._MSAARenderBuffer) {
  15489. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15490. texture._MSAARenderBuffer = null;
  15491. }
  15492. if (samples > 1) {
  15493. var framebuffer = gl.createFramebuffer();
  15494. if (!framebuffer) {
  15495. throw new Error("Unable to create multi sampled framebuffer");
  15496. }
  15497. texture._MSAAFramebuffer = framebuffer;
  15498. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15499. var colorRenderbuffer = gl.createRenderbuffer();
  15500. if (!colorRenderbuffer) {
  15501. throw new Error("Unable to create multi sampled framebuffer");
  15502. }
  15503. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15504. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15505. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15506. texture._MSAARenderBuffer = colorRenderbuffer;
  15507. }
  15508. else {
  15509. this.bindUnboundFramebuffer(texture._framebuffer);
  15510. }
  15511. texture.samples = samples;
  15512. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15513. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15514. this.bindUnboundFramebuffer(null);
  15515. return samples;
  15516. };
  15517. /**
  15518. * Update the sample count for a given multiple render target texture
  15519. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15520. * @param textures defines the textures to update
  15521. * @param samples defines the sample count to set
  15522. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15523. */
  15524. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15525. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15526. return 1;
  15527. }
  15528. if (textures[0].samples === samples) {
  15529. return samples;
  15530. }
  15531. var gl = this._gl;
  15532. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15533. // Dispose previous render buffers
  15534. if (textures[0]._depthStencilBuffer) {
  15535. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15536. textures[0]._depthStencilBuffer = null;
  15537. }
  15538. if (textures[0]._MSAAFramebuffer) {
  15539. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15540. textures[0]._MSAAFramebuffer = null;
  15541. }
  15542. for (var i = 0; i < textures.length; i++) {
  15543. if (textures[i]._MSAARenderBuffer) {
  15544. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15545. textures[i]._MSAARenderBuffer = null;
  15546. }
  15547. }
  15548. if (samples > 1) {
  15549. var framebuffer = gl.createFramebuffer();
  15550. if (!framebuffer) {
  15551. throw new Error("Unable to create multi sampled framebuffer");
  15552. }
  15553. this.bindUnboundFramebuffer(framebuffer);
  15554. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15555. var attachments = [];
  15556. for (var i = 0; i < textures.length; i++) {
  15557. var texture = textures[i];
  15558. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15559. var colorRenderbuffer = gl.createRenderbuffer();
  15560. if (!colorRenderbuffer) {
  15561. throw new Error("Unable to create multi sampled framebuffer");
  15562. }
  15563. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15564. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15565. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15566. texture._MSAAFramebuffer = framebuffer;
  15567. texture._MSAARenderBuffer = colorRenderbuffer;
  15568. texture.samples = samples;
  15569. texture._depthStencilBuffer = depthStencilBuffer;
  15570. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15571. attachments.push(attachment);
  15572. }
  15573. gl.drawBuffers(attachments);
  15574. }
  15575. else {
  15576. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15577. }
  15578. this.bindUnboundFramebuffer(null);
  15579. return samples;
  15580. };
  15581. /** @hidden */
  15582. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15583. if (faceIndex === void 0) { faceIndex = 0; }
  15584. if (lod === void 0) { lod = 0; }
  15585. var gl = this._gl;
  15586. var target = gl.TEXTURE_2D;
  15587. if (texture.isCube) {
  15588. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15589. }
  15590. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15591. };
  15592. /** @hidden */
  15593. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15594. if (faceIndex === void 0) { faceIndex = 0; }
  15595. if (lod === void 0) { lod = 0; }
  15596. var gl = this._gl;
  15597. var textureType = this._getWebGLTextureType(texture.type);
  15598. var format = this._getInternalFormat(texture.format);
  15599. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15600. this._unpackFlipY(texture.invertY);
  15601. var target = gl.TEXTURE_2D;
  15602. if (texture.isCube) {
  15603. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15604. }
  15605. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15606. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15607. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15608. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15609. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15610. };
  15611. /** @hidden */
  15612. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15613. if (faceIndex === void 0) { faceIndex = 0; }
  15614. if (lod === void 0) { lod = 0; }
  15615. var gl = this._gl;
  15616. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15617. this._bindTextureDirectly(bindTarget, texture, true);
  15618. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15619. this._bindTextureDirectly(bindTarget, null, true);
  15620. };
  15621. /** @hidden */
  15622. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15623. if (faceIndex === void 0) { faceIndex = 0; }
  15624. if (lod === void 0) { lod = 0; }
  15625. var gl = this._gl;
  15626. var textureType = this._getWebGLTextureType(texture.type);
  15627. var format = this._getInternalFormat(texture.format);
  15628. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15629. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15630. this._bindTextureDirectly(bindTarget, texture, true);
  15631. this._unpackFlipY(texture.invertY);
  15632. var target = gl.TEXTURE_2D;
  15633. if (texture.isCube) {
  15634. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15635. }
  15636. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15637. this._bindTextureDirectly(bindTarget, null, true);
  15638. };
  15639. /**
  15640. * Creates a new render target cube texture
  15641. * @param size defines the size of the texture
  15642. * @param options defines the options used to create the texture
  15643. * @returns a new render target cube texture stored in an InternalTexture
  15644. */
  15645. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15646. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15647. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15648. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15649. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15650. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15651. }
  15652. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15653. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15654. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15655. }
  15656. var gl = this._gl;
  15657. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15658. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15659. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15660. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15661. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15662. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15663. }
  15664. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15666. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15668. for (var face = 0; face < 6; face++) {
  15669. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15670. }
  15671. // Create the framebuffer
  15672. var framebuffer = gl.createFramebuffer();
  15673. this.bindUnboundFramebuffer(framebuffer);
  15674. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15675. // MipMaps
  15676. if (fullOptions.generateMipMaps) {
  15677. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15678. }
  15679. // Unbind
  15680. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15681. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15682. this.bindUnboundFramebuffer(null);
  15683. texture._framebuffer = framebuffer;
  15684. texture.width = size;
  15685. texture.height = size;
  15686. texture.isReady = true;
  15687. texture.isCube = true;
  15688. texture.samples = 1;
  15689. texture.generateMipMaps = fullOptions.generateMipMaps;
  15690. texture.samplingMode = fullOptions.samplingMode;
  15691. texture.type = fullOptions.type;
  15692. texture.format = fullOptions.format;
  15693. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15694. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15695. this._internalTexturesCache.push(texture);
  15696. return texture;
  15697. };
  15698. /**
  15699. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15700. * @param rootUrl defines the url where the file to load is located
  15701. * @param scene defines the current scene
  15702. * @param lodScale defines scale to apply to the mip map selection
  15703. * @param lodOffset defines offset to apply to the mip map selection
  15704. * @param onLoad defines an optional callback raised when the texture is loaded
  15705. * @param onError defines an optional callback raised if there is an issue to load the texture
  15706. * @param format defines the format of the data
  15707. * @param forcedExtension defines the extension to use to pick the right loader
  15708. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15709. * @returns the cube texture as an InternalTexture
  15710. */
  15711. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15712. var _this = this;
  15713. if (onLoad === void 0) { onLoad = null; }
  15714. if (onError === void 0) { onError = null; }
  15715. if (forcedExtension === void 0) { forcedExtension = null; }
  15716. if (createPolynomials === void 0) { createPolynomials = true; }
  15717. var callback = function (loadData) {
  15718. if (!loadData) {
  15719. if (onLoad) {
  15720. onLoad(null);
  15721. }
  15722. return;
  15723. }
  15724. var texture = loadData.texture;
  15725. if (!createPolynomials) {
  15726. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15727. }
  15728. else if (loadData.info.sphericalPolynomial) {
  15729. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15730. }
  15731. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15732. if (_this._caps.textureLOD) {
  15733. // Do not add extra process if texture lod is supported.
  15734. if (onLoad) {
  15735. onLoad(texture);
  15736. }
  15737. return;
  15738. }
  15739. var mipSlices = 3;
  15740. var gl = _this._gl;
  15741. var width = loadData.width;
  15742. if (!width) {
  15743. return;
  15744. }
  15745. var textures = [];
  15746. for (var i = 0; i < mipSlices; i++) {
  15747. //compute LOD from even spacing in smoothness (matching shader calculation)
  15748. var smoothness = i / (mipSlices - 1);
  15749. var roughness = 1 - smoothness;
  15750. var minLODIndex = lodOffset; // roughness = 0
  15751. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15752. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15753. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15754. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15755. glTextureFromLod.type = texture.type;
  15756. glTextureFromLod.format = texture.format;
  15757. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15758. glTextureFromLod.height = glTextureFromLod.width;
  15759. glTextureFromLod.isCube = true;
  15760. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15761. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15764. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15765. if (loadData.isDDS) {
  15766. var info = loadData.info;
  15767. var data = loadData.data;
  15768. _this._unpackFlipY(info.isCompressed);
  15769. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15770. }
  15771. else {
  15772. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15773. }
  15774. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15775. // Wrap in a base texture for easy binding.
  15776. var lodTexture = new BABYLON.BaseTexture(scene);
  15777. lodTexture.isCube = true;
  15778. lodTexture._texture = glTextureFromLod;
  15779. glTextureFromLod.isReady = true;
  15780. textures.push(lodTexture);
  15781. }
  15782. texture._lodTextureHigh = textures[2];
  15783. texture._lodTextureMid = textures[1];
  15784. texture._lodTextureLow = textures[0];
  15785. if (onLoad) {
  15786. onLoad(texture);
  15787. }
  15788. };
  15789. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15790. };
  15791. /**
  15792. * Creates a cube texture
  15793. * @param rootUrl defines the url where the files to load is located
  15794. * @param scene defines the current scene
  15795. * @param files defines the list of files to load (1 per face)
  15796. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15797. * @param onLoad defines an optional callback raised when the texture is loaded
  15798. * @param onError defines an optional callback raised if there is an issue to load the texture
  15799. * @param format defines the format of the data
  15800. * @param forcedExtension defines the extension to use to pick the right loader
  15801. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15802. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15803. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15804. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15805. * @returns the cube texture as an InternalTexture
  15806. */
  15807. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15808. var _this = this;
  15809. if (onLoad === void 0) { onLoad = null; }
  15810. if (onError === void 0) { onError = null; }
  15811. if (forcedExtension === void 0) { forcedExtension = null; }
  15812. if (createPolynomials === void 0) { createPolynomials = false; }
  15813. if (lodScale === void 0) { lodScale = 0; }
  15814. if (lodOffset === void 0) { lodOffset = 0; }
  15815. if (fallback === void 0) { fallback = null; }
  15816. var gl = this._gl;
  15817. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15818. texture.isCube = true;
  15819. texture.url = rootUrl;
  15820. texture.generateMipMaps = !noMipmap;
  15821. texture._lodGenerationScale = lodScale;
  15822. texture._lodGenerationOffset = lodOffset;
  15823. if (!this._doNotHandleContextLost) {
  15824. texture._extension = forcedExtension;
  15825. texture._files = files;
  15826. }
  15827. var lastDot = rootUrl.lastIndexOf('.');
  15828. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15829. var loader = null;
  15830. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15831. var availableLoader = _a[_i];
  15832. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15833. loader = availableLoader;
  15834. break;
  15835. }
  15836. }
  15837. var onInternalError = function (request, exception) {
  15838. if (loader) {
  15839. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15840. if (fallbackUrl) {
  15841. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15842. }
  15843. }
  15844. if (onError && request) {
  15845. onError(request.status + " " + request.statusText, exception);
  15846. }
  15847. };
  15848. if (loader) {
  15849. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15850. var onloaddata = function (data) {
  15851. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15852. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15853. };
  15854. if (files && files.length === 6) {
  15855. if (loader.supportCascades) {
  15856. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15857. }
  15858. else if (onError) {
  15859. onError("Textures type does not support cascades.");
  15860. }
  15861. }
  15862. else {
  15863. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15864. }
  15865. }
  15866. else {
  15867. if (!files) {
  15868. throw new Error("Cannot load cubemap because files were not defined");
  15869. }
  15870. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15871. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15872. var height = width;
  15873. _this._prepareWorkingCanvas();
  15874. if (!_this._workingCanvas || !_this._workingContext) {
  15875. return;
  15876. }
  15877. _this._workingCanvas.width = width;
  15878. _this._workingCanvas.height = height;
  15879. var faces = [
  15880. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15881. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15882. ];
  15883. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15884. _this._unpackFlipY(false);
  15885. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15886. for (var index = 0; index < faces.length; index++) {
  15887. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15888. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15889. }
  15890. if (!noMipmap) {
  15891. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15892. }
  15893. _this._setCubeMapTextureParams(!noMipmap);
  15894. texture.width = width;
  15895. texture.height = height;
  15896. texture.isReady = true;
  15897. if (format) {
  15898. texture.format = format;
  15899. }
  15900. texture.onLoadedObservable.notifyObservers(texture);
  15901. texture.onLoadedObservable.clear();
  15902. if (onLoad) {
  15903. onLoad();
  15904. }
  15905. }, files, onError);
  15906. }
  15907. this._internalTexturesCache.push(texture);
  15908. return texture;
  15909. };
  15910. /**
  15911. * @hidden
  15912. */
  15913. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15914. var gl = this._gl;
  15915. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15916. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15917. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15918. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15919. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15920. // this.resetTextureCache();
  15921. };
  15922. /**
  15923. * Update a raw cube texture
  15924. * @param texture defines the texture to udpdate
  15925. * @param data defines the data to store
  15926. * @param format defines the data format
  15927. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15928. * @param invertY defines if data must be stored with Y axis inverted
  15929. * @param compression defines the compression used (null by default)
  15930. * @param level defines which level of the texture to update
  15931. */
  15932. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15933. if (compression === void 0) { compression = null; }
  15934. if (level === void 0) { level = 0; }
  15935. texture._bufferViewArray = data;
  15936. texture.format = format;
  15937. texture.type = type;
  15938. texture.invertY = invertY;
  15939. texture._compression = compression;
  15940. var gl = this._gl;
  15941. var textureType = this._getWebGLTextureType(type);
  15942. var internalFormat = this._getInternalFormat(format);
  15943. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15944. var needConversion = false;
  15945. if (internalFormat === gl.RGB) {
  15946. internalFormat = gl.RGBA;
  15947. needConversion = true;
  15948. }
  15949. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15950. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15951. if (texture.width % 4 !== 0) {
  15952. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15953. }
  15954. // Data are known to be in +X +Y +Z -X -Y -Z
  15955. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15956. var faceData = data[faceIndex];
  15957. if (compression) {
  15958. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15959. }
  15960. else {
  15961. if (needConversion) {
  15962. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15963. }
  15964. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15965. }
  15966. }
  15967. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15968. if (isPot && texture.generateMipMaps && level === 0) {
  15969. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15970. }
  15971. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15972. // this.resetTextureCache();
  15973. texture.isReady = true;
  15974. };
  15975. /**
  15976. * Creates a new raw cube texture
  15977. * @param data defines the array of data to use to create each face
  15978. * @param size defines the size of the textures
  15979. * @param format defines the format of the data
  15980. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15981. * @param generateMipMaps defines if the engine should generate the mip levels
  15982. * @param invertY defines if data must be stored with Y axis inverted
  15983. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15984. * @param compression defines the compression used (null by default)
  15985. * @returns the cube texture as an InternalTexture
  15986. */
  15987. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15988. if (compression === void 0) { compression = null; }
  15989. var gl = this._gl;
  15990. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15991. texture.isCube = true;
  15992. texture.format = format;
  15993. texture.type = type;
  15994. if (!this._doNotHandleContextLost) {
  15995. texture._bufferViewArray = data;
  15996. }
  15997. var textureType = this._getWebGLTextureType(type);
  15998. var internalFormat = this._getInternalFormat(format);
  15999. if (internalFormat === gl.RGB) {
  16000. internalFormat = gl.RGBA;
  16001. }
  16002. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16003. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16004. generateMipMaps = false;
  16005. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16006. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16007. }
  16008. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16009. generateMipMaps = false;
  16010. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16011. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16012. }
  16013. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16014. generateMipMaps = false;
  16015. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16016. }
  16017. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16018. generateMipMaps = false;
  16019. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16020. }
  16021. var width = size;
  16022. var height = width;
  16023. texture.width = width;
  16024. texture.height = height;
  16025. // Double check on POT to generate Mips.
  16026. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16027. if (!isPot) {
  16028. generateMipMaps = false;
  16029. }
  16030. // Upload data if needed. The texture won't be ready until then.
  16031. if (data) {
  16032. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16033. }
  16034. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16035. // Filters
  16036. if (data && generateMipMaps) {
  16037. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16038. }
  16039. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16040. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16041. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16042. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16043. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16044. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16045. texture.generateMipMaps = generateMipMaps;
  16046. return texture;
  16047. };
  16048. /**
  16049. * Creates a new raw cube texture from a specified url
  16050. * @param url defines the url where the data is located
  16051. * @param scene defines the current scene
  16052. * @param size defines the size of the textures
  16053. * @param format defines the format of the data
  16054. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16055. * @param noMipmap defines if the engine should avoid generating the mip levels
  16056. * @param callback defines a callback used to extract texture data from loaded data
  16057. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16058. * @param onLoad defines a callback called when texture is loaded
  16059. * @param onError defines a callback called if there is an error
  16060. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16061. * @param invertY defines if data must be stored with Y axis inverted
  16062. * @returns the cube texture as an InternalTexture
  16063. */
  16064. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16065. var _this = this;
  16066. if (onLoad === void 0) { onLoad = null; }
  16067. if (onError === void 0) { onError = null; }
  16068. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16069. if (invertY === void 0) { invertY = false; }
  16070. var gl = this._gl;
  16071. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16072. scene._addPendingData(texture);
  16073. texture.url = url;
  16074. this._internalTexturesCache.push(texture);
  16075. var onerror = function (request, exception) {
  16076. scene._removePendingData(texture);
  16077. if (onError && request) {
  16078. onError(request.status + " " + request.statusText, exception);
  16079. }
  16080. };
  16081. var internalCallback = function (data) {
  16082. var width = texture.width;
  16083. var faceDataArrays = callback(data);
  16084. if (!faceDataArrays) {
  16085. return;
  16086. }
  16087. if (mipmapGenerator) {
  16088. var textureType = _this._getWebGLTextureType(type);
  16089. var internalFormat = _this._getInternalFormat(format);
  16090. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16091. var needConversion = false;
  16092. if (internalFormat === gl.RGB) {
  16093. internalFormat = gl.RGBA;
  16094. needConversion = true;
  16095. }
  16096. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16097. _this._unpackFlipY(false);
  16098. var mipData = mipmapGenerator(faceDataArrays);
  16099. for (var level = 0; level < mipData.length; level++) {
  16100. var mipSize = width >> level;
  16101. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16102. var mipFaceData = mipData[level][faceIndex];
  16103. if (needConversion) {
  16104. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16105. }
  16106. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16107. }
  16108. }
  16109. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16110. }
  16111. else {
  16112. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16113. }
  16114. texture.isReady = true;
  16115. // this.resetTextureCache();
  16116. scene._removePendingData(texture);
  16117. if (onLoad) {
  16118. onLoad();
  16119. }
  16120. };
  16121. this._loadFile(url, function (data) {
  16122. internalCallback(data);
  16123. }, undefined, scene.database, true, onerror);
  16124. return texture;
  16125. };
  16126. ;
  16127. /**
  16128. * Update a raw 3D texture
  16129. * @param texture defines the texture to update
  16130. * @param data defines the data to store
  16131. * @param format defines the data format
  16132. * @param invertY defines if data must be stored with Y axis inverted
  16133. * @param compression defines the used compression (can be null)
  16134. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16135. */
  16136. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16137. if (compression === void 0) { compression = null; }
  16138. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16139. var internalType = this._getWebGLTextureType(textureType);
  16140. var internalFormat = this._getInternalFormat(format);
  16141. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16142. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16143. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16144. if (!this._doNotHandleContextLost) {
  16145. texture._bufferView = data;
  16146. texture.format = format;
  16147. texture.invertY = invertY;
  16148. texture._compression = compression;
  16149. }
  16150. if (texture.width % 4 !== 0) {
  16151. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16152. }
  16153. if (compression && data) {
  16154. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16155. }
  16156. else {
  16157. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16158. }
  16159. if (texture.generateMipMaps) {
  16160. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16161. }
  16162. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16163. // this.resetTextureCache();
  16164. texture.isReady = true;
  16165. };
  16166. /**
  16167. * Creates a new raw 3D texture
  16168. * @param data defines the data used to create the texture
  16169. * @param width defines the width of the texture
  16170. * @param height defines the height of the texture
  16171. * @param depth defines the depth of the texture
  16172. * @param format defines the format of the texture
  16173. * @param generateMipMaps defines if the engine must generate mip levels
  16174. * @param invertY defines if data must be stored with Y axis inverted
  16175. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16176. * @param compression defines the compressed used (can be null)
  16177. * @param textureType defines the compressed used (can be null)
  16178. * @returns a new raw 3D texture (stored in an InternalTexture)
  16179. */
  16180. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16181. if (compression === void 0) { compression = null; }
  16182. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16183. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16184. texture.baseWidth = width;
  16185. texture.baseHeight = height;
  16186. texture.baseDepth = depth;
  16187. texture.width = width;
  16188. texture.height = height;
  16189. texture.depth = depth;
  16190. texture.format = format;
  16191. texture.type = textureType;
  16192. texture.generateMipMaps = generateMipMaps;
  16193. texture.samplingMode = samplingMode;
  16194. texture.is3D = true;
  16195. if (!this._doNotHandleContextLost) {
  16196. texture._bufferView = data;
  16197. }
  16198. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16199. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16200. // Filters
  16201. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16202. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16203. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16204. if (generateMipMaps) {
  16205. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16206. }
  16207. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16208. this._internalTexturesCache.push(texture);
  16209. return texture;
  16210. };
  16211. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16212. var gl = this._gl;
  16213. if (!gl) {
  16214. return;
  16215. }
  16216. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16219. if (!noMipmap && !isCompressed) {
  16220. gl.generateMipmap(gl.TEXTURE_2D);
  16221. }
  16222. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16223. // this.resetTextureCache();
  16224. if (scene) {
  16225. scene._removePendingData(texture);
  16226. }
  16227. texture.onLoadedObservable.notifyObservers(texture);
  16228. texture.onLoadedObservable.clear();
  16229. };
  16230. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16231. var _this = this;
  16232. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16233. var maxTextureSize = this.getCaps().maxTextureSize;
  16234. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16235. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16236. var gl = this._gl;
  16237. if (!gl) {
  16238. return;
  16239. }
  16240. if (!texture._webGLTexture) {
  16241. // this.resetTextureCache();
  16242. if (scene) {
  16243. scene._removePendingData(texture);
  16244. }
  16245. return;
  16246. }
  16247. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16248. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16249. texture.baseWidth = width;
  16250. texture.baseHeight = height;
  16251. texture.width = potWidth;
  16252. texture.height = potHeight;
  16253. texture.isReady = true;
  16254. if (processFunction(potWidth, potHeight, function () {
  16255. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16256. })) {
  16257. // Returning as texture needs extra async steps
  16258. return;
  16259. }
  16260. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16261. };
  16262. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16263. // Create new RGBA data container.
  16264. var rgbaData;
  16265. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16266. rgbaData = new Float32Array(width * height * 4);
  16267. }
  16268. else {
  16269. rgbaData = new Uint32Array(width * height * 4);
  16270. }
  16271. // Convert each pixel.
  16272. for (var x = 0; x < width; x++) {
  16273. for (var y = 0; y < height; y++) {
  16274. var index = (y * width + x) * 3;
  16275. var newIndex = (y * width + x) * 4;
  16276. // Map Old Value to new value.
  16277. rgbaData[newIndex + 0] = rgbData[index + 0];
  16278. rgbaData[newIndex + 1] = rgbData[index + 1];
  16279. rgbaData[newIndex + 2] = rgbData[index + 2];
  16280. // Add fully opaque alpha channel.
  16281. rgbaData[newIndex + 3] = 1;
  16282. }
  16283. }
  16284. return rgbaData;
  16285. };
  16286. /** @hidden */
  16287. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16288. var gl = this._gl;
  16289. if (texture._framebuffer) {
  16290. gl.deleteFramebuffer(texture._framebuffer);
  16291. texture._framebuffer = null;
  16292. }
  16293. if (texture._depthStencilBuffer) {
  16294. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16295. texture._depthStencilBuffer = null;
  16296. }
  16297. if (texture._MSAAFramebuffer) {
  16298. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16299. texture._MSAAFramebuffer = null;
  16300. }
  16301. if (texture._MSAARenderBuffer) {
  16302. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16303. texture._MSAARenderBuffer = null;
  16304. }
  16305. };
  16306. /** @hidden */
  16307. Engine.prototype._releaseTexture = function (texture) {
  16308. var gl = this._gl;
  16309. this._releaseFramebufferObjects(texture);
  16310. gl.deleteTexture(texture._webGLTexture);
  16311. // Unbind channels
  16312. this.unbindAllTextures();
  16313. var index = this._internalTexturesCache.indexOf(texture);
  16314. if (index !== -1) {
  16315. this._internalTexturesCache.splice(index, 1);
  16316. }
  16317. // Integrated fixed lod samplers.
  16318. if (texture._lodTextureHigh) {
  16319. texture._lodTextureHigh.dispose();
  16320. }
  16321. if (texture._lodTextureMid) {
  16322. texture._lodTextureMid.dispose();
  16323. }
  16324. if (texture._lodTextureLow) {
  16325. texture._lodTextureLow.dispose();
  16326. }
  16327. // Set output texture of post process to null if the texture has been released/disposed
  16328. this.scenes.forEach(function (scene) {
  16329. scene.postProcesses.forEach(function (postProcess) {
  16330. if (postProcess._outputTexture == texture) {
  16331. postProcess._outputTexture = null;
  16332. }
  16333. });
  16334. scene.cameras.forEach(function (camera) {
  16335. camera._postProcesses.forEach(function (postProcess) {
  16336. if (postProcess) {
  16337. if (postProcess._outputTexture == texture) {
  16338. postProcess._outputTexture = null;
  16339. }
  16340. }
  16341. });
  16342. });
  16343. });
  16344. };
  16345. Engine.prototype.setProgram = function (program) {
  16346. if (this._currentProgram !== program) {
  16347. this._gl.useProgram(program);
  16348. this._currentProgram = program;
  16349. }
  16350. };
  16351. /**
  16352. * Binds an effect to the webGL context
  16353. * @param effect defines the effect to bind
  16354. */
  16355. Engine.prototype.bindSamplers = function (effect) {
  16356. this.setProgram(effect.getProgram());
  16357. var samplers = effect.getSamplers();
  16358. for (var index = 0; index < samplers.length; index++) {
  16359. var uniform = effect.getUniform(samplers[index]);
  16360. if (uniform) {
  16361. this._boundUniforms[index] = uniform;
  16362. }
  16363. }
  16364. this._currentEffect = null;
  16365. };
  16366. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16367. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16368. return;
  16369. }
  16370. // Remove
  16371. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16372. // Bind last to it
  16373. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16374. // Bind to dummy
  16375. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16376. };
  16377. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16378. if (!internalTexture) {
  16379. return -1;
  16380. }
  16381. internalTexture._initialSlot = channel;
  16382. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16383. if (channel !== internalTexture._designatedSlot) {
  16384. this._textureCollisions.addCount(1, false);
  16385. }
  16386. }
  16387. else {
  16388. if (channel !== internalTexture._designatedSlot) {
  16389. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16390. return internalTexture._designatedSlot;
  16391. }
  16392. else {
  16393. // No slot for this texture, let's pick a new one (if we find a free slot)
  16394. if (this._nextFreeTextureSlots.length) {
  16395. return this._nextFreeTextureSlots[0];
  16396. }
  16397. // We need to recycle the oldest bound texture, sorry.
  16398. this._textureCollisions.addCount(1, false);
  16399. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16400. }
  16401. }
  16402. }
  16403. return channel;
  16404. };
  16405. Engine.prototype._linkTrackers = function (previous, next) {
  16406. previous.next = next;
  16407. next.previous = previous;
  16408. };
  16409. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16410. var currentSlot = internalTexture._designatedSlot;
  16411. if (currentSlot === -1) {
  16412. return -1;
  16413. }
  16414. internalTexture._designatedSlot = -1;
  16415. if (this.disableTextureBindingOptimization) {
  16416. return -1;
  16417. }
  16418. // Remove from bound list
  16419. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16420. // Free the slot
  16421. this._boundTexturesCache[currentSlot] = null;
  16422. this._nextFreeTextureSlots.push(currentSlot);
  16423. return currentSlot;
  16424. };
  16425. Engine.prototype._activateCurrentTexture = function () {
  16426. if (this._currentTextureChannel !== this._activeChannel) {
  16427. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16428. this._currentTextureChannel = this._activeChannel;
  16429. }
  16430. };
  16431. /** @hidden */
  16432. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16433. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16434. if (force === void 0) { force = false; }
  16435. var wasPreviouslyBound = false;
  16436. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16437. this._activeChannel = texture._designatedSlot;
  16438. }
  16439. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16440. var isTextureForRendering = texture && texture._initialSlot > -1;
  16441. if (currentTextureBound !== texture || force) {
  16442. if (currentTextureBound) {
  16443. this._removeDesignatedSlot(currentTextureBound);
  16444. }
  16445. this._activateCurrentTexture();
  16446. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16447. this._boundTexturesCache[this._activeChannel] = texture;
  16448. if (texture) {
  16449. if (!this.disableTextureBindingOptimization) {
  16450. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16451. if (slotIndex > -1) {
  16452. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16453. }
  16454. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16455. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16456. }
  16457. texture._designatedSlot = this._activeChannel;
  16458. }
  16459. }
  16460. else if (forTextureDataUpdate) {
  16461. wasPreviouslyBound = true;
  16462. this._activateCurrentTexture();
  16463. }
  16464. if (isTextureForRendering && !forTextureDataUpdate) {
  16465. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16466. }
  16467. return wasPreviouslyBound;
  16468. };
  16469. /** @hidden */
  16470. Engine.prototype._bindTexture = function (channel, texture) {
  16471. if (channel < 0) {
  16472. return;
  16473. }
  16474. if (texture) {
  16475. channel = this._getCorrectTextureChannel(channel, texture);
  16476. }
  16477. this._activeChannel = channel;
  16478. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16479. };
  16480. /**
  16481. * Sets a texture to the webGL context from a postprocess
  16482. * @param channel defines the channel to use
  16483. * @param postProcess defines the source postprocess
  16484. */
  16485. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16486. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16487. };
  16488. /**
  16489. * Binds the output of the passed in post process to the texture channel specified
  16490. * @param channel The channel the texture should be bound to
  16491. * @param postProcess The post process which's output should be bound
  16492. */
  16493. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16494. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16495. };
  16496. /**
  16497. * Unbind all textures from the webGL context
  16498. */
  16499. Engine.prototype.unbindAllTextures = function () {
  16500. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16501. this._activeChannel = channel;
  16502. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16503. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16504. if (this.webGLVersion > 1) {
  16505. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16506. }
  16507. }
  16508. };
  16509. /**
  16510. * Sets a texture to the according uniform.
  16511. * @param channel The texture channel
  16512. * @param uniform The uniform to set
  16513. * @param texture The texture to apply
  16514. */
  16515. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16516. if (channel < 0) {
  16517. return;
  16518. }
  16519. if (uniform) {
  16520. this._boundUniforms[channel] = uniform;
  16521. }
  16522. this._setTexture(channel, texture);
  16523. };
  16524. /**
  16525. * Sets a depth stencil texture from a render target to the according uniform.
  16526. * @param channel The texture channel
  16527. * @param uniform The uniform to set
  16528. * @param texture The render target texture containing the depth stencil texture to apply
  16529. */
  16530. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16531. if (channel < 0) {
  16532. return;
  16533. }
  16534. if (uniform) {
  16535. this._boundUniforms[channel] = uniform;
  16536. }
  16537. if (!texture || !texture.depthStencilTexture) {
  16538. this._setTexture(channel, null);
  16539. }
  16540. else {
  16541. this._setTexture(channel, texture, false, true);
  16542. }
  16543. };
  16544. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16545. var uniform = this._boundUniforms[sourceSlot];
  16546. if (uniform._currentState === destination) {
  16547. return;
  16548. }
  16549. this._gl.uniform1i(uniform, destination);
  16550. uniform._currentState = destination;
  16551. };
  16552. Engine.prototype._getTextureWrapMode = function (mode) {
  16553. switch (mode) {
  16554. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16555. return this._gl.REPEAT;
  16556. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16557. return this._gl.CLAMP_TO_EDGE;
  16558. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16559. return this._gl.MIRRORED_REPEAT;
  16560. }
  16561. return this._gl.REPEAT;
  16562. };
  16563. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16564. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16565. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16566. // Not ready?
  16567. if (!texture) {
  16568. if (this._boundTexturesCache[channel] != null) {
  16569. this._activeChannel = channel;
  16570. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16571. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16572. if (this.webGLVersion > 1) {
  16573. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16574. }
  16575. }
  16576. return false;
  16577. }
  16578. // Video
  16579. if (texture.video) {
  16580. this._activeChannel = channel;
  16581. texture.update();
  16582. }
  16583. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16584. texture.delayLoad();
  16585. return false;
  16586. }
  16587. var internalTexture;
  16588. if (depthStencilTexture) {
  16589. internalTexture = texture.depthStencilTexture;
  16590. }
  16591. else if (texture.isReady()) {
  16592. internalTexture = texture.getInternalTexture();
  16593. }
  16594. else if (texture.isCube) {
  16595. internalTexture = this.emptyCubeTexture;
  16596. }
  16597. else if (texture.is3D) {
  16598. internalTexture = this.emptyTexture3D;
  16599. }
  16600. else {
  16601. internalTexture = this.emptyTexture;
  16602. }
  16603. if (!isPartOfTextureArray) {
  16604. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16605. }
  16606. var needToBind = true;
  16607. if (this._boundTexturesCache[channel] === internalTexture) {
  16608. this._moveBoundTextureOnTop(internalTexture);
  16609. if (!isPartOfTextureArray) {
  16610. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16611. }
  16612. needToBind = false;
  16613. }
  16614. this._activeChannel = channel;
  16615. if (internalTexture && internalTexture.is3D) {
  16616. if (needToBind) {
  16617. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16618. }
  16619. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16620. internalTexture._cachedWrapU = texture.wrapU;
  16621. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16622. }
  16623. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16624. internalTexture._cachedWrapV = texture.wrapV;
  16625. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16626. }
  16627. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16628. internalTexture._cachedWrapR = texture.wrapR;
  16629. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16630. }
  16631. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16632. }
  16633. else if (internalTexture && internalTexture.isCube) {
  16634. if (needToBind) {
  16635. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16636. }
  16637. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16638. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16639. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16640. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16641. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16642. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16643. }
  16644. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16645. }
  16646. else {
  16647. if (needToBind) {
  16648. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16649. }
  16650. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16651. internalTexture._cachedWrapU = texture.wrapU;
  16652. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16653. }
  16654. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16655. internalTexture._cachedWrapV = texture.wrapV;
  16656. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16657. }
  16658. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16659. }
  16660. return true;
  16661. };
  16662. /**
  16663. * Sets an array of texture to the webGL context
  16664. * @param channel defines the channel where the texture array must be set
  16665. * @param uniform defines the associated uniform location
  16666. * @param textures defines the array of textures to bind
  16667. */
  16668. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16669. if (channel < 0 || !uniform) {
  16670. return;
  16671. }
  16672. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16673. this._textureUnits = new Int32Array(textures.length);
  16674. }
  16675. for (var i = 0; i < textures.length; i++) {
  16676. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16677. }
  16678. this._gl.uniform1iv(uniform, this._textureUnits);
  16679. for (var index = 0; index < textures.length; index++) {
  16680. this._setTexture(this._textureUnits[index], textures[index], true);
  16681. }
  16682. };
  16683. /** @hidden */
  16684. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16685. var internalTexture = texture.getInternalTexture();
  16686. if (!internalTexture) {
  16687. return;
  16688. }
  16689. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16690. var value = texture.anisotropicFilteringLevel;
  16691. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16692. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16693. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16694. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16695. }
  16696. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16697. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16698. internalTexture._cachedAnisotropicFilteringLevel = value;
  16699. }
  16700. };
  16701. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16702. this._bindTextureDirectly(target, texture, true, true);
  16703. this._gl.texParameterf(target, parameter, value);
  16704. };
  16705. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16706. if (texture) {
  16707. this._bindTextureDirectly(target, texture, true, true);
  16708. }
  16709. this._gl.texParameteri(target, parameter, value);
  16710. };
  16711. /**
  16712. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16713. * @param x defines the x coordinate of the rectangle where pixels must be read
  16714. * @param y defines the y coordinate of the rectangle where pixels must be read
  16715. * @param width defines the width of the rectangle where pixels must be read
  16716. * @param height defines the height of the rectangle where pixels must be read
  16717. * @returns a Uint8Array containing RGBA colors
  16718. */
  16719. Engine.prototype.readPixels = function (x, y, width, height) {
  16720. var data = new Uint8Array(height * width * 4);
  16721. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16722. return data;
  16723. };
  16724. /**
  16725. * Add an externaly attached data from its key.
  16726. * This method call will fail and return false, if such key already exists.
  16727. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16728. * @param key the unique key that identifies the data
  16729. * @param data the data object to associate to the key for this Engine instance
  16730. * @return true if no such key were already present and the data was added successfully, false otherwise
  16731. */
  16732. Engine.prototype.addExternalData = function (key, data) {
  16733. if (!this._externalData) {
  16734. this._externalData = new BABYLON.StringDictionary();
  16735. }
  16736. return this._externalData.add(key, data);
  16737. };
  16738. /**
  16739. * Get an externaly attached data from its key
  16740. * @param key the unique key that identifies the data
  16741. * @return the associated data, if present (can be null), or undefined if not present
  16742. */
  16743. Engine.prototype.getExternalData = function (key) {
  16744. if (!this._externalData) {
  16745. this._externalData = new BABYLON.StringDictionary();
  16746. }
  16747. return this._externalData.get(key);
  16748. };
  16749. /**
  16750. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16751. * @param key the unique key that identifies the data
  16752. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16753. * @return the associated data, can be null if the factory returned null.
  16754. */
  16755. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16756. if (!this._externalData) {
  16757. this._externalData = new BABYLON.StringDictionary();
  16758. }
  16759. return this._externalData.getOrAddWithFactory(key, factory);
  16760. };
  16761. /**
  16762. * Remove an externaly attached data from the Engine instance
  16763. * @param key the unique key that identifies the data
  16764. * @return true if the data was successfully removed, false if it doesn't exist
  16765. */
  16766. Engine.prototype.removeExternalData = function (key) {
  16767. if (!this._externalData) {
  16768. this._externalData = new BABYLON.StringDictionary();
  16769. }
  16770. return this._externalData.remove(key);
  16771. };
  16772. /**
  16773. * Unbind all vertex attributes from the webGL context
  16774. */
  16775. Engine.prototype.unbindAllAttributes = function () {
  16776. if (this._mustWipeVertexAttributes) {
  16777. this._mustWipeVertexAttributes = false;
  16778. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16779. this._gl.disableVertexAttribArray(i);
  16780. this._vertexAttribArraysEnabled[i] = false;
  16781. this._currentBufferPointers[i].active = false;
  16782. }
  16783. return;
  16784. }
  16785. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16786. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16787. continue;
  16788. }
  16789. this._gl.disableVertexAttribArray(i);
  16790. this._vertexAttribArraysEnabled[i] = false;
  16791. this._currentBufferPointers[i].active = false;
  16792. }
  16793. };
  16794. /**
  16795. * 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
  16796. */
  16797. Engine.prototype.releaseEffects = function () {
  16798. for (var name in this._compiledEffects) {
  16799. this._deleteProgram(this._compiledEffects[name]._program);
  16800. }
  16801. this._compiledEffects = {};
  16802. };
  16803. /**
  16804. * Dispose and release all associated resources
  16805. */
  16806. Engine.prototype.dispose = function () {
  16807. this.hideLoadingUI();
  16808. this.stopRenderLoop();
  16809. // Release postProcesses
  16810. while (this.postProcesses.length) {
  16811. this.postProcesses[0].dispose();
  16812. }
  16813. // Empty texture
  16814. if (this._emptyTexture) {
  16815. this._releaseTexture(this._emptyTexture);
  16816. this._emptyTexture = null;
  16817. }
  16818. if (this._emptyCubeTexture) {
  16819. this._releaseTexture(this._emptyCubeTexture);
  16820. this._emptyCubeTexture = null;
  16821. }
  16822. // Rescale PP
  16823. if (this._rescalePostProcess) {
  16824. this._rescalePostProcess.dispose();
  16825. }
  16826. // Release scenes
  16827. while (this.scenes.length) {
  16828. this.scenes[0].dispose();
  16829. }
  16830. // Release audio engine
  16831. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16832. Engine.audioEngine.dispose();
  16833. }
  16834. // Release effects
  16835. this.releaseEffects();
  16836. // Unbind
  16837. this.unbindAllAttributes();
  16838. this._boundUniforms = [];
  16839. if (this._dummyFramebuffer) {
  16840. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16841. }
  16842. //WebVR
  16843. this.disableVR();
  16844. // Events
  16845. if (BABYLON.Tools.IsWindowObjectExist()) {
  16846. window.removeEventListener("blur", this._onBlur);
  16847. window.removeEventListener("focus", this._onFocus);
  16848. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16849. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16850. if (this._renderingCanvas) {
  16851. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16852. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16853. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16854. if (!this._doNotHandleContextLost) {
  16855. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16856. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16857. }
  16858. }
  16859. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16860. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16861. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16862. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16863. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16864. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16865. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16866. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16867. if (this._onVrDisplayConnect) {
  16868. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16869. if (this._onVrDisplayDisconnect) {
  16870. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16871. }
  16872. if (this._onVrDisplayPresentChange) {
  16873. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16874. }
  16875. this._onVrDisplayConnect = null;
  16876. this._onVrDisplayDisconnect = null;
  16877. }
  16878. }
  16879. // Remove from Instances
  16880. var index = Engine.Instances.indexOf(this);
  16881. if (index >= 0) {
  16882. Engine.Instances.splice(index, 1);
  16883. }
  16884. this._workingCanvas = null;
  16885. this._workingContext = null;
  16886. this._currentBufferPointers = [];
  16887. this._renderingCanvas = null;
  16888. this._currentProgram = null;
  16889. this._bindedRenderFunction = null;
  16890. this.onResizeObservable.clear();
  16891. this.onCanvasBlurObservable.clear();
  16892. this.onCanvasFocusObservable.clear();
  16893. this.onCanvasPointerOutObservable.clear();
  16894. this.onBeginFrameObservable.clear();
  16895. this.onEndFrameObservable.clear();
  16896. BABYLON.Effect.ResetCache();
  16897. // Abort active requests
  16898. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16899. var request = _a[_i];
  16900. request.abort();
  16901. }
  16902. };
  16903. // Loading screen
  16904. /**
  16905. * Display the loading screen
  16906. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16907. */
  16908. Engine.prototype.displayLoadingUI = function () {
  16909. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16910. return;
  16911. }
  16912. var loadingScreen = this.loadingScreen;
  16913. if (loadingScreen) {
  16914. loadingScreen.displayLoadingUI();
  16915. }
  16916. };
  16917. /**
  16918. * Hide the loading screen
  16919. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16920. */
  16921. Engine.prototype.hideLoadingUI = function () {
  16922. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16923. return;
  16924. }
  16925. var loadingScreen = this.loadingScreen;
  16926. if (loadingScreen) {
  16927. loadingScreen.hideLoadingUI();
  16928. }
  16929. };
  16930. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16931. /**
  16932. * Gets the current loading screen object
  16933. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16934. */
  16935. get: function () {
  16936. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16937. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16938. return this._loadingScreen;
  16939. },
  16940. /**
  16941. * Sets the current loading screen object
  16942. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16943. */
  16944. set: function (loadingScreen) {
  16945. this._loadingScreen = loadingScreen;
  16946. },
  16947. enumerable: true,
  16948. configurable: true
  16949. });
  16950. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16951. /**
  16952. * Sets the current loading screen text
  16953. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16954. */
  16955. set: function (text) {
  16956. this.loadingScreen.loadingUIText = text;
  16957. },
  16958. enumerable: true,
  16959. configurable: true
  16960. });
  16961. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16962. /**
  16963. * Sets the current loading screen background color
  16964. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16965. */
  16966. set: function (color) {
  16967. this.loadingScreen.loadingUIBackgroundColor = color;
  16968. },
  16969. enumerable: true,
  16970. configurable: true
  16971. });
  16972. /**
  16973. * Attach a new callback raised when context lost event is fired
  16974. * @param callback defines the callback to call
  16975. */
  16976. Engine.prototype.attachContextLostEvent = function (callback) {
  16977. if (this._renderingCanvas) {
  16978. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16979. }
  16980. };
  16981. /**
  16982. * Attach a new callback raised when context restored event is fired
  16983. * @param callback defines the callback to call
  16984. */
  16985. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16986. if (this._renderingCanvas) {
  16987. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16988. }
  16989. };
  16990. /**
  16991. * Gets the source code of the vertex shader associated with a specific webGL program
  16992. * @param program defines the program to use
  16993. * @returns a string containing the source code of the vertex shader associated with the program
  16994. */
  16995. Engine.prototype.getVertexShaderSource = function (program) {
  16996. var shaders = this._gl.getAttachedShaders(program);
  16997. if (!shaders) {
  16998. return null;
  16999. }
  17000. return this._gl.getShaderSource(shaders[0]);
  17001. };
  17002. /**
  17003. * Gets the source code of the fragment shader associated with a specific webGL program
  17004. * @param program defines the program to use
  17005. * @returns a string containing the source code of the fragment shader associated with the program
  17006. */
  17007. Engine.prototype.getFragmentShaderSource = function (program) {
  17008. var shaders = this._gl.getAttachedShaders(program);
  17009. if (!shaders) {
  17010. return null;
  17011. }
  17012. return this._gl.getShaderSource(shaders[1]);
  17013. };
  17014. /**
  17015. * Get the current error code of the webGL context
  17016. * @returns the error code
  17017. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17018. */
  17019. Engine.prototype.getError = function () {
  17020. return this._gl.getError();
  17021. };
  17022. // FPS
  17023. /**
  17024. * Gets the current framerate
  17025. * @returns a number representing the framerate
  17026. */
  17027. Engine.prototype.getFps = function () {
  17028. return this._fps;
  17029. };
  17030. /**
  17031. * Gets the time spent between current and previous frame
  17032. * @returns a number representing the delta time in ms
  17033. */
  17034. Engine.prototype.getDeltaTime = function () {
  17035. return this._deltaTime;
  17036. };
  17037. Engine.prototype._measureFps = function () {
  17038. this._performanceMonitor.sampleFrame();
  17039. this._fps = this._performanceMonitor.averageFPS;
  17040. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17041. };
  17042. /** @hidden */
  17043. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17044. if (faceIndex === void 0) { faceIndex = -1; }
  17045. if (level === void 0) { level = 0; }
  17046. if (buffer === void 0) { buffer = null; }
  17047. var gl = this._gl;
  17048. if (!this._dummyFramebuffer) {
  17049. var dummy = gl.createFramebuffer();
  17050. if (!dummy) {
  17051. throw new Error("Unable to create dummy framebuffer");
  17052. }
  17053. this._dummyFramebuffer = dummy;
  17054. }
  17055. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17056. if (faceIndex > -1) {
  17057. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17058. }
  17059. else {
  17060. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17061. }
  17062. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17063. switch (readType) {
  17064. case gl.UNSIGNED_BYTE:
  17065. if (!buffer) {
  17066. buffer = new Uint8Array(4 * width * height);
  17067. }
  17068. readType = gl.UNSIGNED_BYTE;
  17069. break;
  17070. default:
  17071. if (!buffer) {
  17072. buffer = new Float32Array(4 * width * height);
  17073. }
  17074. readType = gl.FLOAT;
  17075. break;
  17076. }
  17077. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17078. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17079. return buffer;
  17080. };
  17081. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17082. if (this._webGLVersion > 1) {
  17083. return this._caps.colorBufferFloat;
  17084. }
  17085. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17086. };
  17087. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17088. if (this._webGLVersion > 1) {
  17089. return this._caps.colorBufferFloat;
  17090. }
  17091. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17092. };
  17093. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17094. Engine.prototype._canRenderToFramebuffer = function (type) {
  17095. var gl = this._gl;
  17096. //clear existing errors
  17097. while (gl.getError() !== gl.NO_ERROR) { }
  17098. var successful = true;
  17099. var texture = gl.createTexture();
  17100. gl.bindTexture(gl.TEXTURE_2D, texture);
  17101. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17102. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17103. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17104. var fb = gl.createFramebuffer();
  17105. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17106. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17107. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17108. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17109. successful = successful && (gl.getError() === gl.NO_ERROR);
  17110. //try render by clearing frame buffer's color buffer
  17111. if (successful) {
  17112. gl.clear(gl.COLOR_BUFFER_BIT);
  17113. successful = successful && (gl.getError() === gl.NO_ERROR);
  17114. }
  17115. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17116. if (successful) {
  17117. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17118. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17119. var readFormat = gl.RGBA;
  17120. var readType = gl.UNSIGNED_BYTE;
  17121. var buffer = new Uint8Array(4);
  17122. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17123. successful = successful && (gl.getError() === gl.NO_ERROR);
  17124. }
  17125. //clean up
  17126. gl.deleteTexture(texture);
  17127. gl.deleteFramebuffer(fb);
  17128. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17129. //clear accumulated errors
  17130. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17131. return successful;
  17132. };
  17133. /** @hidden */
  17134. Engine.prototype._getWebGLTextureType = function (type) {
  17135. if (this._webGLVersion === 1) {
  17136. switch (type) {
  17137. case Engine.TEXTURETYPE_FLOAT:
  17138. return this._gl.FLOAT;
  17139. case Engine.TEXTURETYPE_HALF_FLOAT:
  17140. return this._gl.HALF_FLOAT_OES;
  17141. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17142. return this._gl.UNSIGNED_BYTE;
  17143. }
  17144. return this._gl.UNSIGNED_BYTE;
  17145. }
  17146. switch (type) {
  17147. case Engine.TEXTURETYPE_BYTE:
  17148. return this._gl.BYTE;
  17149. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17150. return this._gl.UNSIGNED_BYTE;
  17151. case Engine.TEXTURETYPE_SHORT:
  17152. return this._gl.SHORT;
  17153. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17154. return this._gl.UNSIGNED_SHORT;
  17155. case Engine.TEXTURETYPE_INT:
  17156. return this._gl.INT;
  17157. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17158. return this._gl.UNSIGNED_INT;
  17159. case Engine.TEXTURETYPE_FLOAT:
  17160. return this._gl.FLOAT;
  17161. case Engine.TEXTURETYPE_HALF_FLOAT:
  17162. return this._gl.HALF_FLOAT;
  17163. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17164. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17165. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17166. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17167. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17168. return this._gl.UNSIGNED_SHORT_5_6_5;
  17169. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17170. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17171. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17172. return this._gl.UNSIGNED_INT_24_8;
  17173. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17174. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17175. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17176. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17177. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17178. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17179. }
  17180. return this._gl.UNSIGNED_BYTE;
  17181. };
  17182. ;
  17183. Engine.prototype._getInternalFormat = function (format) {
  17184. var internalFormat = this._gl.RGBA;
  17185. switch (format) {
  17186. case Engine.TEXTUREFORMAT_ALPHA:
  17187. internalFormat = this._gl.ALPHA;
  17188. break;
  17189. case Engine.TEXTUREFORMAT_LUMINANCE:
  17190. internalFormat = this._gl.LUMINANCE;
  17191. break;
  17192. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17193. internalFormat = this._gl.LUMINANCE_ALPHA;
  17194. break;
  17195. case Engine.TEXTUREFORMAT_RED:
  17196. internalFormat = this._gl.RED;
  17197. break;
  17198. case Engine.TEXTUREFORMAT_RG:
  17199. internalFormat = this._gl.RG;
  17200. break;
  17201. case Engine.TEXTUREFORMAT_RGB:
  17202. internalFormat = this._gl.RGB;
  17203. break;
  17204. case Engine.TEXTUREFORMAT_RGBA:
  17205. internalFormat = this._gl.RGBA;
  17206. break;
  17207. }
  17208. if (this._webGLVersion > 1) {
  17209. switch (format) {
  17210. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17211. internalFormat = this._gl.RED_INTEGER;
  17212. break;
  17213. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17214. internalFormat = this._gl.RG_INTEGER;
  17215. break;
  17216. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17217. internalFormat = this._gl.RGB_INTEGER;
  17218. break;
  17219. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17220. internalFormat = this._gl.RGBA_INTEGER;
  17221. break;
  17222. }
  17223. }
  17224. return internalFormat;
  17225. };
  17226. /** @hidden */
  17227. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17228. if (this._webGLVersion === 1) {
  17229. if (format !== undefined) {
  17230. switch (format) {
  17231. case Engine.TEXTUREFORMAT_ALPHA:
  17232. return this._gl.ALPHA;
  17233. case Engine.TEXTUREFORMAT_LUMINANCE:
  17234. return this._gl.LUMINANCE;
  17235. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17236. return this._gl.LUMINANCE_ALPHA;
  17237. }
  17238. }
  17239. return this._gl.RGBA;
  17240. }
  17241. switch (type) {
  17242. case Engine.TEXTURETYPE_BYTE:
  17243. switch (format) {
  17244. case Engine.TEXTUREFORMAT_RED:
  17245. return this._gl.R8_SNORM;
  17246. case Engine.TEXTUREFORMAT_RG:
  17247. return this._gl.RG8_SNORM;
  17248. case Engine.TEXTUREFORMAT_RGB:
  17249. return this._gl.RGB8_SNORM;
  17250. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17251. return this._gl.R8I;
  17252. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17253. return this._gl.RG8I;
  17254. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17255. return this._gl.RGB8I;
  17256. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17257. return this._gl.RGBA8I;
  17258. default:
  17259. return this._gl.RGBA8_SNORM;
  17260. }
  17261. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17262. switch (format) {
  17263. case Engine.TEXTUREFORMAT_RED:
  17264. return this._gl.R8;
  17265. case Engine.TEXTUREFORMAT_RG:
  17266. return this._gl.RG8;
  17267. case Engine.TEXTUREFORMAT_RGB:
  17268. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17269. case Engine.TEXTUREFORMAT_RGBA:
  17270. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17271. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17272. return this._gl.R8UI;
  17273. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17274. return this._gl.RG8UI;
  17275. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17276. return this._gl.RGB8UI;
  17277. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17278. return this._gl.RGBA8UI;
  17279. default:
  17280. return this._gl.RGBA8;
  17281. }
  17282. case Engine.TEXTURETYPE_SHORT:
  17283. switch (format) {
  17284. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17285. return this._gl.R16I;
  17286. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17287. return this._gl.RG16I;
  17288. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17289. return this._gl.RGB16I;
  17290. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17291. return this._gl.RGBA16I;
  17292. default:
  17293. return this._gl.RGBA16I;
  17294. }
  17295. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17296. switch (format) {
  17297. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17298. return this._gl.R16UI;
  17299. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17300. return this._gl.RG16UI;
  17301. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17302. return this._gl.RGB16UI;
  17303. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17304. return this._gl.RGBA16UI;
  17305. default:
  17306. return this._gl.RGBA16UI;
  17307. }
  17308. case Engine.TEXTURETYPE_INT:
  17309. switch (format) {
  17310. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17311. return this._gl.R32I;
  17312. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17313. return this._gl.RG32I;
  17314. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17315. return this._gl.RGB32I;
  17316. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17317. return this._gl.RGBA32I;
  17318. default:
  17319. return this._gl.RGBA32I;
  17320. }
  17321. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17322. switch (format) {
  17323. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17324. return this._gl.R32UI;
  17325. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17326. return this._gl.RG32UI;
  17327. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17328. return this._gl.RGB32UI;
  17329. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17330. return this._gl.RGBA32UI;
  17331. default:
  17332. return this._gl.RGBA32UI;
  17333. }
  17334. case Engine.TEXTURETYPE_FLOAT:
  17335. switch (format) {
  17336. case Engine.TEXTUREFORMAT_RED:
  17337. return this._gl.R32F; // By default. Other possibility is R16F.
  17338. case Engine.TEXTUREFORMAT_RG:
  17339. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17340. case Engine.TEXTUREFORMAT_RGB:
  17341. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17342. case Engine.TEXTUREFORMAT_RGBA:
  17343. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17344. default:
  17345. return this._gl.RGBA32F;
  17346. }
  17347. case Engine.TEXTURETYPE_HALF_FLOAT:
  17348. switch (format) {
  17349. case Engine.TEXTUREFORMAT_RED:
  17350. return this._gl.R16F;
  17351. case Engine.TEXTUREFORMAT_RG:
  17352. return this._gl.RG16F;
  17353. case Engine.TEXTUREFORMAT_RGB:
  17354. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17355. case Engine.TEXTUREFORMAT_RGBA:
  17356. return this._gl.RGBA16F;
  17357. default:
  17358. return this._gl.RGBA16F;
  17359. }
  17360. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17361. return this._gl.RGB565;
  17362. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17363. return this._gl.R11F_G11F_B10F;
  17364. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17365. return this._gl.RGB9_E5;
  17366. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17367. return this._gl.RGBA4;
  17368. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17369. return this._gl.RGB5_A1;
  17370. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17371. switch (format) {
  17372. case Engine.TEXTUREFORMAT_RGBA:
  17373. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17374. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17375. return this._gl.RGB10_A2UI;
  17376. default:
  17377. return this._gl.RGB10_A2;
  17378. }
  17379. }
  17380. return this._gl.RGBA8;
  17381. };
  17382. ;
  17383. /** @hidden */
  17384. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17385. if (type === Engine.TEXTURETYPE_FLOAT) {
  17386. return this._gl.RGBA32F;
  17387. }
  17388. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17389. return this._gl.RGBA16F;
  17390. }
  17391. return this._gl.RGBA8;
  17392. };
  17393. ;
  17394. /** @hidden */
  17395. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17396. var _this = this;
  17397. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17398. this._activeRequests.push(request);
  17399. request.onCompleteObservable.add(function (request) {
  17400. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17401. });
  17402. return request;
  17403. };
  17404. /** @hidden */
  17405. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17406. var _this = this;
  17407. return new Promise(function (resolve, reject) {
  17408. _this._loadFile(url, function (data) {
  17409. resolve(data);
  17410. }, undefined, database, useArrayBuffer, function (request, exception) {
  17411. reject(exception);
  17412. });
  17413. });
  17414. };
  17415. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17416. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17417. var onload = function (data) {
  17418. loadedFiles[index] = data;
  17419. loadedFiles._internalCount++;
  17420. if (loadedFiles._internalCount === 6) {
  17421. onfinish(loadedFiles);
  17422. }
  17423. };
  17424. var onerror = function (request, exception) {
  17425. if (onErrorCallBack && request) {
  17426. onErrorCallBack(request.status + " " + request.statusText, exception);
  17427. }
  17428. };
  17429. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17430. };
  17431. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17432. if (onError === void 0) { onError = null; }
  17433. var loadedFiles = [];
  17434. loadedFiles._internalCount = 0;
  17435. for (var index = 0; index < 6; index++) {
  17436. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17437. }
  17438. };
  17439. // Statics
  17440. /**
  17441. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17442. * @returns true if the engine can be created
  17443. * @ignorenaming
  17444. */
  17445. Engine.isSupported = function () {
  17446. try {
  17447. var tempcanvas = document.createElement("canvas");
  17448. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17449. return gl != null && !!window.WebGLRenderingContext;
  17450. }
  17451. catch (e) {
  17452. return false;
  17453. }
  17454. };
  17455. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17456. Engine.ExceptionList = [
  17457. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17458. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17459. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17460. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17461. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17462. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17463. ];
  17464. /** Gets the list of created engines */
  17465. Engine.Instances = new Array();
  17466. /**
  17467. * Hidden
  17468. */
  17469. Engine._TextureLoaders = [];
  17470. // Const statics
  17471. /** Defines that alpha blending is disabled */
  17472. Engine.ALPHA_DISABLE = 0;
  17473. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17474. Engine.ALPHA_ADD = 1;
  17475. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17476. Engine.ALPHA_COMBINE = 2;
  17477. /** Defines that alpha blending to DEST - SRC * DEST */
  17478. Engine.ALPHA_SUBTRACT = 3;
  17479. /** Defines that alpha blending to SRC * DEST */
  17480. Engine.ALPHA_MULTIPLY = 4;
  17481. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17482. Engine.ALPHA_MAXIMIZED = 5;
  17483. /** Defines that alpha blending to SRC + DEST */
  17484. Engine.ALPHA_ONEONE = 6;
  17485. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17486. Engine.ALPHA_PREMULTIPLIED = 7;
  17487. /**
  17488. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17489. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17490. */
  17491. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17492. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17493. Engine.ALPHA_INTERPOLATE = 9;
  17494. /**
  17495. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17496. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17497. */
  17498. Engine.ALPHA_SCREENMODE = 10;
  17499. /** Defines that the ressource is not delayed*/
  17500. Engine.DELAYLOADSTATE_NONE = 0;
  17501. /** Defines that the ressource was successfully delay loaded */
  17502. Engine.DELAYLOADSTATE_LOADED = 1;
  17503. /** Defines that the ressource is currently delay loading */
  17504. Engine.DELAYLOADSTATE_LOADING = 2;
  17505. /** Defines that the ressource is delayed and has not started loading */
  17506. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17507. // Depht or Stencil test Constants.
  17508. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17509. Engine.NEVER = 0x0200;
  17510. /** 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 */
  17511. Engine.ALWAYS = 0x0207;
  17512. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17513. Engine.LESS = 0x0201;
  17514. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17515. Engine.EQUAL = 0x0202;
  17516. /** 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 */
  17517. Engine.LEQUAL = 0x0203;
  17518. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17519. Engine.GREATER = 0x0204;
  17520. /** 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 */
  17521. Engine.GEQUAL = 0x0206;
  17522. /** 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 */
  17523. Engine.NOTEQUAL = 0x0205;
  17524. // Stencil Actions Constants.
  17525. /** Passed to stencilOperation to specify that stencil value must be kept */
  17526. Engine.KEEP = 0x1E00;
  17527. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17528. Engine.REPLACE = 0x1E01;
  17529. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17530. Engine.INCR = 0x1E02;
  17531. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17532. Engine.DECR = 0x1E03;
  17533. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17534. Engine.INVERT = 0x150A;
  17535. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17536. Engine.INCR_WRAP = 0x8507;
  17537. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17538. Engine.DECR_WRAP = 0x8508;
  17539. /** Texture is not repeating outside of 0..1 UVs */
  17540. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17541. /** Texture is repeating outside of 0..1 UVs */
  17542. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17543. /** Texture is repeating and mirrored */
  17544. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17545. /** ALPHA */
  17546. Engine.TEXTUREFORMAT_ALPHA = 0;
  17547. /** LUMINANCE */
  17548. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17549. /** LUMINANCE_ALPHA */
  17550. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17551. /** RGB */
  17552. Engine.TEXTUREFORMAT_RGB = 4;
  17553. /** RGBA */
  17554. Engine.TEXTUREFORMAT_RGBA = 5;
  17555. /** RED */
  17556. Engine.TEXTUREFORMAT_RED = 6;
  17557. /** RED (2nd reference) */
  17558. Engine.TEXTUREFORMAT_R = 6;
  17559. /** RG */
  17560. Engine.TEXTUREFORMAT_RG = 7;
  17561. /** RED_INTEGER */
  17562. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17563. /** RED_INTEGER (2nd reference) */
  17564. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17565. /** RG_INTEGER */
  17566. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17567. /** RGB_INTEGER */
  17568. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17569. /** RGBA_INTEGER */
  17570. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17571. /** UNSIGNED_BYTE */
  17572. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17573. /** UNSIGNED_BYTE (2nd reference) */
  17574. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17575. /** FLOAT */
  17576. Engine.TEXTURETYPE_FLOAT = 1;
  17577. /** HALF_FLOAT */
  17578. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17579. /** BYTE */
  17580. Engine.TEXTURETYPE_BYTE = 3;
  17581. /** SHORT */
  17582. Engine.TEXTURETYPE_SHORT = 4;
  17583. /** UNSIGNED_SHORT */
  17584. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17585. /** INT */
  17586. Engine.TEXTURETYPE_INT = 6;
  17587. /** UNSIGNED_INT */
  17588. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17589. /** UNSIGNED_SHORT_4_4_4_4 */
  17590. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17591. /** UNSIGNED_SHORT_5_5_5_1 */
  17592. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17593. /** UNSIGNED_SHORT_5_6_5 */
  17594. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17595. /** UNSIGNED_INT_2_10_10_10_REV */
  17596. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17597. /** UNSIGNED_INT_24_8 */
  17598. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17599. /** UNSIGNED_INT_10F_11F_11F_REV */
  17600. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17601. /** UNSIGNED_INT_5_9_9_9_REV */
  17602. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17603. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17604. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17605. /** nearest is mag = nearest and min = nearest and mip = linear */
  17606. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17607. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17608. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17609. /** Trilinear is mag = linear and min = linear and mip = linear */
  17610. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17611. /** nearest is mag = nearest and min = nearest and mip = linear */
  17612. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17613. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17614. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17615. /** Trilinear is mag = linear and min = linear and mip = linear */
  17616. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17617. /** mag = nearest and min = nearest and mip = nearest */
  17618. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17619. /** mag = nearest and min = linear and mip = nearest */
  17620. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17621. /** mag = nearest and min = linear and mip = linear */
  17622. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17623. /** mag = nearest and min = linear and mip = none */
  17624. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17625. /** mag = nearest and min = nearest and mip = none */
  17626. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17627. /** mag = linear and min = nearest and mip = nearest */
  17628. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17629. /** mag = linear and min = nearest and mip = linear */
  17630. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17631. /** mag = linear and min = linear and mip = none */
  17632. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17633. /** mag = linear and min = nearest and mip = none */
  17634. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17635. /** Explicit coordinates mode */
  17636. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17637. /** Spherical coordinates mode */
  17638. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17639. /** Planar coordinates mode */
  17640. Engine.TEXTURE_PLANAR_MODE = 2;
  17641. /** Cubic coordinates mode */
  17642. Engine.TEXTURE_CUBIC_MODE = 3;
  17643. /** Projection coordinates mode */
  17644. Engine.TEXTURE_PROJECTION_MODE = 4;
  17645. /** Skybox coordinates mode */
  17646. Engine.TEXTURE_SKYBOX_MODE = 5;
  17647. /** Inverse Cubic coordinates mode */
  17648. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17649. /** Equirectangular coordinates mode */
  17650. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17651. /** Equirectangular Fixed coordinates mode */
  17652. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17653. /** Equirectangular Fixed Mirrored coordinates mode */
  17654. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17655. // Texture rescaling mode
  17656. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17657. Engine.SCALEMODE_FLOOR = 1;
  17658. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17659. Engine.SCALEMODE_NEAREST = 2;
  17660. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17661. Engine.SCALEMODE_CEILING = 3;
  17662. // Updatable statics so stick with vars here
  17663. /**
  17664. * Gets or sets the epsilon value used by collision engine
  17665. */
  17666. Engine.CollisionsEpsilon = 0.001;
  17667. /**
  17668. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17669. */
  17670. Engine.CodeRepository = "src/";
  17671. /**
  17672. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17673. */
  17674. Engine.ShadersRepository = "src/Shaders/";
  17675. return Engine;
  17676. }());
  17677. BABYLON.Engine = Engine;
  17678. })(BABYLON || (BABYLON = {}));
  17679. //# sourceMappingURL=babylon.engine.js.map
  17680. var BABYLON;
  17681. (function (BABYLON) {
  17682. /**
  17683. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17684. */
  17685. var Node = /** @class */ (function () {
  17686. /**
  17687. * Creates a new Node
  17688. * @param {string} name - the name and id to be given to this node
  17689. * @param {BABYLON.Scene} the scene this node will be added to
  17690. */
  17691. function Node(name, scene) {
  17692. if (scene === void 0) { scene = null; }
  17693. /**
  17694. * Gets or sets a string used to store user defined state for the node
  17695. */
  17696. this.state = "";
  17697. /**
  17698. * Gets or sets an object used to store user defined information for the node
  17699. */
  17700. this.metadata = null;
  17701. /**
  17702. * Gets or sets a boolean used to define if the node must be serialized
  17703. */
  17704. this.doNotSerialize = false;
  17705. /** @hidden */
  17706. this._isDisposed = false;
  17707. /**
  17708. * Gets a list of Animations associated with the node
  17709. */
  17710. this.animations = new Array();
  17711. this._ranges = {};
  17712. this._isEnabled = true;
  17713. this._isParentEnabled = true;
  17714. this._isReady = true;
  17715. /** @hidden */
  17716. this._currentRenderId = -1;
  17717. this._parentRenderId = -1;
  17718. this._childRenderId = -1;
  17719. /** @hidden */
  17720. this._worldMatrix = BABYLON.Matrix.Identity();
  17721. /** @hidden */
  17722. this._worldMatrixDeterminant = 0;
  17723. this._animationPropertiesOverride = null;
  17724. /**
  17725. * An event triggered when the mesh is disposed
  17726. */
  17727. this.onDisposeObservable = new BABYLON.Observable();
  17728. // Behaviors
  17729. this._behaviors = new Array();
  17730. this.name = name;
  17731. this.id = name;
  17732. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17733. this.uniqueId = this._scene.getUniqueId();
  17734. this._initCache();
  17735. this._scene.rootNodes.push(this);
  17736. }
  17737. /**
  17738. * Add a new node constructor
  17739. * @param type defines the type name of the node to construct
  17740. * @param constructorFunc defines the constructor function
  17741. */
  17742. Node.AddNodeConstructor = function (type, constructorFunc) {
  17743. this._NodeConstructors[type] = constructorFunc;
  17744. };
  17745. /**
  17746. * Returns a node constructor based on type name
  17747. * @param type defines the type name
  17748. * @param name defines the new node name
  17749. * @param scene defines the hosting scene
  17750. * @param options defines optional options to transmit to constructors
  17751. * @returns the new constructor or null
  17752. */
  17753. Node.Construct = function (type, name, scene, options) {
  17754. var constructorFunc = this._NodeConstructors[type];
  17755. if (!constructorFunc) {
  17756. return null;
  17757. }
  17758. return constructorFunc(name, scene, options);
  17759. };
  17760. /**
  17761. * Gets a boolean indicating if the node has been disposed
  17762. * @returns true if the node was disposed
  17763. */
  17764. Node.prototype.isDisposed = function () {
  17765. return this._isDisposed;
  17766. };
  17767. Object.defineProperty(Node.prototype, "parent", {
  17768. get: function () {
  17769. return this._parentNode;
  17770. },
  17771. /**
  17772. * Gets or sets the parent of the node
  17773. */
  17774. set: function (parent) {
  17775. if (this._parentNode === parent) {
  17776. return;
  17777. }
  17778. var previousParentNode = this._parentNode;
  17779. // Remove self from list of children of parent
  17780. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17781. var index = this._parentNode._children.indexOf(this);
  17782. if (index !== -1) {
  17783. this._parentNode._children.splice(index, 1);
  17784. }
  17785. if (!parent) {
  17786. // Need to add this node to the rootNodes
  17787. this._scene.rootNodes.push(this);
  17788. }
  17789. }
  17790. // Store new parent
  17791. this._parentNode = parent;
  17792. // Add as child to new parent
  17793. if (this._parentNode) {
  17794. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17795. this._parentNode._children = new Array();
  17796. }
  17797. this._parentNode._children.push(this);
  17798. if (!previousParentNode) {
  17799. // Need to remove from rootNodes
  17800. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17801. if (rootNodeIndex > -1) {
  17802. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17803. }
  17804. }
  17805. }
  17806. // Enabled state
  17807. this._syncParentEnabledState();
  17808. },
  17809. enumerable: true,
  17810. configurable: true
  17811. });
  17812. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17813. /**
  17814. * Gets or sets the animation properties override
  17815. */
  17816. get: function () {
  17817. if (!this._animationPropertiesOverride) {
  17818. return this._scene.animationPropertiesOverride;
  17819. }
  17820. return this._animationPropertiesOverride;
  17821. },
  17822. set: function (value) {
  17823. this._animationPropertiesOverride = value;
  17824. },
  17825. enumerable: true,
  17826. configurable: true
  17827. });
  17828. /**
  17829. * Gets a string idenfifying the name of the class
  17830. * @returns "Node" string
  17831. */
  17832. Node.prototype.getClassName = function () {
  17833. return "Node";
  17834. };
  17835. Object.defineProperty(Node.prototype, "onDispose", {
  17836. /**
  17837. * Sets a callback that will be raised when the node will be disposed
  17838. */
  17839. set: function (callback) {
  17840. if (this._onDisposeObserver) {
  17841. this.onDisposeObservable.remove(this._onDisposeObserver);
  17842. }
  17843. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17844. },
  17845. enumerable: true,
  17846. configurable: true
  17847. });
  17848. /**
  17849. * Gets the scene of the node
  17850. * @returns a {BABYLON.Scene}
  17851. */
  17852. Node.prototype.getScene = function () {
  17853. return this._scene;
  17854. };
  17855. /**
  17856. * Gets the engine of the node
  17857. * @returns a {BABYLON.Engine}
  17858. */
  17859. Node.prototype.getEngine = function () {
  17860. return this._scene.getEngine();
  17861. };
  17862. /**
  17863. * Attach a behavior to the node
  17864. * @see http://doc.babylonjs.com/features/behaviour
  17865. * @param behavior defines the behavior to attach
  17866. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  17867. * @returns the current Node
  17868. */
  17869. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  17870. var _this = this;
  17871. if (attachImmediately === void 0) { attachImmediately = false; }
  17872. var index = this._behaviors.indexOf(behavior);
  17873. if (index !== -1) {
  17874. return this;
  17875. }
  17876. behavior.init();
  17877. if (this._scene.isLoading && !attachImmediately) {
  17878. // We defer the attach when the scene will be loaded
  17879. this._scene.onDataLoadedObservable.addOnce(function () {
  17880. behavior.attach(_this);
  17881. });
  17882. }
  17883. else {
  17884. behavior.attach(this);
  17885. }
  17886. this._behaviors.push(behavior);
  17887. return this;
  17888. };
  17889. /**
  17890. * Remove an attached behavior
  17891. * @see http://doc.babylonjs.com/features/behaviour
  17892. * @param behavior defines the behavior to attach
  17893. * @returns the current Node
  17894. */
  17895. Node.prototype.removeBehavior = function (behavior) {
  17896. var index = this._behaviors.indexOf(behavior);
  17897. if (index === -1) {
  17898. return this;
  17899. }
  17900. this._behaviors[index].detach();
  17901. this._behaviors.splice(index, 1);
  17902. return this;
  17903. };
  17904. Object.defineProperty(Node.prototype, "behaviors", {
  17905. /**
  17906. * Gets the list of attached behaviors
  17907. * @see http://doc.babylonjs.com/features/behaviour
  17908. */
  17909. get: function () {
  17910. return this._behaviors;
  17911. },
  17912. enumerable: true,
  17913. configurable: true
  17914. });
  17915. /**
  17916. * Gets an attached behavior by name
  17917. * @param name defines the name of the behavior to look for
  17918. * @see http://doc.babylonjs.com/features/behaviour
  17919. * @returns null if behavior was not found else the requested behavior
  17920. */
  17921. Node.prototype.getBehaviorByName = function (name) {
  17922. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17923. var behavior = _a[_i];
  17924. if (behavior.name === name) {
  17925. return behavior;
  17926. }
  17927. }
  17928. return null;
  17929. };
  17930. /**
  17931. * Returns the latest update of the World matrix
  17932. * @returns a Matrix
  17933. */
  17934. Node.prototype.getWorldMatrix = function () {
  17935. if (this._currentRenderId !== this._scene.getRenderId()) {
  17936. this.computeWorldMatrix();
  17937. }
  17938. return this._worldMatrix;
  17939. };
  17940. /** @hidden */
  17941. Node.prototype._getWorldMatrixDeterminant = function () {
  17942. return this._worldMatrixDeterminant;
  17943. };
  17944. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17945. /**
  17946. * Returns directly the latest state of the mesh World matrix.
  17947. * A Matrix is returned.
  17948. */
  17949. get: function () {
  17950. return this._worldMatrix;
  17951. },
  17952. enumerable: true,
  17953. configurable: true
  17954. });
  17955. // override it in derived class if you add new variables to the cache
  17956. // and call the parent class method
  17957. /** @hidden */
  17958. Node.prototype._initCache = function () {
  17959. this._cache = {};
  17960. this._cache.parent = undefined;
  17961. };
  17962. /** @hidden */
  17963. Node.prototype.updateCache = function (force) {
  17964. if (!force && this.isSynchronized())
  17965. return;
  17966. this._cache.parent = this.parent;
  17967. this._updateCache();
  17968. };
  17969. // override it in derived class if you add new variables to the cache
  17970. // and call the parent class method if !ignoreParentClass
  17971. /** @hidden */
  17972. Node.prototype._updateCache = function (ignoreParentClass) {
  17973. };
  17974. // override it in derived class if you add new variables to the cache
  17975. /** @hidden */
  17976. Node.prototype._isSynchronized = function () {
  17977. return true;
  17978. };
  17979. /** @hidden */
  17980. Node.prototype._markSyncedWithParent = function () {
  17981. if (this._parentNode) {
  17982. this._parentRenderId = this._parentNode._childRenderId;
  17983. }
  17984. };
  17985. /** @hidden */
  17986. Node.prototype.isSynchronizedWithParent = function () {
  17987. if (!this._parentNode) {
  17988. return true;
  17989. }
  17990. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17991. return false;
  17992. }
  17993. return this._parentNode.isSynchronized();
  17994. };
  17995. /** @hidden */
  17996. Node.prototype.isSynchronized = function () {
  17997. if (this._cache.parent != this._parentNode) {
  17998. this._cache.parent = this._parentNode;
  17999. return false;
  18000. }
  18001. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18002. return false;
  18003. }
  18004. return this._isSynchronized();
  18005. };
  18006. /**
  18007. * Is this node ready to be used/rendered
  18008. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18009. * @return true if the node is ready
  18010. */
  18011. Node.prototype.isReady = function (completeCheck) {
  18012. if (completeCheck === void 0) { completeCheck = false; }
  18013. return this._isReady;
  18014. };
  18015. /**
  18016. * Is this node enabled?
  18017. * 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
  18018. * @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
  18019. * @return whether this node (and its parent) is enabled
  18020. */
  18021. Node.prototype.isEnabled = function (checkAncestors) {
  18022. if (checkAncestors === void 0) { checkAncestors = true; }
  18023. if (checkAncestors === false) {
  18024. return this._isEnabled;
  18025. }
  18026. if (!this._isEnabled) {
  18027. return false;
  18028. }
  18029. return this._isParentEnabled;
  18030. };
  18031. /** @hidden */
  18032. Node.prototype._syncParentEnabledState = function () {
  18033. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18034. if (this._children) {
  18035. this._children.forEach(function (c) {
  18036. c._syncParentEnabledState(); // Force children to update accordingly
  18037. });
  18038. }
  18039. };
  18040. /**
  18041. * Set the enabled state of this node
  18042. * @param value defines the new enabled state
  18043. */
  18044. Node.prototype.setEnabled = function (value) {
  18045. this._isEnabled = value;
  18046. this._syncParentEnabledState();
  18047. };
  18048. /**
  18049. * Is this node a descendant of the given node?
  18050. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18051. * @param ancestor defines the parent node to inspect
  18052. * @returns a boolean indicating if this node is a descendant of the given node
  18053. */
  18054. Node.prototype.isDescendantOf = function (ancestor) {
  18055. if (this.parent) {
  18056. if (this.parent === ancestor) {
  18057. return true;
  18058. }
  18059. return this.parent.isDescendantOf(ancestor);
  18060. }
  18061. return false;
  18062. };
  18063. /** @hidden */
  18064. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18065. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18066. if (!this._children) {
  18067. return;
  18068. }
  18069. for (var index = 0; index < this._children.length; index++) {
  18070. var item = this._children[index];
  18071. if (!predicate || predicate(item)) {
  18072. results.push(item);
  18073. }
  18074. if (!directDescendantsOnly) {
  18075. item._getDescendants(results, false, predicate);
  18076. }
  18077. }
  18078. };
  18079. /**
  18080. * Will return all nodes that have this node as ascendant
  18081. * @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
  18082. * @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
  18083. * @return all children nodes of all types
  18084. */
  18085. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18086. var results = new Array();
  18087. this._getDescendants(results, directDescendantsOnly, predicate);
  18088. return results;
  18089. };
  18090. /**
  18091. * Get all child-meshes of this node
  18092. * @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
  18093. * @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
  18094. * @returns an array of {BABYLON.AbstractMesh}
  18095. */
  18096. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18097. var results = [];
  18098. this._getDescendants(results, directDescendantsOnly, function (node) {
  18099. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18100. });
  18101. return results;
  18102. };
  18103. /**
  18104. * Get all child-transformNodes of this node
  18105. * @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
  18106. * @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
  18107. * @returns an array of {BABYLON.TransformNode}
  18108. */
  18109. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18110. var results = [];
  18111. this._getDescendants(results, directDescendantsOnly, function (node) {
  18112. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18113. });
  18114. return results;
  18115. };
  18116. /**
  18117. * Get all direct children of this node
  18118. * @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
  18119. * @returns an array of {BABYLON.Node}
  18120. */
  18121. Node.prototype.getChildren = function (predicate) {
  18122. return this.getDescendants(true, predicate);
  18123. };
  18124. /** @hidden */
  18125. Node.prototype._setReady = function (state) {
  18126. if (state === this._isReady) {
  18127. return;
  18128. }
  18129. if (!state) {
  18130. this._isReady = false;
  18131. return;
  18132. }
  18133. if (this.onReady) {
  18134. this.onReady(this);
  18135. }
  18136. this._isReady = true;
  18137. };
  18138. /**
  18139. * Get an animation by name
  18140. * @param name defines the name of the animation to look for
  18141. * @returns null if not found else the requested animation
  18142. */
  18143. Node.prototype.getAnimationByName = function (name) {
  18144. for (var i = 0; i < this.animations.length; i++) {
  18145. var animation = this.animations[i];
  18146. if (animation.name === name) {
  18147. return animation;
  18148. }
  18149. }
  18150. return null;
  18151. };
  18152. /**
  18153. * Creates an animation range for this node
  18154. * @param name defines the name of the range
  18155. * @param from defines the starting key
  18156. * @param to defines the end key
  18157. */
  18158. Node.prototype.createAnimationRange = function (name, from, to) {
  18159. // check name not already in use
  18160. if (!this._ranges[name]) {
  18161. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18162. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18163. if (this.animations[i]) {
  18164. this.animations[i].createRange(name, from, to);
  18165. }
  18166. }
  18167. }
  18168. };
  18169. /**
  18170. * Delete a specific animation range
  18171. * @param name defines the name of the range to delete
  18172. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18173. */
  18174. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18175. if (deleteFrames === void 0) { deleteFrames = true; }
  18176. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18177. if (this.animations[i]) {
  18178. this.animations[i].deleteRange(name, deleteFrames);
  18179. }
  18180. }
  18181. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18182. };
  18183. /**
  18184. * Get an animation range by name
  18185. * @param name defines the name of the animation range to look for
  18186. * @returns null if not found else the requested animation range
  18187. */
  18188. Node.prototype.getAnimationRange = function (name) {
  18189. return this._ranges[name];
  18190. };
  18191. /**
  18192. * Will start the animation sequence
  18193. * @param name defines the range frames for animation sequence
  18194. * @param loop defines if the animation should loop (false by default)
  18195. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18196. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18197. * @returns the object created for this animation. If range does not exist, it will return null
  18198. */
  18199. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18200. var range = this.getAnimationRange(name);
  18201. if (!range) {
  18202. return null;
  18203. }
  18204. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18205. };
  18206. /**
  18207. * Serialize animation ranges into a JSON compatible object
  18208. * @returns serialization object
  18209. */
  18210. Node.prototype.serializeAnimationRanges = function () {
  18211. var serializationRanges = [];
  18212. for (var name in this._ranges) {
  18213. var localRange = this._ranges[name];
  18214. if (!localRange) {
  18215. continue;
  18216. }
  18217. var range = {};
  18218. range.name = name;
  18219. range.from = localRange.from;
  18220. range.to = localRange.to;
  18221. serializationRanges.push(range);
  18222. }
  18223. return serializationRanges;
  18224. };
  18225. /**
  18226. * Computes the world matrix of the node
  18227. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18228. * @returns the world matrix
  18229. */
  18230. Node.prototype.computeWorldMatrix = function (force) {
  18231. if (!this._worldMatrix) {
  18232. this._worldMatrix = BABYLON.Matrix.Identity();
  18233. }
  18234. return this._worldMatrix;
  18235. };
  18236. /**
  18237. * Releases resources associated with this node.
  18238. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18239. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18240. */
  18241. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18242. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18243. if (!doNotRecurse) {
  18244. var nodes = this.getDescendants(true);
  18245. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18246. var node = nodes_1[_i];
  18247. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18248. }
  18249. }
  18250. else {
  18251. var transformNodes = this.getChildTransformNodes(true);
  18252. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18253. var transformNode = transformNodes_1[_a];
  18254. transformNode.parent = null;
  18255. transformNode.computeWorldMatrix(true);
  18256. }
  18257. }
  18258. if (!this.parent) {
  18259. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18260. if (rootNodeIndex > -1) {
  18261. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18262. }
  18263. }
  18264. else {
  18265. this.parent = null;
  18266. }
  18267. // Callback
  18268. this.onDisposeObservable.notifyObservers(this);
  18269. this.onDisposeObservable.clear();
  18270. // Behaviors
  18271. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18272. var behavior = _c[_b];
  18273. behavior.detach();
  18274. }
  18275. this._behaviors = [];
  18276. this._isDisposed = true;
  18277. };
  18278. /**
  18279. * Parse animation range data from a serialization object and store them into a given node
  18280. * @param node defines where to store the animation ranges
  18281. * @param parsedNode defines the serialization object to read data from
  18282. * @param scene defines the hosting scene
  18283. */
  18284. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18285. if (parsedNode.ranges) {
  18286. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18287. var data = parsedNode.ranges[index];
  18288. node.createAnimationRange(data.name, data.from, data.to);
  18289. }
  18290. }
  18291. };
  18292. Node._NodeConstructors = {};
  18293. __decorate([
  18294. BABYLON.serialize()
  18295. ], Node.prototype, "name", void 0);
  18296. __decorate([
  18297. BABYLON.serialize()
  18298. ], Node.prototype, "id", void 0);
  18299. __decorate([
  18300. BABYLON.serialize()
  18301. ], Node.prototype, "uniqueId", void 0);
  18302. __decorate([
  18303. BABYLON.serialize()
  18304. ], Node.prototype, "state", void 0);
  18305. __decorate([
  18306. BABYLON.serialize()
  18307. ], Node.prototype, "metadata", void 0);
  18308. return Node;
  18309. }());
  18310. BABYLON.Node = Node;
  18311. })(BABYLON || (BABYLON = {}));
  18312. //# sourceMappingURL=babylon.node.js.map
  18313. var BABYLON;
  18314. (function (BABYLON) {
  18315. // This matrix is used as a value to reset the bounding box.
  18316. var _identityMatrix = BABYLON.Matrix.Identity();
  18317. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18318. var BoundingSphere = /** @class */ (function () {
  18319. /**
  18320. * Creates a new bounding sphere
  18321. * @param min defines the minimum vector (in local space)
  18322. * @param max defines the maximum vector (in local space)
  18323. */
  18324. function BoundingSphere(min, max) {
  18325. this.center = BABYLON.Vector3.Zero();
  18326. this.centerWorld = BABYLON.Vector3.Zero();
  18327. this.reConstruct(min, max);
  18328. }
  18329. /**
  18330. * Recreates the entire bounding sphere from scratch
  18331. * @param min defines the new minimum vector (in local space)
  18332. * @param max defines the new maximum vector (in local space)
  18333. */
  18334. BoundingSphere.prototype.reConstruct = function (min, max) {
  18335. this.minimum = min.clone();
  18336. this.maximum = max.clone();
  18337. var distance = BABYLON.Vector3.Distance(min, max);
  18338. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18339. this.radius = distance * 0.5;
  18340. this.centerWorld.set(0, 0, 0);
  18341. this._update(_identityMatrix);
  18342. };
  18343. /**
  18344. * Scale the current bounding sphere by applying a scale factor
  18345. * @param factor defines the scale factor to apply
  18346. * @returns the current bounding box
  18347. */
  18348. BoundingSphere.prototype.scale = function (factor) {
  18349. var newRadius = this.radius * factor;
  18350. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18351. var min = this.center.subtract(_tempRadiusVector);
  18352. var max = this.center.add(_tempRadiusVector);
  18353. this.reConstruct(min, max);
  18354. return this;
  18355. };
  18356. // Methods
  18357. /** @hidden */
  18358. BoundingSphere.prototype._update = function (world) {
  18359. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18360. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18361. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18362. };
  18363. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18364. for (var i = 0; i < 6; i++) {
  18365. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18366. return false;
  18367. }
  18368. return true;
  18369. };
  18370. BoundingSphere.prototype.intersectsPoint = function (point) {
  18371. var x = this.centerWorld.x - point.x;
  18372. var y = this.centerWorld.y - point.y;
  18373. var z = this.centerWorld.z - point.z;
  18374. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18375. if (this.radiusWorld < distance)
  18376. return false;
  18377. return true;
  18378. };
  18379. // Statics
  18380. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18381. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18382. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18383. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18384. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18385. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18386. return false;
  18387. return true;
  18388. };
  18389. return BoundingSphere;
  18390. }());
  18391. BABYLON.BoundingSphere = BoundingSphere;
  18392. })(BABYLON || (BABYLON = {}));
  18393. //# sourceMappingURL=babylon.boundingSphere.js.map
  18394. var BABYLON;
  18395. (function (BABYLON) {
  18396. /**
  18397. * Class used to store bounding box information
  18398. */
  18399. var BoundingBox = /** @class */ (function () {
  18400. /**
  18401. * Creates a new bounding box
  18402. * @param min defines the minimum vector (in local space)
  18403. * @param max defines the maximum vector (in local space)
  18404. */
  18405. function BoundingBox(min, max) {
  18406. /**
  18407. * Gets the 8 vectors representing the bounding box in world space
  18408. */
  18409. this.vectorsWorld = new Array();
  18410. this.reConstruct(min, max);
  18411. }
  18412. // Methods
  18413. /**
  18414. * Recreates the entire bounding box from scratch
  18415. * @param min defines the new minimum vector (in local space)
  18416. * @param max defines the new maximum vector (in local space)
  18417. */
  18418. BoundingBox.prototype.reConstruct = function (min, max) {
  18419. this.minimum = min.clone();
  18420. this.maximum = max.clone();
  18421. // Bounding vectors
  18422. this.vectors = [
  18423. this.minimum.clone(),
  18424. this.maximum.clone(),
  18425. this.minimum.clone(),
  18426. this.minimum.clone(),
  18427. this.minimum.clone(),
  18428. this.maximum.clone(),
  18429. this.maximum.clone(),
  18430. this.maximum.clone()
  18431. ];
  18432. this.vectors[2].x = this.maximum.x;
  18433. this.vectors[3].y = this.maximum.y;
  18434. this.vectors[4].z = this.maximum.z;
  18435. this.vectors[5].z = this.minimum.z;
  18436. this.vectors[6].x = this.minimum.x;
  18437. this.vectors[7].y = this.minimum.y;
  18438. // OBB
  18439. this.center = this.maximum.add(this.minimum).scale(0.5);
  18440. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18441. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18442. // World
  18443. for (var index = 0; index < this.vectors.length; index++) {
  18444. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18445. }
  18446. this.minimumWorld = BABYLON.Vector3.Zero();
  18447. this.maximumWorld = BABYLON.Vector3.Zero();
  18448. this.centerWorld = BABYLON.Vector3.Zero();
  18449. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18450. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18451. };
  18452. /**
  18453. * Scale the current bounding box by applying a scale factor
  18454. * @param factor defines the scale factor to apply
  18455. * @returns the current bounding box
  18456. */
  18457. BoundingBox.prototype.scale = function (factor) {
  18458. var diff = this.maximum.subtract(this.minimum);
  18459. var distance = diff.length() * factor;
  18460. diff.normalize();
  18461. var newRadius = diff.scale(distance / 2);
  18462. var min = this.center.subtract(newRadius);
  18463. var max = this.center.add(newRadius);
  18464. this.reConstruct(min, max);
  18465. return this;
  18466. };
  18467. /**
  18468. * Gets the world matrix of the bounding box
  18469. * @returns a matrix
  18470. */
  18471. BoundingBox.prototype.getWorldMatrix = function () {
  18472. return this._worldMatrix;
  18473. };
  18474. /**
  18475. * Sets the world matrix stored in the bounding box
  18476. * @param matrix defines the matrix to store
  18477. * @returns current bounding box
  18478. */
  18479. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18480. this._worldMatrix.copyFrom(matrix);
  18481. return this;
  18482. };
  18483. /** @hidden */
  18484. BoundingBox.prototype._update = function (world) {
  18485. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18486. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18487. for (var index = 0; index < this.vectors.length; index++) {
  18488. var v = this.vectorsWorld[index];
  18489. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18490. if (v.x < this.minimumWorld.x)
  18491. this.minimumWorld.x = v.x;
  18492. if (v.y < this.minimumWorld.y)
  18493. this.minimumWorld.y = v.y;
  18494. if (v.z < this.minimumWorld.z)
  18495. this.minimumWorld.z = v.z;
  18496. if (v.x > this.maximumWorld.x)
  18497. this.maximumWorld.x = v.x;
  18498. if (v.y > this.maximumWorld.y)
  18499. this.maximumWorld.y = v.y;
  18500. if (v.z > this.maximumWorld.z)
  18501. this.maximumWorld.z = v.z;
  18502. }
  18503. // Extend
  18504. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18505. this.extendSizeWorld.scaleInPlace(0.5);
  18506. // OBB
  18507. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18508. this.centerWorld.scaleInPlace(0.5);
  18509. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18510. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18511. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18512. this._worldMatrix = world;
  18513. };
  18514. /**
  18515. * Tests if the bounding box is intersecting the frustum planes
  18516. * @param frustumPlanes defines the frustum planes to test
  18517. * @returns true if there is an intersection
  18518. */
  18519. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18520. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18521. };
  18522. /**
  18523. * Tests if the bounding box is entirely inside the frustum planes
  18524. * @param frustumPlanes defines the frustum planes to test
  18525. * @returns true if there is an inclusion
  18526. */
  18527. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18528. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18529. };
  18530. /**
  18531. * Tests if a point is inside the bounding box
  18532. * @param point defines the point to test
  18533. * @returns true if the point is inside the bounding box
  18534. */
  18535. BoundingBox.prototype.intersectsPoint = function (point) {
  18536. var delta = -BABYLON.Epsilon;
  18537. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18538. return false;
  18539. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18540. return false;
  18541. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18542. return false;
  18543. return true;
  18544. };
  18545. /**
  18546. * Tests if the bounding box intersects with a bounding sphere
  18547. * @param sphere defines the sphere to test
  18548. * @returns true if there is an intersection
  18549. */
  18550. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18551. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18552. };
  18553. /**
  18554. * Tests if the bounding box intersects with a box defined by a min and max vectors
  18555. * @param min defines the min vector to use
  18556. * @param max defines the max vector to use
  18557. * @returns true if there is an intersection
  18558. */
  18559. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18560. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18561. return false;
  18562. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18563. return false;
  18564. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18565. return false;
  18566. return true;
  18567. };
  18568. // Statics
  18569. /**
  18570. * Tests if two bounding boxes are intersections
  18571. * @param box0 defines the first box to test
  18572. * @param box1 defines the second box to test
  18573. * @returns true if there is an intersection
  18574. */
  18575. BoundingBox.Intersects = function (box0, box1) {
  18576. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18577. return false;
  18578. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18579. return false;
  18580. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18581. return false;
  18582. return true;
  18583. };
  18584. /**
  18585. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  18586. * @param minPoint defines the minimum vector of the bounding box
  18587. * @param maxPoint defines the maximum vector of the bounding box
  18588. * @param sphereCenter defines the sphere center
  18589. * @param sphereRadius defines the sphere radius
  18590. * @returns true if there is an intersection
  18591. */
  18592. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18593. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18594. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18595. return (num <= (sphereRadius * sphereRadius));
  18596. };
  18597. /**
  18598. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  18599. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18600. * @param frustumPlanes defines the frustum planes to test
  18601. * @return true if there is an inclusion
  18602. */
  18603. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18604. for (var p = 0; p < 6; p++) {
  18605. for (var i = 0; i < 8; i++) {
  18606. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18607. return false;
  18608. }
  18609. }
  18610. }
  18611. return true;
  18612. };
  18613. /**
  18614. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  18615. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18616. * @param frustumPlanes defines the frustum planes to test
  18617. * @return true if there is an intersection
  18618. */
  18619. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18620. for (var p = 0; p < 6; p++) {
  18621. var inCount = 8;
  18622. for (var i = 0; i < 8; i++) {
  18623. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18624. --inCount;
  18625. }
  18626. else {
  18627. break;
  18628. }
  18629. }
  18630. if (inCount === 0)
  18631. return false;
  18632. }
  18633. return true;
  18634. };
  18635. return BoundingBox;
  18636. }());
  18637. BABYLON.BoundingBox = BoundingBox;
  18638. })(BABYLON || (BABYLON = {}));
  18639. //# sourceMappingURL=babylon.boundingBox.js.map
  18640. var BABYLON;
  18641. (function (BABYLON) {
  18642. var computeBoxExtents = function (axis, box) {
  18643. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18644. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18645. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18646. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18647. var r = r0 + r1 + r2;
  18648. return {
  18649. min: p - r,
  18650. max: p + r
  18651. };
  18652. };
  18653. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18654. var axisOverlap = function (axis, box0, box1) {
  18655. var result0 = computeBoxExtents(axis, box0);
  18656. var result1 = computeBoxExtents(axis, box1);
  18657. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18658. };
  18659. var BoundingInfo = /** @class */ (function () {
  18660. function BoundingInfo(minimum, maximum) {
  18661. this.minimum = minimum;
  18662. this.maximum = maximum;
  18663. this._isLocked = false;
  18664. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18665. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18666. }
  18667. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18668. get: function () {
  18669. return this._isLocked;
  18670. },
  18671. set: function (value) {
  18672. this._isLocked = value;
  18673. },
  18674. enumerable: true,
  18675. configurable: true
  18676. });
  18677. // Methods
  18678. BoundingInfo.prototype.update = function (world) {
  18679. if (this._isLocked) {
  18680. return;
  18681. }
  18682. this.boundingBox._update(world);
  18683. this.boundingSphere._update(world);
  18684. };
  18685. /**
  18686. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18687. * @param center New center of the bounding info
  18688. * @param extend New extend of the bounding info
  18689. */
  18690. BoundingInfo.prototype.centerOn = function (center, extend) {
  18691. this.minimum = center.subtract(extend);
  18692. this.maximum = center.add(extend);
  18693. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18694. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18695. return this;
  18696. };
  18697. /**
  18698. * Scale the current bounding info by applying a scale factor
  18699. * @param factor defines the scale factor to apply
  18700. * @returns the current bounding info
  18701. */
  18702. BoundingInfo.prototype.scale = function (factor) {
  18703. this.boundingBox.scale(factor);
  18704. this.boundingSphere.scale(factor);
  18705. return this;
  18706. };
  18707. /**
  18708. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18709. * @param frustumPlanes defines the frustum to test
  18710. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18711. * @returns true if the bounding info is in the frustum planes
  18712. */
  18713. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18714. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18715. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18716. return false;
  18717. }
  18718. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18719. return true;
  18720. }
  18721. return this.boundingBox.isInFrustum(frustumPlanes);
  18722. };
  18723. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18724. /**
  18725. * Gets the world distance between the min and max points of the bounding box
  18726. */
  18727. get: function () {
  18728. var boundingBox = this.boundingBox;
  18729. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18730. return size.length();
  18731. },
  18732. enumerable: true,
  18733. configurable: true
  18734. });
  18735. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18736. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18737. };
  18738. /** @hidden */
  18739. BoundingInfo.prototype._checkCollision = function (collider) {
  18740. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18741. };
  18742. BoundingInfo.prototype.intersectsPoint = function (point) {
  18743. if (!this.boundingSphere.centerWorld) {
  18744. return false;
  18745. }
  18746. if (!this.boundingSphere.intersectsPoint(point)) {
  18747. return false;
  18748. }
  18749. if (!this.boundingBox.intersectsPoint(point)) {
  18750. return false;
  18751. }
  18752. return true;
  18753. };
  18754. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18755. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18756. return false;
  18757. }
  18758. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18759. return false;
  18760. }
  18761. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18762. return false;
  18763. }
  18764. if (!precise) {
  18765. return true;
  18766. }
  18767. var box0 = this.boundingBox;
  18768. var box1 = boundingInfo.boundingBox;
  18769. if (!axisOverlap(box0.directions[0], box0, box1))
  18770. return false;
  18771. if (!axisOverlap(box0.directions[1], box0, box1))
  18772. return false;
  18773. if (!axisOverlap(box0.directions[2], box0, box1))
  18774. return false;
  18775. if (!axisOverlap(box1.directions[0], box0, box1))
  18776. return false;
  18777. if (!axisOverlap(box1.directions[1], box0, box1))
  18778. return false;
  18779. if (!axisOverlap(box1.directions[2], box0, box1))
  18780. return false;
  18781. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18782. return false;
  18783. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18784. return false;
  18785. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18786. return false;
  18787. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18788. return false;
  18789. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18790. return false;
  18791. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18792. return false;
  18793. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18794. return false;
  18795. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18796. return false;
  18797. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18798. return false;
  18799. return true;
  18800. };
  18801. return BoundingInfo;
  18802. }());
  18803. BABYLON.BoundingInfo = BoundingInfo;
  18804. })(BABYLON || (BABYLON = {}));
  18805. //# sourceMappingURL=babylon.boundingInfo.js.map
  18806. var BABYLON;
  18807. (function (BABYLON) {
  18808. var TransformNode = /** @class */ (function (_super) {
  18809. __extends(TransformNode, _super);
  18810. function TransformNode(name, scene, isPure) {
  18811. if (scene === void 0) { scene = null; }
  18812. if (isPure === void 0) { isPure = true; }
  18813. var _this = _super.call(this, name, scene) || this;
  18814. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18815. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18816. _this._up = new BABYLON.Vector3(0, 1, 0);
  18817. _this._right = new BABYLON.Vector3(1, 0, 0);
  18818. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18819. // Properties
  18820. _this._position = BABYLON.Vector3.Zero();
  18821. _this._rotation = BABYLON.Vector3.Zero();
  18822. _this._scaling = BABYLON.Vector3.One();
  18823. _this._isDirty = false;
  18824. /**
  18825. * Set the billboard mode. Default is 0.
  18826. *
  18827. * | Value | Type | Description |
  18828. * | --- | --- | --- |
  18829. * | 0 | BILLBOARDMODE_NONE | |
  18830. * | 1 | BILLBOARDMODE_X | |
  18831. * | 2 | BILLBOARDMODE_Y | |
  18832. * | 4 | BILLBOARDMODE_Z | |
  18833. * | 7 | BILLBOARDMODE_ALL | |
  18834. *
  18835. */
  18836. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18837. _this.scalingDeterminant = 1;
  18838. _this.infiniteDistance = false;
  18839. /**
  18840. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18841. * By default the system will update normals to compensate
  18842. */
  18843. _this.ignoreNonUniformScaling = false;
  18844. _this._localWorld = BABYLON.Matrix.Zero();
  18845. _this._absolutePosition = BABYLON.Vector3.Zero();
  18846. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18847. _this._postMultiplyPivotMatrix = false;
  18848. _this._isWorldMatrixFrozen = false;
  18849. /**
  18850. * An event triggered after the world matrix is updated
  18851. */
  18852. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18853. _this._nonUniformScaling = false;
  18854. if (isPure) {
  18855. _this.getScene().addTransformNode(_this);
  18856. }
  18857. return _this;
  18858. }
  18859. /**
  18860. * Gets a string identifying the name of the class
  18861. * @returns "TransformNode" string
  18862. */
  18863. TransformNode.prototype.getClassName = function () {
  18864. return "TransformNode";
  18865. };
  18866. Object.defineProperty(TransformNode.prototype, "position", {
  18867. /**
  18868. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18869. */
  18870. get: function () {
  18871. return this._position;
  18872. },
  18873. set: function (newPosition) {
  18874. this._position = newPosition;
  18875. this._isDirty = true;
  18876. },
  18877. enumerable: true,
  18878. configurable: true
  18879. });
  18880. Object.defineProperty(TransformNode.prototype, "rotation", {
  18881. /**
  18882. * 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)).
  18883. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18884. */
  18885. get: function () {
  18886. return this._rotation;
  18887. },
  18888. set: function (newRotation) {
  18889. this._rotation = newRotation;
  18890. this._isDirty = true;
  18891. },
  18892. enumerable: true,
  18893. configurable: true
  18894. });
  18895. Object.defineProperty(TransformNode.prototype, "scaling", {
  18896. /**
  18897. * 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)).
  18898. */
  18899. get: function () {
  18900. return this._scaling;
  18901. },
  18902. set: function (newScaling) {
  18903. this._scaling = newScaling;
  18904. this._isDirty = true;
  18905. },
  18906. enumerable: true,
  18907. configurable: true
  18908. });
  18909. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18910. /**
  18911. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18912. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18913. */
  18914. get: function () {
  18915. return this._rotationQuaternion;
  18916. },
  18917. set: function (quaternion) {
  18918. this._rotationQuaternion = quaternion;
  18919. //reset the rotation vector.
  18920. if (quaternion && this.rotation.length()) {
  18921. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18922. }
  18923. },
  18924. enumerable: true,
  18925. configurable: true
  18926. });
  18927. Object.defineProperty(TransformNode.prototype, "forward", {
  18928. /**
  18929. * The forward direction of that transform in world space.
  18930. */
  18931. get: function () {
  18932. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18933. },
  18934. enumerable: true,
  18935. configurable: true
  18936. });
  18937. Object.defineProperty(TransformNode.prototype, "up", {
  18938. /**
  18939. * The up direction of that transform in world space.
  18940. */
  18941. get: function () {
  18942. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18943. },
  18944. enumerable: true,
  18945. configurable: true
  18946. });
  18947. Object.defineProperty(TransformNode.prototype, "right", {
  18948. /**
  18949. * The right direction of that transform in world space.
  18950. */
  18951. get: function () {
  18952. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18953. },
  18954. enumerable: true,
  18955. configurable: true
  18956. });
  18957. /**
  18958. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18959. * Returns the TransformNode.
  18960. */
  18961. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18962. this._poseMatrix.copyFrom(matrix);
  18963. return this;
  18964. };
  18965. /**
  18966. * Returns the mesh Pose matrix.
  18967. * Returned object : Matrix
  18968. */
  18969. TransformNode.prototype.getPoseMatrix = function () {
  18970. return this._poseMatrix;
  18971. };
  18972. /** @hidden */
  18973. TransformNode.prototype._isSynchronized = function () {
  18974. if (this._isDirty) {
  18975. return false;
  18976. }
  18977. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18978. return false;
  18979. if (this._cache.pivotMatrixUpdated) {
  18980. return false;
  18981. }
  18982. if (this.infiniteDistance) {
  18983. return false;
  18984. }
  18985. if (!this._cache.position.equals(this._position))
  18986. return false;
  18987. if (this._rotationQuaternion) {
  18988. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18989. return false;
  18990. }
  18991. if (!this._cache.rotation.equals(this._rotation))
  18992. return false;
  18993. if (!this._cache.scaling.equals(this._scaling))
  18994. return false;
  18995. return true;
  18996. };
  18997. /** @hidden */
  18998. TransformNode.prototype._initCache = function () {
  18999. _super.prototype._initCache.call(this);
  19000. this._cache.localMatrixUpdated = false;
  19001. this._cache.position = BABYLON.Vector3.Zero();
  19002. this._cache.scaling = BABYLON.Vector3.Zero();
  19003. this._cache.rotation = BABYLON.Vector3.Zero();
  19004. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19005. this._cache.billboardMode = -1;
  19006. };
  19007. TransformNode.prototype.markAsDirty = function (property) {
  19008. if (property === "rotation") {
  19009. this.rotationQuaternion = null;
  19010. }
  19011. this._currentRenderId = Number.MAX_VALUE;
  19012. this._isDirty = true;
  19013. return this;
  19014. };
  19015. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19016. /**
  19017. * Returns the current mesh absolute position.
  19018. * Returns a Vector3.
  19019. */
  19020. get: function () {
  19021. return this._absolutePosition;
  19022. },
  19023. enumerable: true,
  19024. configurable: true
  19025. });
  19026. /**
  19027. * Sets a new matrix to apply before all other transformation
  19028. * @param matrix defines the transform matrix
  19029. * @returns the current TransformNode
  19030. */
  19031. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19032. return this.setPivotMatrix(matrix, false);
  19033. };
  19034. /**
  19035. * Sets a new pivot matrix to the current node
  19036. * @param matrix defines the new pivot matrix to use
  19037. * @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
  19038. * @returns the current TransformNode
  19039. */
  19040. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19041. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19042. this._pivotMatrix = matrix.clone();
  19043. this._cache.pivotMatrixUpdated = true;
  19044. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19045. if (this._postMultiplyPivotMatrix) {
  19046. if (!this._pivotMatrixInverse) {
  19047. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19048. }
  19049. else {
  19050. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19051. }
  19052. }
  19053. return this;
  19054. };
  19055. /**
  19056. * Returns the mesh pivot matrix.
  19057. * Default : Identity.
  19058. * A Matrix is returned.
  19059. */
  19060. TransformNode.prototype.getPivotMatrix = function () {
  19061. return this._pivotMatrix;
  19062. };
  19063. /**
  19064. * Prevents the World matrix to be computed any longer.
  19065. * Returns the TransformNode.
  19066. */
  19067. TransformNode.prototype.freezeWorldMatrix = function () {
  19068. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19069. this.computeWorldMatrix(true);
  19070. this._isWorldMatrixFrozen = true;
  19071. return this;
  19072. };
  19073. /**
  19074. * Allows back the World matrix computation.
  19075. * Returns the TransformNode.
  19076. */
  19077. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19078. this._isWorldMatrixFrozen = false;
  19079. this.computeWorldMatrix(true);
  19080. return this;
  19081. };
  19082. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19083. /**
  19084. * True if the World matrix has been frozen.
  19085. * Returns a boolean.
  19086. */
  19087. get: function () {
  19088. return this._isWorldMatrixFrozen;
  19089. },
  19090. enumerable: true,
  19091. configurable: true
  19092. });
  19093. /**
  19094. * Retuns the mesh absolute position in the World.
  19095. * Returns a Vector3.
  19096. */
  19097. TransformNode.prototype.getAbsolutePosition = function () {
  19098. this.computeWorldMatrix();
  19099. return this._absolutePosition;
  19100. };
  19101. /**
  19102. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19103. * Returns the TransformNode.
  19104. */
  19105. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19106. if (!absolutePosition) {
  19107. return this;
  19108. }
  19109. var absolutePositionX;
  19110. var absolutePositionY;
  19111. var absolutePositionZ;
  19112. if (absolutePosition.x === undefined) {
  19113. if (arguments.length < 3) {
  19114. return this;
  19115. }
  19116. absolutePositionX = arguments[0];
  19117. absolutePositionY = arguments[1];
  19118. absolutePositionZ = arguments[2];
  19119. }
  19120. else {
  19121. absolutePositionX = absolutePosition.x;
  19122. absolutePositionY = absolutePosition.y;
  19123. absolutePositionZ = absolutePosition.z;
  19124. }
  19125. if (this.parent) {
  19126. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19127. invertParentWorldMatrix.invert();
  19128. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19129. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19130. }
  19131. else {
  19132. this.position.x = absolutePositionX;
  19133. this.position.y = absolutePositionY;
  19134. this.position.z = absolutePositionZ;
  19135. }
  19136. return this;
  19137. };
  19138. /**
  19139. * Sets the mesh position in its local space.
  19140. * Returns the TransformNode.
  19141. */
  19142. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19143. this.computeWorldMatrix();
  19144. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19145. return this;
  19146. };
  19147. /**
  19148. * Returns the mesh position in the local space from the current World matrix values.
  19149. * Returns a new Vector3.
  19150. */
  19151. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19152. this.computeWorldMatrix();
  19153. var invLocalWorldMatrix = this._localWorld.clone();
  19154. invLocalWorldMatrix.invert();
  19155. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19156. };
  19157. /**
  19158. * Translates the mesh along the passed Vector3 in its local space.
  19159. * Returns the TransformNode.
  19160. */
  19161. TransformNode.prototype.locallyTranslate = function (vector3) {
  19162. this.computeWorldMatrix(true);
  19163. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19164. return this;
  19165. };
  19166. /**
  19167. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19168. * @param targetPoint the position (must be in same space as current mesh) to look at
  19169. * @param yawCor optional yaw (y-axis) correction in radians
  19170. * @param pitchCor optional pitch (x-axis) correction in radians
  19171. * @param rollCor optional roll (z-axis) correction in radians
  19172. * @param space the choosen space of the target
  19173. * @returns the TransformNode.
  19174. */
  19175. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19176. if (yawCor === void 0) { yawCor = 0; }
  19177. if (pitchCor === void 0) { pitchCor = 0; }
  19178. if (rollCor === void 0) { rollCor = 0; }
  19179. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19180. var dv = TransformNode._lookAtVectorCache;
  19181. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19182. targetPoint.subtractToRef(pos, dv);
  19183. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19184. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19185. var pitch = Math.atan2(dv.y, len);
  19186. if (this.rotationQuaternion) {
  19187. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19188. }
  19189. else {
  19190. this.rotation.x = pitch + pitchCor;
  19191. this.rotation.y = yaw + yawCor;
  19192. this.rotation.z = rollCor;
  19193. }
  19194. return this;
  19195. };
  19196. /**
  19197. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19198. * This Vector3 is expressed in the World space.
  19199. */
  19200. TransformNode.prototype.getDirection = function (localAxis) {
  19201. var result = BABYLON.Vector3.Zero();
  19202. this.getDirectionToRef(localAxis, result);
  19203. return result;
  19204. };
  19205. /**
  19206. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19207. * localAxis is expressed in the mesh local space.
  19208. * result is computed in the Wordl space from the mesh World matrix.
  19209. * Returns the TransformNode.
  19210. */
  19211. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19212. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19213. return this;
  19214. };
  19215. /**
  19216. * Sets a new pivot point to the current node
  19217. * @param point defines the new pivot point to use
  19218. * @param space defines if the point is in world or local space (local by default)
  19219. * @returns the current TransformNode
  19220. */
  19221. TransformNode.prototype.setPivotPoint = function (point, space) {
  19222. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19223. if (this.getScene().getRenderId() == 0) {
  19224. this.computeWorldMatrix(true);
  19225. }
  19226. var wm = this.getWorldMatrix();
  19227. if (space == BABYLON.Space.WORLD) {
  19228. var tmat = BABYLON.Tmp.Matrix[0];
  19229. wm.invertToRef(tmat);
  19230. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19231. }
  19232. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19233. };
  19234. /**
  19235. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19236. */
  19237. TransformNode.prototype.getPivotPoint = function () {
  19238. var point = BABYLON.Vector3.Zero();
  19239. this.getPivotPointToRef(point);
  19240. return point;
  19241. };
  19242. /**
  19243. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19244. * Returns the TransformNode.
  19245. */
  19246. TransformNode.prototype.getPivotPointToRef = function (result) {
  19247. result.x = -this._pivotMatrix.m[12];
  19248. result.y = -this._pivotMatrix.m[13];
  19249. result.z = -this._pivotMatrix.m[14];
  19250. return this;
  19251. };
  19252. /**
  19253. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19254. */
  19255. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19256. var point = BABYLON.Vector3.Zero();
  19257. this.getAbsolutePivotPointToRef(point);
  19258. return point;
  19259. };
  19260. /**
  19261. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19262. * Returns the TransformNode.
  19263. */
  19264. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19265. result.x = this._pivotMatrix.m[12];
  19266. result.y = this._pivotMatrix.m[13];
  19267. result.z = this._pivotMatrix.m[14];
  19268. this.getPivotPointToRef(result);
  19269. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19270. return this;
  19271. };
  19272. /**
  19273. * Defines the passed node as the parent of the current node.
  19274. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19275. * Returns the TransformNode.
  19276. */
  19277. TransformNode.prototype.setParent = function (node) {
  19278. if (!node && !this.parent) {
  19279. return this;
  19280. }
  19281. if (!node) {
  19282. var rotation = BABYLON.Tmp.Quaternion[0];
  19283. var position = BABYLON.Tmp.Vector3[0];
  19284. var scale = BABYLON.Tmp.Vector3[1];
  19285. if (this.parent && this.parent.computeWorldMatrix) {
  19286. this.parent.computeWorldMatrix(true);
  19287. }
  19288. this.computeWorldMatrix(true);
  19289. this.getWorldMatrix().decompose(scale, rotation, position);
  19290. if (this.rotationQuaternion) {
  19291. this.rotationQuaternion.copyFrom(rotation);
  19292. }
  19293. else {
  19294. rotation.toEulerAnglesToRef(this.rotation);
  19295. }
  19296. this.scaling.x = scale.x;
  19297. this.scaling.y = scale.y;
  19298. this.scaling.z = scale.z;
  19299. this.position.x = position.x;
  19300. this.position.y = position.y;
  19301. this.position.z = position.z;
  19302. }
  19303. else {
  19304. var rotation = BABYLON.Tmp.Quaternion[0];
  19305. var position = BABYLON.Tmp.Vector3[0];
  19306. var scale = BABYLON.Tmp.Vector3[1];
  19307. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19308. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19309. this.computeWorldMatrix(true);
  19310. node.computeWorldMatrix(true);
  19311. node.getWorldMatrix().invertToRef(invParentMatrix);
  19312. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19313. diffMatrix.decompose(scale, rotation, position);
  19314. if (this.rotationQuaternion) {
  19315. this.rotationQuaternion.copyFrom(rotation);
  19316. }
  19317. else {
  19318. rotation.toEulerAnglesToRef(this.rotation);
  19319. }
  19320. this.position.x = position.x;
  19321. this.position.y = position.y;
  19322. this.position.z = position.z;
  19323. this.scaling.x = scale.x;
  19324. this.scaling.y = scale.y;
  19325. this.scaling.z = scale.z;
  19326. }
  19327. this.parent = node;
  19328. return this;
  19329. };
  19330. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19331. get: function () {
  19332. return this._nonUniformScaling;
  19333. },
  19334. enumerable: true,
  19335. configurable: true
  19336. });
  19337. /** @hidden */
  19338. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19339. if (this._nonUniformScaling === value) {
  19340. return false;
  19341. }
  19342. this._nonUniformScaling = value;
  19343. return true;
  19344. };
  19345. /**
  19346. * Attach the current TransformNode to another TransformNode associated with a bone
  19347. * @param bone Bone affecting the TransformNode
  19348. * @param affectedTransformNode TransformNode associated with the bone
  19349. */
  19350. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19351. this._transformToBoneReferal = affectedTransformNode;
  19352. this.parent = bone;
  19353. if (bone.getWorldMatrix().determinant() < 0) {
  19354. this.scalingDeterminant *= -1;
  19355. }
  19356. return this;
  19357. };
  19358. TransformNode.prototype.detachFromBone = function () {
  19359. if (!this.parent) {
  19360. return this;
  19361. }
  19362. if (this.parent.getWorldMatrix().determinant() < 0) {
  19363. this.scalingDeterminant *= -1;
  19364. }
  19365. this._transformToBoneReferal = null;
  19366. this.parent = null;
  19367. return this;
  19368. };
  19369. /**
  19370. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19371. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19372. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19373. * The passed axis is also normalized.
  19374. * Returns the TransformNode.
  19375. */
  19376. TransformNode.prototype.rotate = function (axis, amount, space) {
  19377. axis.normalize();
  19378. if (!this.rotationQuaternion) {
  19379. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19380. this.rotation = BABYLON.Vector3.Zero();
  19381. }
  19382. var rotationQuaternion;
  19383. if (!space || space === BABYLON.Space.LOCAL) {
  19384. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19385. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19386. }
  19387. else {
  19388. if (this.parent) {
  19389. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19390. invertParentWorldMatrix.invert();
  19391. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19392. }
  19393. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19394. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19395. }
  19396. return this;
  19397. };
  19398. /**
  19399. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19400. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19401. * The passed axis is also normalized.
  19402. * Returns the TransformNode.
  19403. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19404. */
  19405. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19406. axis.normalize();
  19407. if (!this.rotationQuaternion) {
  19408. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19409. this.rotation.copyFromFloats(0, 0, 0);
  19410. }
  19411. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19412. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19413. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19414. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19415. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19416. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19417. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19418. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19419. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19420. return this;
  19421. };
  19422. /**
  19423. * Translates the mesh along the axis vector for the passed distance in the given space.
  19424. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19425. * Returns the TransformNode.
  19426. */
  19427. TransformNode.prototype.translate = function (axis, distance, space) {
  19428. var displacementVector = axis.scale(distance);
  19429. if (!space || space === BABYLON.Space.LOCAL) {
  19430. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19431. this.setPositionWithLocalVector(tempV3);
  19432. }
  19433. else {
  19434. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19435. }
  19436. return this;
  19437. };
  19438. /**
  19439. * Adds a rotation step to the mesh current rotation.
  19440. * x, y, z are Euler angles expressed in radians.
  19441. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19442. * This means this rotation is made in the mesh local space only.
  19443. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19444. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19445. * ```javascript
  19446. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19447. * ```
  19448. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19449. * 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.
  19450. * Returns the TransformNode.
  19451. */
  19452. TransformNode.prototype.addRotation = function (x, y, z) {
  19453. var rotationQuaternion;
  19454. if (this.rotationQuaternion) {
  19455. rotationQuaternion = this.rotationQuaternion;
  19456. }
  19457. else {
  19458. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19459. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19460. }
  19461. var accumulation = BABYLON.Tmp.Quaternion[0];
  19462. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19463. rotationQuaternion.multiplyInPlace(accumulation);
  19464. if (!this.rotationQuaternion) {
  19465. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19466. }
  19467. return this;
  19468. };
  19469. /**
  19470. * Computes the world matrix of the node
  19471. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19472. * @returns the world matrix
  19473. */
  19474. TransformNode.prototype.computeWorldMatrix = function (force) {
  19475. if (this._isWorldMatrixFrozen) {
  19476. return this._worldMatrix;
  19477. }
  19478. if (!force && this.isSynchronized()) {
  19479. this._currentRenderId = this.getScene().getRenderId();
  19480. return this._worldMatrix;
  19481. }
  19482. this._updateCache();
  19483. this._cache.position.copyFrom(this.position);
  19484. this._cache.scaling.copyFrom(this.scaling);
  19485. this._cache.pivotMatrixUpdated = false;
  19486. this._cache.billboardMode = this.billboardMode;
  19487. this._currentRenderId = this.getScene().getRenderId();
  19488. this._childRenderId = this.getScene().getRenderId();
  19489. this._isDirty = false;
  19490. // Scaling
  19491. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19492. // Rotation
  19493. //rotate, if quaternion is set and rotation was used
  19494. if (this.rotationQuaternion) {
  19495. var len = this.rotation.length();
  19496. if (len) {
  19497. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19498. this.rotation.copyFromFloats(0, 0, 0);
  19499. }
  19500. }
  19501. if (this.rotationQuaternion) {
  19502. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19503. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19504. }
  19505. else {
  19506. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19507. this._cache.rotation.copyFrom(this.rotation);
  19508. }
  19509. // Translation
  19510. var camera = this.getScene().activeCamera;
  19511. if (this.infiniteDistance && !this.parent && camera) {
  19512. var cameraWorldMatrix = camera.getWorldMatrix();
  19513. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19514. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19515. }
  19516. else {
  19517. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19518. }
  19519. // Composing transformations
  19520. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19521. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19522. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19523. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19524. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19525. // Need to decompose each rotation here
  19526. var currentPosition = BABYLON.Tmp.Vector3[3];
  19527. if (this.parent && this.parent.getWorldMatrix) {
  19528. if (this._transformToBoneReferal) {
  19529. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19530. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19531. }
  19532. else {
  19533. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19534. }
  19535. }
  19536. else {
  19537. currentPosition.copyFrom(this.position);
  19538. }
  19539. currentPosition.subtractInPlace(camera.globalPosition);
  19540. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19541. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19542. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19543. }
  19544. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19545. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19546. }
  19547. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19548. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19549. }
  19550. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19551. }
  19552. else {
  19553. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19554. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19555. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19556. }
  19557. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19558. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19559. }
  19560. // Post multiply inverse of pivotMatrix
  19561. if (this._postMultiplyPivotMatrix) {
  19562. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19563. }
  19564. // Local world
  19565. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19566. // Parent
  19567. if (this.parent && this.parent.getWorldMatrix) {
  19568. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19569. if (this._transformToBoneReferal) {
  19570. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19571. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19572. }
  19573. else {
  19574. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19575. }
  19576. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19577. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19578. this._worldMatrix.copyFrom(this._localWorld);
  19579. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19580. }
  19581. else {
  19582. if (this._transformToBoneReferal) {
  19583. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19584. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19585. }
  19586. else {
  19587. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19588. }
  19589. }
  19590. this._markSyncedWithParent();
  19591. }
  19592. else {
  19593. this._worldMatrix.copyFrom(this._localWorld);
  19594. }
  19595. // Normal matrix
  19596. if (!this.ignoreNonUniformScaling) {
  19597. if (this.scaling.isNonUniform) {
  19598. this._updateNonUniformScalingState(true);
  19599. }
  19600. else if (this.parent && this.parent._nonUniformScaling) {
  19601. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19602. }
  19603. else {
  19604. this._updateNonUniformScalingState(false);
  19605. }
  19606. }
  19607. else {
  19608. this._updateNonUniformScalingState(false);
  19609. }
  19610. this._afterComputeWorldMatrix();
  19611. // Absolute position
  19612. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19613. // Callbacks
  19614. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19615. if (!this._poseMatrix) {
  19616. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19617. }
  19618. // Cache the determinant
  19619. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19620. return this._worldMatrix;
  19621. };
  19622. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19623. };
  19624. /**
  19625. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19626. * @param func: callback function to add
  19627. *
  19628. * Returns the TransformNode.
  19629. */
  19630. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19631. this.onAfterWorldMatrixUpdateObservable.add(func);
  19632. return this;
  19633. };
  19634. /**
  19635. * Removes a registered callback function.
  19636. * Returns the TransformNode.
  19637. */
  19638. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19639. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19640. return this;
  19641. };
  19642. /**
  19643. * Clone the current transform node
  19644. * Returns the new transform node
  19645. * @param name Name of the new clone
  19646. * @param newParent New parent for the clone
  19647. * @param doNotCloneChildren Do not clone children hierarchy
  19648. */
  19649. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19650. var _this = this;
  19651. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19652. result.name = name;
  19653. result.id = name;
  19654. if (newParent) {
  19655. result.parent = newParent;
  19656. }
  19657. if (!doNotCloneChildren) {
  19658. // Children
  19659. var directDescendants = this.getDescendants(true);
  19660. for (var index = 0; index < directDescendants.length; index++) {
  19661. var child = directDescendants[index];
  19662. if (child.clone) {
  19663. child.clone(name + "." + child.name, result);
  19664. }
  19665. }
  19666. }
  19667. return result;
  19668. };
  19669. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19670. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19671. serializationObject.type = this.getClassName();
  19672. // Parent
  19673. if (this.parent) {
  19674. serializationObject.parentId = this.parent.id;
  19675. }
  19676. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19677. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19678. }
  19679. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19680. serializationObject.isEnabled = this.isEnabled();
  19681. // Parent
  19682. if (this.parent) {
  19683. serializationObject.parentId = this.parent.id;
  19684. }
  19685. return serializationObject;
  19686. };
  19687. // Statics
  19688. /**
  19689. * Returns a new TransformNode object parsed from the source provided.
  19690. * The parameter `parsedMesh` is the source.
  19691. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19692. */
  19693. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19694. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19695. if (BABYLON.Tags) {
  19696. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19697. }
  19698. if (parsedTransformNode.localMatrix) {
  19699. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19700. }
  19701. else if (parsedTransformNode.pivotMatrix) {
  19702. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19703. }
  19704. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19705. // Parent
  19706. if (parsedTransformNode.parentId) {
  19707. transformNode._waitingParentId = parsedTransformNode.parentId;
  19708. }
  19709. return transformNode;
  19710. };
  19711. /**
  19712. * Releases resources associated with this transform node.
  19713. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19714. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19715. */
  19716. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19717. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19718. // Animations
  19719. this.getScene().stopAnimation(this);
  19720. // Remove from scene
  19721. this.getScene().removeTransformNode(this);
  19722. this.onAfterWorldMatrixUpdateObservable.clear();
  19723. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19724. };
  19725. // Statics
  19726. TransformNode.BILLBOARDMODE_NONE = 0;
  19727. TransformNode.BILLBOARDMODE_X = 1;
  19728. TransformNode.BILLBOARDMODE_Y = 2;
  19729. TransformNode.BILLBOARDMODE_Z = 4;
  19730. TransformNode.BILLBOARDMODE_ALL = 7;
  19731. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19732. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19733. __decorate([
  19734. BABYLON.serializeAsVector3("position")
  19735. ], TransformNode.prototype, "_position", void 0);
  19736. __decorate([
  19737. BABYLON.serializeAsVector3("rotation")
  19738. ], TransformNode.prototype, "_rotation", void 0);
  19739. __decorate([
  19740. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19741. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19742. __decorate([
  19743. BABYLON.serializeAsVector3("scaling")
  19744. ], TransformNode.prototype, "_scaling", void 0);
  19745. __decorate([
  19746. BABYLON.serialize()
  19747. ], TransformNode.prototype, "billboardMode", void 0);
  19748. __decorate([
  19749. BABYLON.serialize()
  19750. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19751. __decorate([
  19752. BABYLON.serialize()
  19753. ], TransformNode.prototype, "infiniteDistance", void 0);
  19754. __decorate([
  19755. BABYLON.serialize()
  19756. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19757. return TransformNode;
  19758. }(BABYLON.Node));
  19759. BABYLON.TransformNode = TransformNode;
  19760. })(BABYLON || (BABYLON = {}));
  19761. //# sourceMappingURL=babylon.transformNode.js.map
  19762. var BABYLON;
  19763. (function (BABYLON) {
  19764. /**
  19765. * Class used to store all common mesh properties
  19766. */
  19767. var AbstractMesh = /** @class */ (function (_super) {
  19768. __extends(AbstractMesh, _super);
  19769. // Constructor
  19770. /**
  19771. * Creates a new AbstractMesh
  19772. * @param name defines the name of the mesh
  19773. * @param scene defines the hosting scene
  19774. */
  19775. function AbstractMesh(name, scene) {
  19776. if (scene === void 0) { scene = null; }
  19777. var _this = _super.call(this, name, scene, false) || this;
  19778. _this._facetNb = 0; // facet number
  19779. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19780. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19781. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19782. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19783. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19784. _this._subDiv = {
  19785. max: 1,
  19786. X: 1,
  19787. Y: 1,
  19788. Z: 1
  19789. };
  19790. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19791. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19792. /** Gets ot sets the culling strategy to use to find visible meshes */
  19793. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19794. // Events
  19795. /**
  19796. * An event triggered when this mesh collides with another one
  19797. */
  19798. _this.onCollideObservable = new BABYLON.Observable();
  19799. /**
  19800. * An event triggered when the collision's position changes
  19801. */
  19802. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19803. /**
  19804. * An event triggered when material is changed
  19805. */
  19806. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19807. // Properties
  19808. /**
  19809. * Gets or sets the orientation for POV movement & rotation
  19810. */
  19811. _this.definedFacingForward = true;
  19812. /**
  19813. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19814. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19815. * * 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.
  19816. * @see http://doc.babylonjs.com/features/occlusionquery
  19817. */
  19818. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19819. /**
  19820. * 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:
  19821. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19822. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19823. * * 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.
  19824. * @see http://doc.babylonjs.com/features/occlusionquery
  19825. */
  19826. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19827. /**
  19828. * 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.
  19829. * The default value is -1 which means don't break the query and wait till the result
  19830. * @see http://doc.babylonjs.com/features/occlusionquery
  19831. */
  19832. _this.occlusionRetryCount = -1;
  19833. /** @hidden */
  19834. _this._occlusionInternalRetryCounter = 0;
  19835. /** @hidden */
  19836. _this._isOccluded = false;
  19837. /** @hidden */
  19838. _this._isOcclusionQueryInProgress = false;
  19839. _this._visibility = 1.0;
  19840. /** Gets or sets the alpha index used to sort transparent meshes
  19841. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19842. */
  19843. _this.alphaIndex = Number.MAX_VALUE;
  19844. /**
  19845. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19846. */
  19847. _this.isVisible = true;
  19848. /**
  19849. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19850. */
  19851. _this.isPickable = true;
  19852. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19853. _this.showSubMeshesBoundingBox = false;
  19854. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19855. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19856. */
  19857. _this.isBlocker = false;
  19858. /**
  19859. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19860. */
  19861. _this.enablePointerMoveEvents = false;
  19862. /**
  19863. * Specifies the rendering group id for this mesh (0 by default)
  19864. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19865. */
  19866. _this.renderingGroupId = 0;
  19867. _this._receiveShadows = false;
  19868. /** Defines color to use when rendering outline */
  19869. _this.outlineColor = BABYLON.Color3.Red();
  19870. /** Define width to use when rendering outline */
  19871. _this.outlineWidth = 0.02;
  19872. /** Defines color to use when rendering overlay */
  19873. _this.overlayColor = BABYLON.Color3.Red();
  19874. /** Defines alpha to use when rendering overlay */
  19875. _this.overlayAlpha = 0.5;
  19876. _this._hasVertexAlpha = false;
  19877. _this._useVertexColors = true;
  19878. _this._computeBonesUsingShaders = true;
  19879. _this._numBoneInfluencers = 4;
  19880. _this._applyFog = true;
  19881. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19882. _this.useOctreeForRenderingSelection = true;
  19883. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19884. _this.useOctreeForPicking = true;
  19885. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19886. _this.useOctreeForCollisions = true;
  19887. _this._layerMask = 0x0FFFFFFF;
  19888. /**
  19889. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19890. */
  19891. _this.alwaysSelectAsActiveMesh = false;
  19892. /**
  19893. * Gets or sets the current action manager
  19894. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19895. */
  19896. _this.actionManager = null;
  19897. // Collisions
  19898. _this._checkCollisions = false;
  19899. _this._collisionMask = -1;
  19900. _this._collisionGroup = -1;
  19901. /**
  19902. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19903. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19904. */
  19905. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19906. /**
  19907. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19908. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19909. */
  19910. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19911. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19912. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19913. // Edges
  19914. /**
  19915. * Defines edge width used when edgesRenderer is enabled
  19916. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19917. */
  19918. _this.edgesWidth = 1;
  19919. /**
  19920. * Defines edge color used when edgesRenderer is enabled
  19921. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19922. */
  19923. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19924. // Cache
  19925. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19926. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19927. /** @hidden */
  19928. _this._renderId = 0;
  19929. /** @hidden */
  19930. _this._intersectionsInProgress = new Array();
  19931. /** @hidden */
  19932. _this._unIndexed = false;
  19933. /** @hidden */
  19934. _this._lightSources = new Array();
  19935. /**
  19936. * An event triggered when the mesh is rebuilt.
  19937. */
  19938. _this.onRebuildObservable = new BABYLON.Observable();
  19939. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19940. if (collidedMesh === void 0) { collidedMesh = null; }
  19941. //TODO move this to the collision coordinator!
  19942. if (_this.getScene().workerCollisions)
  19943. newPosition.multiplyInPlace(_this._collider._radius);
  19944. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19945. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19946. _this.position.addInPlace(_this._diffPositionForCollisions);
  19947. }
  19948. if (collidedMesh) {
  19949. _this.onCollideObservable.notifyObservers(collidedMesh);
  19950. }
  19951. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19952. };
  19953. _this.getScene().addMesh(_this);
  19954. _this._resyncLightSources();
  19955. return _this;
  19956. }
  19957. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19958. /**
  19959. * No billboard
  19960. */
  19961. get: function () {
  19962. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19963. },
  19964. enumerable: true,
  19965. configurable: true
  19966. });
  19967. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19968. /** Billboard on X axis */
  19969. get: function () {
  19970. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19971. },
  19972. enumerable: true,
  19973. configurable: true
  19974. });
  19975. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19976. /** Billboard on Y axis */
  19977. get: function () {
  19978. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19979. },
  19980. enumerable: true,
  19981. configurable: true
  19982. });
  19983. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19984. /** Billboard on Z axis */
  19985. get: function () {
  19986. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19987. },
  19988. enumerable: true,
  19989. configurable: true
  19990. });
  19991. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19992. /** Billboard on all axes */
  19993. get: function () {
  19994. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19995. },
  19996. enumerable: true,
  19997. configurable: true
  19998. });
  19999. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20000. /**
  20001. * Gets the number of facets in the mesh
  20002. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20003. */
  20004. get: function () {
  20005. return this._facetNb;
  20006. },
  20007. enumerable: true,
  20008. configurable: true
  20009. });
  20010. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20011. /**
  20012. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20013. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20014. */
  20015. get: function () {
  20016. return this._partitioningSubdivisions;
  20017. },
  20018. set: function (nb) {
  20019. this._partitioningSubdivisions = nb;
  20020. },
  20021. enumerable: true,
  20022. configurable: true
  20023. });
  20024. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20025. /**
  20026. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20027. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20028. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20029. */
  20030. get: function () {
  20031. return this._partitioningBBoxRatio;
  20032. },
  20033. set: function (ratio) {
  20034. this._partitioningBBoxRatio = ratio;
  20035. },
  20036. enumerable: true,
  20037. configurable: true
  20038. });
  20039. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20040. /**
  20041. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20042. * Works only for updatable meshes.
  20043. * Doesn't work with multi-materials
  20044. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20045. */
  20046. get: function () {
  20047. return this._facetDepthSort;
  20048. },
  20049. set: function (sort) {
  20050. this._facetDepthSort = sort;
  20051. },
  20052. enumerable: true,
  20053. configurable: true
  20054. });
  20055. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20056. /**
  20057. * The location (Vector3) where the facet depth sort must be computed from.
  20058. * By default, the active camera position.
  20059. * Used only when facet depth sort is enabled
  20060. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20061. */
  20062. get: function () {
  20063. return this._facetDepthSortFrom;
  20064. },
  20065. set: function (location) {
  20066. this._facetDepthSortFrom = location;
  20067. },
  20068. enumerable: true,
  20069. configurable: true
  20070. });
  20071. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20072. /**
  20073. * gets a boolean indicating if facetData is enabled
  20074. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20075. */
  20076. get: function () {
  20077. return this._facetDataEnabled;
  20078. },
  20079. enumerable: true,
  20080. configurable: true
  20081. });
  20082. /** @hidden */
  20083. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20084. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20085. return false;
  20086. }
  20087. this._markSubMeshesAsMiscDirty();
  20088. return true;
  20089. };
  20090. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20091. /** Set a function to call when this mesh collides with another one */
  20092. set: function (callback) {
  20093. if (this._onCollideObserver) {
  20094. this.onCollideObservable.remove(this._onCollideObserver);
  20095. }
  20096. this._onCollideObserver = this.onCollideObservable.add(callback);
  20097. },
  20098. enumerable: true,
  20099. configurable: true
  20100. });
  20101. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20102. /** Set a function to call when the collision's position changes */
  20103. set: function (callback) {
  20104. if (this._onCollisionPositionChangeObserver) {
  20105. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20106. }
  20107. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20108. },
  20109. enumerable: true,
  20110. configurable: true
  20111. });
  20112. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  20113. /**
  20114. * 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
  20115. * @see http://doc.babylonjs.com/features/occlusionquery
  20116. */
  20117. get: function () {
  20118. return this._isOccluded;
  20119. },
  20120. set: function (value) {
  20121. this._isOccluded = value;
  20122. },
  20123. enumerable: true,
  20124. configurable: true
  20125. });
  20126. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  20127. /**
  20128. * Flag to check the progress status of the query
  20129. * @see http://doc.babylonjs.com/features/occlusionquery
  20130. */
  20131. get: function () {
  20132. return this._isOcclusionQueryInProgress;
  20133. },
  20134. enumerable: true,
  20135. configurable: true
  20136. });
  20137. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20138. /**
  20139. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20140. */
  20141. get: function () {
  20142. return this._visibility;
  20143. },
  20144. /**
  20145. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20146. */
  20147. set: function (value) {
  20148. if (this._visibility === value) {
  20149. return;
  20150. }
  20151. this._visibility = value;
  20152. this._markSubMeshesAsMiscDirty();
  20153. },
  20154. enumerable: true,
  20155. configurable: true
  20156. });
  20157. Object.defineProperty(AbstractMesh.prototype, "material", {
  20158. /** Gets or sets current material */
  20159. get: function () {
  20160. return this._material;
  20161. },
  20162. set: function (value) {
  20163. if (this._material === value) {
  20164. return;
  20165. }
  20166. this._material = value;
  20167. if (this.onMaterialChangedObservable.hasObservers) {
  20168. this.onMaterialChangedObservable.notifyObservers(this);
  20169. }
  20170. if (!this.subMeshes) {
  20171. return;
  20172. }
  20173. this._unBindEffect();
  20174. },
  20175. enumerable: true,
  20176. configurable: true
  20177. });
  20178. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20179. /**
  20180. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20181. * @see http://doc.babylonjs.com/babylon101/shadows
  20182. */
  20183. get: function () {
  20184. return this._receiveShadows;
  20185. },
  20186. set: function (value) {
  20187. if (this._receiveShadows === value) {
  20188. return;
  20189. }
  20190. this._receiveShadows = value;
  20191. this._markSubMeshesAsLightDirty();
  20192. },
  20193. enumerable: true,
  20194. configurable: true
  20195. });
  20196. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20197. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20198. get: function () {
  20199. return this._hasVertexAlpha;
  20200. },
  20201. set: function (value) {
  20202. if (this._hasVertexAlpha === value) {
  20203. return;
  20204. }
  20205. this._hasVertexAlpha = value;
  20206. this._markSubMeshesAsAttributesDirty();
  20207. this._markSubMeshesAsMiscDirty();
  20208. },
  20209. enumerable: true,
  20210. configurable: true
  20211. });
  20212. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20213. /** 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) */
  20214. get: function () {
  20215. return this._useVertexColors;
  20216. },
  20217. set: function (value) {
  20218. if (this._useVertexColors === value) {
  20219. return;
  20220. }
  20221. this._useVertexColors = value;
  20222. this._markSubMeshesAsAttributesDirty();
  20223. },
  20224. enumerable: true,
  20225. configurable: true
  20226. });
  20227. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20228. /**
  20229. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20230. */
  20231. get: function () {
  20232. return this._computeBonesUsingShaders;
  20233. },
  20234. set: function (value) {
  20235. if (this._computeBonesUsingShaders === value) {
  20236. return;
  20237. }
  20238. this._computeBonesUsingShaders = value;
  20239. this._markSubMeshesAsAttributesDirty();
  20240. },
  20241. enumerable: true,
  20242. configurable: true
  20243. });
  20244. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20245. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20246. get: function () {
  20247. return this._numBoneInfluencers;
  20248. },
  20249. set: function (value) {
  20250. if (this._numBoneInfluencers === value) {
  20251. return;
  20252. }
  20253. this._numBoneInfluencers = value;
  20254. this._markSubMeshesAsAttributesDirty();
  20255. },
  20256. enumerable: true,
  20257. configurable: true
  20258. });
  20259. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20260. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20261. get: function () {
  20262. return this._applyFog;
  20263. },
  20264. set: function (value) {
  20265. if (this._applyFog === value) {
  20266. return;
  20267. }
  20268. this._applyFog = value;
  20269. this._markSubMeshesAsMiscDirty();
  20270. },
  20271. enumerable: true,
  20272. configurable: true
  20273. });
  20274. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20275. /**
  20276. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20277. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20278. */
  20279. get: function () {
  20280. return this._layerMask;
  20281. },
  20282. set: function (value) {
  20283. if (value === this._layerMask) {
  20284. return;
  20285. }
  20286. this._layerMask = value;
  20287. this._resyncLightSources();
  20288. },
  20289. enumerable: true,
  20290. configurable: true
  20291. });
  20292. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20293. /**
  20294. * Gets or sets a collision mask used to mask collisions (default is -1).
  20295. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20296. */
  20297. get: function () {
  20298. return this._collisionMask;
  20299. },
  20300. set: function (mask) {
  20301. this._collisionMask = !isNaN(mask) ? mask : -1;
  20302. },
  20303. enumerable: true,
  20304. configurable: true
  20305. });
  20306. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20307. /**
  20308. * Gets or sets the current collision group mask (-1 by default).
  20309. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20310. */
  20311. get: function () {
  20312. return this._collisionGroup;
  20313. },
  20314. set: function (mask) {
  20315. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20316. },
  20317. enumerable: true,
  20318. configurable: true
  20319. });
  20320. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20321. /** @hidden */
  20322. get: function () {
  20323. return null;
  20324. },
  20325. enumerable: true,
  20326. configurable: true
  20327. });
  20328. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20329. get: function () {
  20330. return this._skeleton;
  20331. },
  20332. /**
  20333. * Gets or sets a skeleton to apply skining transformations
  20334. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20335. */
  20336. set: function (value) {
  20337. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20338. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20339. }
  20340. if (value && value.needInitialSkinMatrix) {
  20341. value._registerMeshWithPoseMatrix(this);
  20342. }
  20343. this._skeleton = value;
  20344. if (!this._skeleton) {
  20345. this._bonesTransformMatrices = null;
  20346. }
  20347. this._markSubMeshesAsAttributesDirty();
  20348. },
  20349. enumerable: true,
  20350. configurable: true
  20351. });
  20352. /**
  20353. * Returns the string "AbstractMesh"
  20354. * @returns "AbstractMesh"
  20355. */
  20356. AbstractMesh.prototype.getClassName = function () {
  20357. return "AbstractMesh";
  20358. };
  20359. /**
  20360. * Gets a string representation of the current mesh
  20361. * @param fullDetails defines a boolean indicating if full details must be included
  20362. * @returns a string representation of the current mesh
  20363. */
  20364. AbstractMesh.prototype.toString = function (fullDetails) {
  20365. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20366. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20367. if (this._skeleton) {
  20368. ret += ", skeleton: " + this._skeleton.name;
  20369. }
  20370. if (fullDetails) {
  20371. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20372. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20373. }
  20374. return ret;
  20375. };
  20376. /** @hidden */
  20377. AbstractMesh.prototype._rebuild = function () {
  20378. this.onRebuildObservable.notifyObservers(this);
  20379. if (this._occlusionQuery) {
  20380. this._occlusionQuery = null;
  20381. }
  20382. if (!this.subMeshes) {
  20383. return;
  20384. }
  20385. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20386. var subMesh = _a[_i];
  20387. subMesh._rebuild();
  20388. }
  20389. };
  20390. /** @hidden */
  20391. AbstractMesh.prototype._resyncLightSources = function () {
  20392. this._lightSources.length = 0;
  20393. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20394. var light = _a[_i];
  20395. if (!light.isEnabled()) {
  20396. continue;
  20397. }
  20398. if (light.canAffectMesh(this)) {
  20399. this._lightSources.push(light);
  20400. }
  20401. }
  20402. this._markSubMeshesAsLightDirty();
  20403. };
  20404. /** @hidden */
  20405. AbstractMesh.prototype._resyncLighSource = function (light) {
  20406. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20407. var index = this._lightSources.indexOf(light);
  20408. if (index === -1) {
  20409. if (!isIn) {
  20410. return;
  20411. }
  20412. this._lightSources.push(light);
  20413. }
  20414. else {
  20415. if (isIn) {
  20416. return;
  20417. }
  20418. this._lightSources.splice(index, 1);
  20419. }
  20420. this._markSubMeshesAsLightDirty();
  20421. };
  20422. /** @hidden */
  20423. AbstractMesh.prototype._unBindEffect = function () {
  20424. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20425. var subMesh = _a[_i];
  20426. subMesh.setEffect(null);
  20427. }
  20428. };
  20429. /** @hidden */
  20430. AbstractMesh.prototype._removeLightSource = function (light) {
  20431. var index = this._lightSources.indexOf(light);
  20432. if (index === -1) {
  20433. return;
  20434. }
  20435. this._lightSources.splice(index, 1);
  20436. this._markSubMeshesAsLightDirty();
  20437. };
  20438. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20439. if (!this.subMeshes) {
  20440. return;
  20441. }
  20442. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20443. var subMesh = _a[_i];
  20444. if (subMesh._materialDefines) {
  20445. func(subMesh._materialDefines);
  20446. }
  20447. }
  20448. };
  20449. /** @hidden */
  20450. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20451. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20452. };
  20453. /** @hidden */
  20454. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20455. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20456. };
  20457. /** @hidden */
  20458. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20459. if (!this.subMeshes) {
  20460. return;
  20461. }
  20462. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20463. var subMesh = _a[_i];
  20464. var material = subMesh.getMaterial();
  20465. if (material) {
  20466. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20467. }
  20468. }
  20469. };
  20470. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20471. /**
  20472. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20473. */
  20474. get: function () {
  20475. return this._scaling;
  20476. },
  20477. set: function (newScaling) {
  20478. this._scaling = newScaling;
  20479. if (this.physicsImpostor) {
  20480. this.physicsImpostor.forceUpdate();
  20481. }
  20482. },
  20483. enumerable: true,
  20484. configurable: true
  20485. });
  20486. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20487. // Methods
  20488. /**
  20489. * Returns true if the mesh is blocked. Implemented by child classes
  20490. */
  20491. get: function () {
  20492. return false;
  20493. },
  20494. enumerable: true,
  20495. configurable: true
  20496. });
  20497. /**
  20498. * Returns the mesh itself by default. Implemented by child classes
  20499. * @param camera defines the camera to use to pick the right LOD level
  20500. * @returns the currentAbstractMesh
  20501. */
  20502. AbstractMesh.prototype.getLOD = function (camera) {
  20503. return this;
  20504. };
  20505. /**
  20506. * Returns 0 by default. Implemented by child classes
  20507. * @returns an integer
  20508. */
  20509. AbstractMesh.prototype.getTotalVertices = function () {
  20510. return 0;
  20511. };
  20512. /**
  20513. * Returns null by default. Implemented by child classes
  20514. * @returns null
  20515. */
  20516. AbstractMesh.prototype.getIndices = function () {
  20517. return null;
  20518. };
  20519. /**
  20520. * Returns the array of the requested vertex data kind. Implemented by child classes
  20521. * @param kind defines the vertex data kind to use
  20522. * @returns null
  20523. */
  20524. AbstractMesh.prototype.getVerticesData = function (kind) {
  20525. return null;
  20526. };
  20527. /**
  20528. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20529. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20530. * Note that a new underlying VertexBuffer object is created each call.
  20531. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20532. * @param kind defines vertex data kind:
  20533. * * BABYLON.VertexBuffer.PositionKind
  20534. * * BABYLON.VertexBuffer.UVKind
  20535. * * BABYLON.VertexBuffer.UV2Kind
  20536. * * BABYLON.VertexBuffer.UV3Kind
  20537. * * BABYLON.VertexBuffer.UV4Kind
  20538. * * BABYLON.VertexBuffer.UV5Kind
  20539. * * BABYLON.VertexBuffer.UV6Kind
  20540. * * BABYLON.VertexBuffer.ColorKind
  20541. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20542. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20543. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20544. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20545. * @param data defines the data source
  20546. * @param updatable defines if the data must be flagged as updatable (or static)
  20547. * @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
  20548. * @returns the current mesh
  20549. */
  20550. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20551. return this;
  20552. };
  20553. /**
  20554. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20555. * If the mesh has no geometry, it is simply returned as it is.
  20556. * @param kind defines vertex data kind:
  20557. * * BABYLON.VertexBuffer.PositionKind
  20558. * * BABYLON.VertexBuffer.UVKind
  20559. * * BABYLON.VertexBuffer.UV2Kind
  20560. * * BABYLON.VertexBuffer.UV3Kind
  20561. * * BABYLON.VertexBuffer.UV4Kind
  20562. * * BABYLON.VertexBuffer.UV5Kind
  20563. * * BABYLON.VertexBuffer.UV6Kind
  20564. * * BABYLON.VertexBuffer.ColorKind
  20565. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20566. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20567. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20568. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20569. * @param data defines the data source
  20570. * @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
  20571. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20572. * @returns the current mesh
  20573. */
  20574. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20575. return this;
  20576. };
  20577. /**
  20578. * Sets the mesh indices,
  20579. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20580. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20581. * @param totalVertices Defines the total number of vertices
  20582. * @returns the current mesh
  20583. */
  20584. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20585. return this;
  20586. };
  20587. /**
  20588. * Gets a boolean indicating if specific vertex data is present
  20589. * @param kind defines the vertex data kind to use
  20590. * @returns true is data kind is present
  20591. */
  20592. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20593. return false;
  20594. };
  20595. /**
  20596. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20597. * @returns a BoundingInfo
  20598. */
  20599. AbstractMesh.prototype.getBoundingInfo = function () {
  20600. if (this._masterMesh) {
  20601. return this._masterMesh.getBoundingInfo();
  20602. }
  20603. if (!this._boundingInfo) {
  20604. // this._boundingInfo is being created here
  20605. this._updateBoundingInfo();
  20606. }
  20607. // cannot be null.
  20608. return this._boundingInfo;
  20609. };
  20610. /**
  20611. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20612. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20613. * @returns the current mesh
  20614. */
  20615. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20616. if (includeDescendants === void 0) { includeDescendants = true; }
  20617. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20618. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20619. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20620. if (maxDimension === 0) {
  20621. return this;
  20622. }
  20623. var scale = 1 / maxDimension;
  20624. this.scaling.scaleInPlace(scale);
  20625. return this;
  20626. };
  20627. /**
  20628. * Overwrite the current bounding info
  20629. * @param boundingInfo defines the new bounding info
  20630. * @returns the current mesh
  20631. */
  20632. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20633. this._boundingInfo = boundingInfo;
  20634. return this;
  20635. };
  20636. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20637. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20638. get: function () {
  20639. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20640. },
  20641. enumerable: true,
  20642. configurable: true
  20643. });
  20644. /** @hidden */
  20645. AbstractMesh.prototype._preActivate = function () {
  20646. };
  20647. /** @hidden */
  20648. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20649. };
  20650. /** @hidden */
  20651. AbstractMesh.prototype._activate = function (renderId) {
  20652. this._renderId = renderId;
  20653. };
  20654. /**
  20655. * Gets the current world matrix
  20656. * @returns a Matrix
  20657. */
  20658. AbstractMesh.prototype.getWorldMatrix = function () {
  20659. if (this._masterMesh) {
  20660. return this._masterMesh.getWorldMatrix();
  20661. }
  20662. return _super.prototype.getWorldMatrix.call(this);
  20663. };
  20664. /** @hidden */
  20665. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20666. if (this._masterMesh) {
  20667. return this._masterMesh._getWorldMatrixDeterminant();
  20668. }
  20669. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20670. };
  20671. // ================================== Point of View Movement =================================
  20672. /**
  20673. * Perform relative position change from the point of view of behind the front of the mesh.
  20674. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20675. * Supports definition of mesh facing forward or backward
  20676. * @param amountRight defines the distance on the right axis
  20677. * @param amountUp defines the distance on the up axis
  20678. * @param amountForward defines the distance on the forward axis
  20679. * @returns the current mesh
  20680. */
  20681. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20682. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20683. return this;
  20684. };
  20685. /**
  20686. * Calculate relative position change from the point of view of behind the front of the mesh.
  20687. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20688. * Supports definition of mesh facing forward or backward
  20689. * @param amountRight defines the distance on the right axis
  20690. * @param amountUp defines the distance on the up axis
  20691. * @param amountForward defines the distance on the forward axis
  20692. * @returns the new displacement vector
  20693. */
  20694. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20695. var rotMatrix = new BABYLON.Matrix();
  20696. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20697. rotQuaternion.toRotationMatrix(rotMatrix);
  20698. var translationDelta = BABYLON.Vector3.Zero();
  20699. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20700. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20701. return translationDelta;
  20702. };
  20703. // ================================== Point of View Rotation =================================
  20704. /**
  20705. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20706. * Supports definition of mesh facing forward or backward
  20707. * @param flipBack defines the flip
  20708. * @param twirlClockwise defines the twirl
  20709. * @param tiltRight defines the tilt
  20710. * @returns the current mesh
  20711. */
  20712. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20713. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20714. return this;
  20715. };
  20716. /**
  20717. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20718. * Supports definition of mesh facing forward or backward.
  20719. * @param flipBack defines the flip
  20720. * @param twirlClockwise defines the twirl
  20721. * @param tiltRight defines the tilt
  20722. * @returns the new rotation vector
  20723. */
  20724. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20725. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20726. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20727. };
  20728. /**
  20729. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20730. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20731. * @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
  20732. * @returns the new bounding vectors
  20733. */
  20734. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20735. if (includeDescendants === void 0) { includeDescendants = true; }
  20736. if (predicate === void 0) { predicate = null; }
  20737. // Ensures that all world matrix will be recomputed.
  20738. this.getScene().incrementRenderId();
  20739. this.computeWorldMatrix(true);
  20740. var min;
  20741. var max;
  20742. var boundingInfo = this.getBoundingInfo();
  20743. if (!this.subMeshes) {
  20744. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20745. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20746. }
  20747. else {
  20748. min = boundingInfo.boundingBox.minimumWorld;
  20749. max = boundingInfo.boundingBox.maximumWorld;
  20750. }
  20751. if (includeDescendants) {
  20752. var descendants = this.getDescendants(false);
  20753. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20754. var descendant = descendants_1[_i];
  20755. var childMesh = descendant;
  20756. childMesh.computeWorldMatrix(true);
  20757. // Filters meshes based on custom predicate function.
  20758. if (predicate && !predicate(childMesh)) {
  20759. continue;
  20760. }
  20761. //make sure we have the needed params to get mix and max
  20762. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20763. continue;
  20764. }
  20765. var childBoundingInfo = childMesh.getBoundingInfo();
  20766. var boundingBox = childBoundingInfo.boundingBox;
  20767. var minBox = boundingBox.minimumWorld;
  20768. var maxBox = boundingBox.maximumWorld;
  20769. BABYLON.Tools.CheckExtends(minBox, min, max);
  20770. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20771. }
  20772. }
  20773. return {
  20774. min: min,
  20775. max: max
  20776. };
  20777. };
  20778. /** @hidden */
  20779. AbstractMesh.prototype._updateBoundingInfo = function () {
  20780. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20781. this._boundingInfo.update(this.worldMatrixFromCache);
  20782. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20783. return this;
  20784. };
  20785. /** @hidden */
  20786. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20787. if (!this.subMeshes) {
  20788. return this;
  20789. }
  20790. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20791. var subMesh = this.subMeshes[subIndex];
  20792. if (!subMesh.IsGlobal) {
  20793. subMesh.updateBoundingInfo(matrix);
  20794. }
  20795. }
  20796. return this;
  20797. };
  20798. /** @hidden */
  20799. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20800. // Bounding info
  20801. this._updateBoundingInfo();
  20802. };
  20803. /**
  20804. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20805. * A mesh is in the frustum if its bounding box intersects the frustum
  20806. * @param frustumPlanes defines the frustum to test
  20807. * @returns true if the mesh is in the frustum planes
  20808. */
  20809. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20810. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20811. };
  20812. /**
  20813. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20814. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20815. * @param frustumPlanes defines the frustum to test
  20816. * @returns true if the mesh is completely in the frustum planes
  20817. */
  20818. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20819. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20820. };
  20821. /**
  20822. * True if the mesh intersects another mesh or a SolidParticle object
  20823. * @param mesh defines a target mesh or SolidParticle to test
  20824. * @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)
  20825. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20826. * @returns true if there is an intersection
  20827. */
  20828. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20829. if (precise === void 0) { precise = false; }
  20830. if (!this._boundingInfo || !mesh._boundingInfo) {
  20831. return false;
  20832. }
  20833. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20834. return true;
  20835. }
  20836. if (includeDescendants) {
  20837. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20838. var child = _a[_i];
  20839. if (child.intersectsMesh(mesh, precise, true)) {
  20840. return true;
  20841. }
  20842. }
  20843. }
  20844. return false;
  20845. };
  20846. /**
  20847. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20848. * @param point defines the point to test
  20849. * @returns true if there is an intersection
  20850. */
  20851. AbstractMesh.prototype.intersectsPoint = function (point) {
  20852. if (!this._boundingInfo) {
  20853. return false;
  20854. }
  20855. return this._boundingInfo.intersectsPoint(point);
  20856. };
  20857. /**
  20858. * Gets the position of the current mesh in camera space
  20859. * @param camera defines the camera to use
  20860. * @returns a position
  20861. */
  20862. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20863. if (camera === void 0) { camera = null; }
  20864. if (!camera) {
  20865. camera = this.getScene().activeCamera;
  20866. }
  20867. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20868. };
  20869. /**
  20870. * Returns the distance from the mesh to the active camera
  20871. * @param camera defines the camera to use
  20872. * @returns the distance
  20873. */
  20874. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20875. if (camera === void 0) { camera = null; }
  20876. if (!camera) {
  20877. camera = this.getScene().activeCamera;
  20878. }
  20879. return this.absolutePosition.subtract(camera.position).length();
  20880. };
  20881. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20882. // Collisions
  20883. /**
  20884. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20885. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20886. */
  20887. get: function () {
  20888. return this._checkCollisions;
  20889. },
  20890. set: function (collisionEnabled) {
  20891. this._checkCollisions = collisionEnabled;
  20892. if (this.getScene().workerCollisions) {
  20893. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20894. }
  20895. },
  20896. enumerable: true,
  20897. configurable: true
  20898. });
  20899. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20900. /**
  20901. * Gets Collider object used to compute collisions (not physics)
  20902. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20903. */
  20904. get: function () {
  20905. return this._collider;
  20906. },
  20907. enumerable: true,
  20908. configurable: true
  20909. });
  20910. /**
  20911. * Move the mesh using collision engine
  20912. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20913. * @param displacement defines the requested displacement vector
  20914. * @returns the current mesh
  20915. */
  20916. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20917. var globalPosition = this.getAbsolutePosition();
  20918. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20919. if (!this._collider) {
  20920. this._collider = new BABYLON.Collider();
  20921. }
  20922. this._collider._radius = this.ellipsoid;
  20923. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20924. return this;
  20925. };
  20926. // Collisions
  20927. /** @hidden */
  20928. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20929. this._generatePointsArray();
  20930. if (!this._positions) {
  20931. return this;
  20932. }
  20933. // Transformation
  20934. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20935. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20936. subMesh._lastColliderWorldVertices = [];
  20937. subMesh._trianglePlanes = [];
  20938. var start = subMesh.verticesStart;
  20939. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20940. for (var i = start; i < end; i++) {
  20941. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20942. }
  20943. }
  20944. // Collide
  20945. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20946. if (collider.collisionFound) {
  20947. collider.collidedMesh = this;
  20948. }
  20949. return this;
  20950. };
  20951. /** @hidden */
  20952. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20953. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20954. var len = subMeshes.length;
  20955. for (var index = 0; index < len; index++) {
  20956. var subMesh = subMeshes.data[index];
  20957. // Bounding test
  20958. if (len > 1 && !subMesh._checkCollision(collider))
  20959. continue;
  20960. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20961. }
  20962. return this;
  20963. };
  20964. /** @hidden */
  20965. AbstractMesh.prototype._checkCollision = function (collider) {
  20966. // Bounding box test
  20967. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20968. return this;
  20969. // Transformation matrix
  20970. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20971. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20972. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20973. return this;
  20974. };
  20975. // Picking
  20976. /** @hidden */
  20977. AbstractMesh.prototype._generatePointsArray = function () {
  20978. return false;
  20979. };
  20980. /**
  20981. * Checks if the passed Ray intersects with the mesh
  20982. * @param ray defines the ray to use
  20983. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20984. * @returns the picking info
  20985. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20986. */
  20987. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20988. var pickingInfo = new BABYLON.PickingInfo();
  20989. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20990. return pickingInfo;
  20991. }
  20992. if (!this._generatePointsArray()) {
  20993. return pickingInfo;
  20994. }
  20995. var intersectInfo = null;
  20996. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20997. var len = subMeshes.length;
  20998. for (var index = 0; index < len; index++) {
  20999. var subMesh = subMeshes.data[index];
  21000. // Bounding test
  21001. if (len > 1 && !subMesh.canIntersects(ray))
  21002. continue;
  21003. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21004. if (currentIntersectInfo) {
  21005. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21006. intersectInfo = currentIntersectInfo;
  21007. intersectInfo.subMeshId = index;
  21008. if (fastCheck) {
  21009. break;
  21010. }
  21011. }
  21012. }
  21013. }
  21014. if (intersectInfo) {
  21015. // Get picked point
  21016. var world = this.getWorldMatrix();
  21017. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21018. var direction = ray.direction.clone();
  21019. direction = direction.scale(intersectInfo.distance);
  21020. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21021. var pickedPoint = worldOrigin.add(worldDirection);
  21022. // Return result
  21023. pickingInfo.hit = true;
  21024. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21025. pickingInfo.pickedPoint = pickedPoint;
  21026. pickingInfo.pickedMesh = this;
  21027. pickingInfo.bu = intersectInfo.bu || 0;
  21028. pickingInfo.bv = intersectInfo.bv || 0;
  21029. pickingInfo.faceId = intersectInfo.faceId;
  21030. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21031. return pickingInfo;
  21032. }
  21033. return pickingInfo;
  21034. };
  21035. /**
  21036. * Clones the current mesh
  21037. * @param name defines the mesh name
  21038. * @param newParent defines the new mesh parent
  21039. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21040. * @returns the new mesh
  21041. */
  21042. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21043. return null;
  21044. };
  21045. /**
  21046. * Disposes all the submeshes of the current meshnp
  21047. * @returns the current mesh
  21048. */
  21049. AbstractMesh.prototype.releaseSubMeshes = function () {
  21050. if (this.subMeshes) {
  21051. while (this.subMeshes.length) {
  21052. this.subMeshes[0].dispose();
  21053. }
  21054. }
  21055. else {
  21056. this.subMeshes = new Array();
  21057. }
  21058. return this;
  21059. };
  21060. /**
  21061. * Releases resources associated with this abstract mesh.
  21062. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21063. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21064. */
  21065. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21066. var _this = this;
  21067. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21068. var index;
  21069. // Smart Array Retainers.
  21070. this.getScene().freeActiveMeshes();
  21071. this.getScene().freeRenderingGroups();
  21072. // Action manager
  21073. if (this.actionManager !== undefined && this.actionManager !== null) {
  21074. this.actionManager.dispose();
  21075. this.actionManager = null;
  21076. }
  21077. // Skeleton
  21078. this._skeleton = null;
  21079. // Intersections in progress
  21080. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21081. var other = this._intersectionsInProgress[index];
  21082. var pos = other._intersectionsInProgress.indexOf(this);
  21083. other._intersectionsInProgress.splice(pos, 1);
  21084. }
  21085. this._intersectionsInProgress = [];
  21086. // Lights
  21087. var lights = this.getScene().lights;
  21088. lights.forEach(function (light) {
  21089. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21090. if (meshIndex !== -1) {
  21091. light.includedOnlyMeshes.splice(meshIndex, 1);
  21092. }
  21093. meshIndex = light.excludedMeshes.indexOf(_this);
  21094. if (meshIndex !== -1) {
  21095. light.excludedMeshes.splice(meshIndex, 1);
  21096. }
  21097. // Shadow generators
  21098. var generator = light.getShadowGenerator();
  21099. if (generator) {
  21100. var shadowMap = generator.getShadowMap();
  21101. if (shadowMap && shadowMap.renderList) {
  21102. meshIndex = shadowMap.renderList.indexOf(_this);
  21103. if (meshIndex !== -1) {
  21104. shadowMap.renderList.splice(meshIndex, 1);
  21105. }
  21106. }
  21107. }
  21108. });
  21109. // SubMeshes
  21110. if (this.getClassName() !== "InstancedMesh") {
  21111. this.releaseSubMeshes();
  21112. }
  21113. // Query
  21114. var engine = this.getScene().getEngine();
  21115. if (this._occlusionQuery) {
  21116. this._isOcclusionQueryInProgress = false;
  21117. engine.deleteQuery(this._occlusionQuery);
  21118. this._occlusionQuery = null;
  21119. }
  21120. // Engine
  21121. engine.wipeCaches();
  21122. // Remove from scene
  21123. this.getScene().removeMesh(this);
  21124. if (disposeMaterialAndTextures) {
  21125. if (this.material) {
  21126. this.material.dispose(false, true);
  21127. }
  21128. }
  21129. if (!doNotRecurse) {
  21130. // Particles
  21131. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21132. if (this.getScene().particleSystems[index].emitter === this) {
  21133. this.getScene().particleSystems[index].dispose();
  21134. index--;
  21135. }
  21136. }
  21137. }
  21138. // facet data
  21139. if (this._facetDataEnabled) {
  21140. this.disableFacetData();
  21141. }
  21142. this.onAfterWorldMatrixUpdateObservable.clear();
  21143. this.onCollideObservable.clear();
  21144. this.onCollisionPositionChangeObservable.clear();
  21145. this.onRebuildObservable.clear();
  21146. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21147. };
  21148. /**
  21149. * Adds the passed mesh as a child to the current mesh
  21150. * @param mesh defines the child mesh
  21151. * @returns the current mesh
  21152. */
  21153. AbstractMesh.prototype.addChild = function (mesh) {
  21154. mesh.setParent(this);
  21155. return this;
  21156. };
  21157. /**
  21158. * Removes the passed mesh from the current mesh children list
  21159. * @param mesh defines the child mesh
  21160. * @returns the current mesh
  21161. */
  21162. AbstractMesh.prototype.removeChild = function (mesh) {
  21163. mesh.setParent(null);
  21164. return this;
  21165. };
  21166. // Facet data
  21167. /** @hidden */
  21168. AbstractMesh.prototype._initFacetData = function () {
  21169. if (!this._facetNormals) {
  21170. this._facetNormals = new Array();
  21171. }
  21172. if (!this._facetPositions) {
  21173. this._facetPositions = new Array();
  21174. }
  21175. if (!this._facetPartitioning) {
  21176. this._facetPartitioning = new Array();
  21177. }
  21178. this._facetNb = (this.getIndices().length / 3) | 0;
  21179. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21180. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21181. for (var f = 0; f < this._facetNb; f++) {
  21182. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21183. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21184. }
  21185. this._facetDataEnabled = true;
  21186. return this;
  21187. };
  21188. /**
  21189. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21190. * This method can be called within the render loop.
  21191. * 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
  21192. * @returns the current mesh
  21193. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21194. */
  21195. AbstractMesh.prototype.updateFacetData = function () {
  21196. if (!this._facetDataEnabled) {
  21197. this._initFacetData();
  21198. }
  21199. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21200. var indices = this.getIndices();
  21201. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21202. var bInfo = this.getBoundingInfo();
  21203. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21204. // init arrays, matrix and sort function on first call
  21205. this._facetDepthSortEnabled = true;
  21206. if (indices instanceof Uint16Array) {
  21207. this._depthSortedIndices = new Uint16Array(indices);
  21208. }
  21209. else if (indices instanceof Uint32Array) {
  21210. this._depthSortedIndices = new Uint32Array(indices);
  21211. }
  21212. else {
  21213. var needs32bits = false;
  21214. for (var i = 0; i < indices.length; i++) {
  21215. if (indices[i] > 65535) {
  21216. needs32bits = true;
  21217. break;
  21218. }
  21219. }
  21220. if (needs32bits) {
  21221. this._depthSortedIndices = new Uint32Array(indices);
  21222. }
  21223. else {
  21224. this._depthSortedIndices = new Uint16Array(indices);
  21225. }
  21226. }
  21227. this._facetDepthSortFunction = function (f1, f2) {
  21228. return (f2.sqDistance - f1.sqDistance);
  21229. };
  21230. if (!this._facetDepthSortFrom) {
  21231. var camera = this.getScene().activeCamera;
  21232. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21233. }
  21234. this._depthSortedFacets = [];
  21235. for (var f = 0; f < this._facetNb; f++) {
  21236. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21237. this._depthSortedFacets.push(depthSortedFacet);
  21238. }
  21239. this._invertedMatrix = BABYLON.Matrix.Identity();
  21240. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21241. }
  21242. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21243. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21244. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21245. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21246. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21247. this._subDiv.max = this._partitioningSubdivisions;
  21248. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21249. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21250. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21251. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21252. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21253. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21254. // set the parameters for ComputeNormals()
  21255. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21256. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21257. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21258. this._facetParameters.bInfo = bInfo;
  21259. this._facetParameters.bbSize = this._bbSize;
  21260. this._facetParameters.subDiv = this._subDiv;
  21261. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21262. this._facetParameters.depthSort = this._facetDepthSort;
  21263. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21264. this.computeWorldMatrix(true);
  21265. this._worldMatrix.invertToRef(this._invertedMatrix);
  21266. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21267. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21268. }
  21269. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21270. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21271. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21272. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21273. var l = (this._depthSortedIndices.length / 3) | 0;
  21274. for (var f = 0; f < l; f++) {
  21275. var sind = this._depthSortedFacets[f].ind;
  21276. this._depthSortedIndices[f * 3] = indices[sind];
  21277. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21278. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21279. }
  21280. this.updateIndices(this._depthSortedIndices);
  21281. }
  21282. return this;
  21283. };
  21284. /**
  21285. * Returns the facetLocalNormals array.
  21286. * The normals are expressed in the mesh local spac
  21287. * @returns an array of Vector3
  21288. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21289. */
  21290. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21291. if (!this._facetNormals) {
  21292. this.updateFacetData();
  21293. }
  21294. return this._facetNormals;
  21295. };
  21296. /**
  21297. * Returns the facetLocalPositions array.
  21298. * The facet positions are expressed in the mesh local space
  21299. * @returns an array of Vector3
  21300. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21301. */
  21302. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21303. if (!this._facetPositions) {
  21304. this.updateFacetData();
  21305. }
  21306. return this._facetPositions;
  21307. };
  21308. /**
  21309. * Returns the facetLocalPartioning array
  21310. * @returns an array of array of numbers
  21311. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21312. */
  21313. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21314. if (!this._facetPartitioning) {
  21315. this.updateFacetData();
  21316. }
  21317. return this._facetPartitioning;
  21318. };
  21319. /**
  21320. * Returns the i-th facet position in the world system.
  21321. * This method allocates a new Vector3 per call
  21322. * @param i defines the facet index
  21323. * @returns a new Vector3
  21324. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21325. */
  21326. AbstractMesh.prototype.getFacetPosition = function (i) {
  21327. var pos = BABYLON.Vector3.Zero();
  21328. this.getFacetPositionToRef(i, pos);
  21329. return pos;
  21330. };
  21331. /**
  21332. * Sets the reference Vector3 with the i-th facet position in the world system
  21333. * @param i defines the facet index
  21334. * @param ref defines the target vector
  21335. * @returns the current mesh
  21336. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21337. */
  21338. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21339. var localPos = (this.getFacetLocalPositions())[i];
  21340. var world = this.getWorldMatrix();
  21341. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21342. return this;
  21343. };
  21344. /**
  21345. * Returns the i-th facet normal in the world system.
  21346. * This method allocates a new Vector3 per call
  21347. * @param i defines the facet index
  21348. * @returns a new Vector3
  21349. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21350. */
  21351. AbstractMesh.prototype.getFacetNormal = function (i) {
  21352. var norm = BABYLON.Vector3.Zero();
  21353. this.getFacetNormalToRef(i, norm);
  21354. return norm;
  21355. };
  21356. /**
  21357. * Sets the reference Vector3 with the i-th facet normal in the world system
  21358. * @param i defines the facet index
  21359. * @param ref defines the target vector
  21360. * @returns the current mesh
  21361. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21362. */
  21363. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21364. var localNorm = (this.getFacetLocalNormals())[i];
  21365. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21366. return this;
  21367. };
  21368. /**
  21369. * 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)
  21370. * @param x defines x coordinate
  21371. * @param y defines y coordinate
  21372. * @param z defines z coordinate
  21373. * @returns the array of facet indexes
  21374. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21375. */
  21376. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21377. var bInfo = this.getBoundingInfo();
  21378. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21379. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21380. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21381. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21382. return null;
  21383. }
  21384. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21385. };
  21386. /**
  21387. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21388. * @param projected sets as the (x,y,z) world projection on the facet
  21389. * @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
  21390. * @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
  21391. * @param x defines x coordinate
  21392. * @param y defines y coordinate
  21393. * @param z defines z coordinate
  21394. * @returns the face index if found (or null instead)
  21395. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21396. */
  21397. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21398. if (checkFace === void 0) { checkFace = false; }
  21399. if (facing === void 0) { facing = true; }
  21400. var world = this.getWorldMatrix();
  21401. var invMat = BABYLON.Tmp.Matrix[5];
  21402. world.invertToRef(invMat);
  21403. var invVect = BABYLON.Tmp.Vector3[8];
  21404. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21405. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21406. if (projected) {
  21407. // tranform the local computed projected vector to world coordinates
  21408. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21409. }
  21410. return closest;
  21411. };
  21412. /**
  21413. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21414. * @param projected sets as the (x,y,z) local projection on the facet
  21415. * @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
  21416. * @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
  21417. * @param x defines x coordinate
  21418. * @param y defines y coordinate
  21419. * @param z defines z coordinate
  21420. * @returns the face index if found (or null instead)
  21421. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21422. */
  21423. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21424. if (checkFace === void 0) { checkFace = false; }
  21425. if (facing === void 0) { facing = true; }
  21426. var closest = null;
  21427. var tmpx = 0.0;
  21428. var tmpy = 0.0;
  21429. var tmpz = 0.0;
  21430. var d = 0.0; // tmp dot facet normal * facet position
  21431. var t0 = 0.0;
  21432. var projx = 0.0;
  21433. var projy = 0.0;
  21434. var projz = 0.0;
  21435. // Get all the facets in the same partitioning block than (x, y, z)
  21436. var facetPositions = this.getFacetLocalPositions();
  21437. var facetNormals = this.getFacetLocalNormals();
  21438. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21439. if (!facetsInBlock) {
  21440. return null;
  21441. }
  21442. // Get the closest facet to (x, y, z)
  21443. var shortest = Number.MAX_VALUE; // init distance vars
  21444. var tmpDistance = shortest;
  21445. var fib; // current facet in the block
  21446. var norm; // current facet normal
  21447. var p0; // current facet barycenter position
  21448. // loop on all the facets in the current partitioning block
  21449. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21450. fib = facetsInBlock[idx];
  21451. norm = facetNormals[fib];
  21452. p0 = facetPositions[fib];
  21453. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21454. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21455. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21456. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21457. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21458. projx = x + norm.x * t0;
  21459. projy = y + norm.y * t0;
  21460. projz = z + norm.z * t0;
  21461. tmpx = projx - x;
  21462. tmpy = projy - y;
  21463. tmpz = projz - z;
  21464. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21465. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21466. shortest = tmpDistance;
  21467. closest = fib;
  21468. if (projected) {
  21469. projected.x = projx;
  21470. projected.y = projy;
  21471. projected.z = projz;
  21472. }
  21473. }
  21474. }
  21475. }
  21476. return closest;
  21477. };
  21478. /**
  21479. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21480. * @returns the parameters
  21481. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21482. */
  21483. AbstractMesh.prototype.getFacetDataParameters = function () {
  21484. return this._facetParameters;
  21485. };
  21486. /**
  21487. * Disables the feature FacetData and frees the related memory
  21488. * @returns the current mesh
  21489. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21490. */
  21491. AbstractMesh.prototype.disableFacetData = function () {
  21492. if (this._facetDataEnabled) {
  21493. this._facetDataEnabled = false;
  21494. this._facetPositions = new Array();
  21495. this._facetNormals = new Array();
  21496. this._facetPartitioning = new Array();
  21497. this._facetParameters = null;
  21498. this._depthSortedIndices = new Uint32Array(0);
  21499. }
  21500. return this;
  21501. };
  21502. /**
  21503. * Updates the AbstractMesh indices array
  21504. * @param indices defines the data source
  21505. * @returns the current mesh
  21506. */
  21507. AbstractMesh.prototype.updateIndices = function (indices) {
  21508. return this;
  21509. };
  21510. /**
  21511. * Creates new normals data for the mesh
  21512. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21513. * @returns the current mesh
  21514. */
  21515. AbstractMesh.prototype.createNormals = function (updatable) {
  21516. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21517. var indices = this.getIndices();
  21518. var normals;
  21519. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21520. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21521. }
  21522. else {
  21523. normals = [];
  21524. }
  21525. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21526. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21527. return this;
  21528. };
  21529. /**
  21530. * Align the mesh with a normal
  21531. * @param normal defines the normal to use
  21532. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21533. * @returns the current mesh
  21534. */
  21535. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21536. if (!upDirection) {
  21537. upDirection = BABYLON.Axis.Y;
  21538. }
  21539. var axisX = BABYLON.Tmp.Vector3[0];
  21540. var axisZ = BABYLON.Tmp.Vector3[1];
  21541. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21542. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21543. if (this.rotationQuaternion) {
  21544. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21545. }
  21546. else {
  21547. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21548. }
  21549. return this;
  21550. };
  21551. /** @hidden */
  21552. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21553. this._isOccluded = false;
  21554. };
  21555. /** No occlusion */
  21556. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21557. /** Occlusion set to optimisitic */
  21558. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21559. /** Occlusion set to strict */
  21560. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21561. /** Use an accurante occlusion algorithm */
  21562. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21563. /** Use a conservative occlusion algorithm */
  21564. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21565. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21566. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21567. /** Culling strategy with bounding sphere only and then frustum culling */
  21568. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21569. return AbstractMesh;
  21570. }(BABYLON.TransformNode));
  21571. BABYLON.AbstractMesh = AbstractMesh;
  21572. })(BABYLON || (BABYLON = {}));
  21573. //# sourceMappingURL=babylon.abstractMesh.js.map
  21574. var BABYLON;
  21575. (function (BABYLON) {
  21576. /**
  21577. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21578. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21579. * 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.
  21580. */
  21581. var Light = /** @class */ (function (_super) {
  21582. __extends(Light, _super);
  21583. /**
  21584. * Creates a Light object in the scene.
  21585. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21586. * @param name The firendly name of the light
  21587. * @param scene The scene the light belongs too
  21588. */
  21589. function Light(name, scene) {
  21590. var _this = _super.call(this, name, scene) || this;
  21591. /**
  21592. * Diffuse gives the basic color to an object.
  21593. */
  21594. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21595. /**
  21596. * Specular produces a highlight color on an object.
  21597. * Note: This is note affecting PBR materials.
  21598. */
  21599. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21600. /**
  21601. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21602. * falling off base on range or angle.
  21603. * This can be set to any values in Light.FALLOFF_x.
  21604. *
  21605. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21606. * other types of materials.
  21607. */
  21608. _this.falloffType = Light.FALLOFF_DEFAULT;
  21609. /**
  21610. * Strength of the light.
  21611. * Note: By default it is define in the framework own unit.
  21612. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21613. */
  21614. _this.intensity = 1.0;
  21615. _this._range = Number.MAX_VALUE;
  21616. _this._inverseSquaredRange = 0;
  21617. /**
  21618. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21619. * of light.
  21620. */
  21621. _this._photometricScale = 1.0;
  21622. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21623. _this._radius = 0.00001;
  21624. /**
  21625. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21626. * exceeding the number allowed of the materials.
  21627. */
  21628. _this.renderPriority = 0;
  21629. _this._shadowEnabled = true;
  21630. _this._excludeWithLayerMask = 0;
  21631. _this._includeOnlyWithLayerMask = 0;
  21632. _this._lightmapMode = 0;
  21633. /**
  21634. * @hidden Internal use only.
  21635. */
  21636. _this._excludedMeshesIds = new Array();
  21637. /**
  21638. * @hidden Internal use only.
  21639. */
  21640. _this._includedOnlyMeshesIds = new Array();
  21641. _this.getScene().addLight(_this);
  21642. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21643. _this._buildUniformLayout();
  21644. _this.includedOnlyMeshes = new Array();
  21645. _this.excludedMeshes = new Array();
  21646. _this._resyncMeshes();
  21647. return _this;
  21648. }
  21649. Object.defineProperty(Light.prototype, "range", {
  21650. /**
  21651. * Defines how far from the source the light is impacting in scene units.
  21652. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21653. */
  21654. get: function () {
  21655. return this._range;
  21656. },
  21657. /**
  21658. * Defines how far from the source the light is impacting in scene units.
  21659. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21660. */
  21661. set: function (value) {
  21662. this._range = value;
  21663. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21664. },
  21665. enumerable: true,
  21666. configurable: true
  21667. });
  21668. Object.defineProperty(Light.prototype, "intensityMode", {
  21669. /**
  21670. * Gets the photometric scale used to interpret the intensity.
  21671. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21672. */
  21673. get: function () {
  21674. return this._intensityMode;
  21675. },
  21676. /**
  21677. * Sets the photometric scale used to interpret the intensity.
  21678. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21679. */
  21680. set: function (value) {
  21681. this._intensityMode = value;
  21682. this._computePhotometricScale();
  21683. },
  21684. enumerable: true,
  21685. configurable: true
  21686. });
  21687. ;
  21688. ;
  21689. Object.defineProperty(Light.prototype, "radius", {
  21690. /**
  21691. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21692. */
  21693. get: function () {
  21694. return this._radius;
  21695. },
  21696. /**
  21697. * sets the light radius used by PBR Materials to simulate soft area lights.
  21698. */
  21699. set: function (value) {
  21700. this._radius = value;
  21701. this._computePhotometricScale();
  21702. },
  21703. enumerable: true,
  21704. configurable: true
  21705. });
  21706. ;
  21707. ;
  21708. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21709. /**
  21710. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21711. * the current shadow generator.
  21712. */
  21713. get: function () {
  21714. return this._shadowEnabled;
  21715. },
  21716. /**
  21717. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21718. * the current shadow generator.
  21719. */
  21720. set: function (value) {
  21721. if (this._shadowEnabled === value) {
  21722. return;
  21723. }
  21724. this._shadowEnabled = value;
  21725. this._markMeshesAsLightDirty();
  21726. },
  21727. enumerable: true,
  21728. configurable: true
  21729. });
  21730. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21731. /**
  21732. * Gets the only meshes impacted by this light.
  21733. */
  21734. get: function () {
  21735. return this._includedOnlyMeshes;
  21736. },
  21737. /**
  21738. * Sets the only meshes impacted by this light.
  21739. */
  21740. set: function (value) {
  21741. this._includedOnlyMeshes = value;
  21742. this._hookArrayForIncludedOnly(value);
  21743. },
  21744. enumerable: true,
  21745. configurable: true
  21746. });
  21747. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21748. /**
  21749. * Gets the meshes not impacted by this light.
  21750. */
  21751. get: function () {
  21752. return this._excludedMeshes;
  21753. },
  21754. /**
  21755. * Sets the meshes not impacted by this light.
  21756. */
  21757. set: function (value) {
  21758. this._excludedMeshes = value;
  21759. this._hookArrayForExcluded(value);
  21760. },
  21761. enumerable: true,
  21762. configurable: true
  21763. });
  21764. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21765. /**
  21766. * Gets the layer id use to find what meshes are not impacted by the light.
  21767. * Inactive if 0
  21768. */
  21769. get: function () {
  21770. return this._excludeWithLayerMask;
  21771. },
  21772. /**
  21773. * Sets the layer id use to find what meshes are not impacted by the light.
  21774. * Inactive if 0
  21775. */
  21776. set: function (value) {
  21777. this._excludeWithLayerMask = value;
  21778. this._resyncMeshes();
  21779. },
  21780. enumerable: true,
  21781. configurable: true
  21782. });
  21783. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21784. /**
  21785. * Gets the layer id use to find what meshes are impacted by the light.
  21786. * Inactive if 0
  21787. */
  21788. get: function () {
  21789. return this._includeOnlyWithLayerMask;
  21790. },
  21791. /**
  21792. * Sets the layer id use to find what meshes are impacted by the light.
  21793. * Inactive if 0
  21794. */
  21795. set: function (value) {
  21796. this._includeOnlyWithLayerMask = value;
  21797. this._resyncMeshes();
  21798. },
  21799. enumerable: true,
  21800. configurable: true
  21801. });
  21802. Object.defineProperty(Light.prototype, "lightmapMode", {
  21803. /**
  21804. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21805. */
  21806. get: function () {
  21807. return this._lightmapMode;
  21808. },
  21809. /**
  21810. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21811. */
  21812. set: function (value) {
  21813. if (this._lightmapMode === value) {
  21814. return;
  21815. }
  21816. this._lightmapMode = value;
  21817. this._markMeshesAsLightDirty();
  21818. },
  21819. enumerable: true,
  21820. configurable: true
  21821. });
  21822. /**
  21823. * Returns the string "Light".
  21824. * @returns the class name
  21825. */
  21826. Light.prototype.getClassName = function () {
  21827. return "Light";
  21828. };
  21829. /**
  21830. * Converts the light information to a readable string for debug purpose.
  21831. * @param fullDetails Supports for multiple levels of logging within scene loading
  21832. * @returns the human readable light info
  21833. */
  21834. Light.prototype.toString = function (fullDetails) {
  21835. var ret = "Name: " + this.name;
  21836. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21837. if (this.animations) {
  21838. for (var i = 0; i < this.animations.length; i++) {
  21839. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21840. }
  21841. }
  21842. if (fullDetails) {
  21843. }
  21844. return ret;
  21845. };
  21846. /** @hidden */
  21847. Light.prototype._syncParentEnabledState = function () {
  21848. _super.prototype._syncParentEnabledState.call(this);
  21849. this._resyncMeshes();
  21850. };
  21851. /**
  21852. * Set the enabled state of this node.
  21853. * @param value - the new enabled state
  21854. */
  21855. Light.prototype.setEnabled = function (value) {
  21856. _super.prototype.setEnabled.call(this, value);
  21857. this._resyncMeshes();
  21858. };
  21859. /**
  21860. * Returns the Light associated shadow generator if any.
  21861. * @return the associated shadow generator.
  21862. */
  21863. Light.prototype.getShadowGenerator = function () {
  21864. return this._shadowGenerator;
  21865. };
  21866. /**
  21867. * Returns a Vector3, the absolute light position in the World.
  21868. * @returns the world space position of the light
  21869. */
  21870. Light.prototype.getAbsolutePosition = function () {
  21871. return BABYLON.Vector3.Zero();
  21872. };
  21873. /**
  21874. * Specifies if the light will affect the passed mesh.
  21875. * @param mesh The mesh to test against the light
  21876. * @return true the mesh is affected otherwise, false.
  21877. */
  21878. Light.prototype.canAffectMesh = function (mesh) {
  21879. if (!mesh) {
  21880. return true;
  21881. }
  21882. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21883. return false;
  21884. }
  21885. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21886. return false;
  21887. }
  21888. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21889. return false;
  21890. }
  21891. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21892. return false;
  21893. }
  21894. return true;
  21895. };
  21896. /**
  21897. * Sort function to order lights for rendering.
  21898. * @param a First Light object to compare to second.
  21899. * @param b Second Light object to compare first.
  21900. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21901. */
  21902. Light.CompareLightsPriority = function (a, b) {
  21903. //shadow-casting lights have priority over non-shadow-casting lights
  21904. //the renderPrioirty is a secondary sort criterion
  21905. if (a.shadowEnabled !== b.shadowEnabled) {
  21906. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21907. }
  21908. return b.renderPriority - a.renderPriority;
  21909. };
  21910. /**
  21911. * Releases resources associated with this node.
  21912. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21913. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21914. */
  21915. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21916. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21917. if (this._shadowGenerator) {
  21918. this._shadowGenerator.dispose();
  21919. this._shadowGenerator = null;
  21920. }
  21921. // Animations
  21922. this.getScene().stopAnimation(this);
  21923. // Remove from meshes
  21924. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21925. var mesh = _a[_i];
  21926. mesh._removeLightSource(this);
  21927. }
  21928. this._uniformBuffer.dispose();
  21929. // Remove from scene
  21930. this.getScene().removeLight(this);
  21931. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21932. };
  21933. /**
  21934. * Returns the light type ID (integer).
  21935. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21936. */
  21937. Light.prototype.getTypeID = function () {
  21938. return 0;
  21939. };
  21940. /**
  21941. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21942. * @returns the scaled intensity in intensity mode unit
  21943. */
  21944. Light.prototype.getScaledIntensity = function () {
  21945. return this._photometricScale * this.intensity;
  21946. };
  21947. /**
  21948. * Returns a new Light object, named "name", from the current one.
  21949. * @param name The name of the cloned light
  21950. * @returns the new created light
  21951. */
  21952. Light.prototype.clone = function (name) {
  21953. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21954. if (!constructor) {
  21955. return null;
  21956. }
  21957. return BABYLON.SerializationHelper.Clone(constructor, this);
  21958. };
  21959. /**
  21960. * Serializes the current light into a Serialization object.
  21961. * @returns the serialized object.
  21962. */
  21963. Light.prototype.serialize = function () {
  21964. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21965. // Type
  21966. serializationObject.type = this.getTypeID();
  21967. // Parent
  21968. if (this.parent) {
  21969. serializationObject.parentId = this.parent.id;
  21970. }
  21971. // Inclusion / exclusions
  21972. if (this.excludedMeshes.length > 0) {
  21973. serializationObject.excludedMeshesIds = [];
  21974. this.excludedMeshes.forEach(function (mesh) {
  21975. serializationObject.excludedMeshesIds.push(mesh.id);
  21976. });
  21977. }
  21978. if (this.includedOnlyMeshes.length > 0) {
  21979. serializationObject.includedOnlyMeshesIds = [];
  21980. this.includedOnlyMeshes.forEach(function (mesh) {
  21981. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21982. });
  21983. }
  21984. // Animations
  21985. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21986. serializationObject.ranges = this.serializeAnimationRanges();
  21987. return serializationObject;
  21988. };
  21989. /**
  21990. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21991. * This new light is named "name" and added to the passed scene.
  21992. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21993. * @param name The friendly name of the light
  21994. * @param scene The scene the new light will belong to
  21995. * @returns the constructor function
  21996. */
  21997. Light.GetConstructorFromName = function (type, name, scene) {
  21998. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21999. if (constructorFunc) {
  22000. return constructorFunc;
  22001. }
  22002. // Default to no light for none present once.
  22003. return null;
  22004. };
  22005. /**
  22006. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22007. * @param parsedLight The JSON representation of the light
  22008. * @param scene The scene to create the parsed light in
  22009. * @returns the created light after parsing
  22010. */
  22011. Light.Parse = function (parsedLight, scene) {
  22012. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22013. if (!constructor) {
  22014. return null;
  22015. }
  22016. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22017. // Inclusion / exclusions
  22018. if (parsedLight.excludedMeshesIds) {
  22019. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22020. }
  22021. if (parsedLight.includedOnlyMeshesIds) {
  22022. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22023. }
  22024. // Parent
  22025. if (parsedLight.parentId) {
  22026. light._waitingParentId = parsedLight.parentId;
  22027. }
  22028. // Animations
  22029. if (parsedLight.animations) {
  22030. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22031. var parsedAnimation = parsedLight.animations[animationIndex];
  22032. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22033. }
  22034. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22035. }
  22036. if (parsedLight.autoAnimate) {
  22037. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22038. }
  22039. return light;
  22040. };
  22041. Light.prototype._hookArrayForExcluded = function (array) {
  22042. var _this = this;
  22043. var oldPush = array.push;
  22044. array.push = function () {
  22045. var items = [];
  22046. for (var _i = 0; _i < arguments.length; _i++) {
  22047. items[_i] = arguments[_i];
  22048. }
  22049. var result = oldPush.apply(array, items);
  22050. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22051. var item = items_1[_a];
  22052. item._resyncLighSource(_this);
  22053. }
  22054. return result;
  22055. };
  22056. var oldSplice = array.splice;
  22057. array.splice = function (index, deleteCount) {
  22058. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22059. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22060. var item = deleted_1[_i];
  22061. item._resyncLighSource(_this);
  22062. }
  22063. return deleted;
  22064. };
  22065. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22066. var item = array_1[_i];
  22067. item._resyncLighSource(this);
  22068. }
  22069. };
  22070. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22071. var _this = this;
  22072. var oldPush = array.push;
  22073. array.push = function () {
  22074. var items = [];
  22075. for (var _i = 0; _i < arguments.length; _i++) {
  22076. items[_i] = arguments[_i];
  22077. }
  22078. var result = oldPush.apply(array, items);
  22079. _this._resyncMeshes();
  22080. return result;
  22081. };
  22082. var oldSplice = array.splice;
  22083. array.splice = function (index, deleteCount) {
  22084. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22085. _this._resyncMeshes();
  22086. return deleted;
  22087. };
  22088. this._resyncMeshes();
  22089. };
  22090. Light.prototype._resyncMeshes = function () {
  22091. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22092. var mesh = _a[_i];
  22093. mesh._resyncLighSource(this);
  22094. }
  22095. };
  22096. /**
  22097. * Forces the meshes to update their light related information in their rendering used effects
  22098. * @hidden Internal Use Only
  22099. */
  22100. Light.prototype._markMeshesAsLightDirty = function () {
  22101. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22102. var mesh = _a[_i];
  22103. if (mesh._lightSources.indexOf(this) !== -1) {
  22104. mesh._markSubMeshesAsLightDirty();
  22105. }
  22106. }
  22107. };
  22108. /**
  22109. * Recomputes the cached photometric scale if needed.
  22110. */
  22111. Light.prototype._computePhotometricScale = function () {
  22112. this._photometricScale = this._getPhotometricScale();
  22113. this.getScene().resetCachedMaterial();
  22114. };
  22115. /**
  22116. * Returns the Photometric Scale according to the light type and intensity mode.
  22117. */
  22118. Light.prototype._getPhotometricScale = function () {
  22119. var photometricScale = 0.0;
  22120. var lightTypeID = this.getTypeID();
  22121. //get photometric mode
  22122. var photometricMode = this.intensityMode;
  22123. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22124. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22125. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22126. }
  22127. else {
  22128. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22129. }
  22130. }
  22131. //compute photometric scale
  22132. switch (lightTypeID) {
  22133. case Light.LIGHTTYPEID_POINTLIGHT:
  22134. case Light.LIGHTTYPEID_SPOTLIGHT:
  22135. switch (photometricMode) {
  22136. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22137. photometricScale = 1.0 / (4.0 * Math.PI);
  22138. break;
  22139. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22140. photometricScale = 1.0;
  22141. break;
  22142. case Light.INTENSITYMODE_LUMINANCE:
  22143. photometricScale = this.radius * this.radius;
  22144. break;
  22145. }
  22146. break;
  22147. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22148. switch (photometricMode) {
  22149. case Light.INTENSITYMODE_ILLUMINANCE:
  22150. photometricScale = 1.0;
  22151. break;
  22152. case Light.INTENSITYMODE_LUMINANCE:
  22153. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22154. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22155. var apexAngleRadians = this.radius;
  22156. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22157. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22158. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22159. photometricScale = solidAngle;
  22160. break;
  22161. }
  22162. break;
  22163. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22164. // No fall off in hemisperic light.
  22165. photometricScale = 1.0;
  22166. break;
  22167. }
  22168. return photometricScale;
  22169. };
  22170. /**
  22171. * Reorder the light in the scene according to their defined priority.
  22172. * @hidden Internal Use Only
  22173. */
  22174. Light.prototype._reorderLightsInScene = function () {
  22175. var scene = this.getScene();
  22176. if (this._renderPriority != 0) {
  22177. scene.requireLightSorting = true;
  22178. }
  22179. this.getScene().sortLightsByPriority();
  22180. };
  22181. /**
  22182. * Falloff Default: light is falling off following the material specification:
  22183. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22184. */
  22185. Light.FALLOFF_DEFAULT = 0;
  22186. /**
  22187. * Falloff Physical: light is falling off following the inverse squared distance law.
  22188. */
  22189. Light.FALLOFF_PHYSICAL = 1;
  22190. /**
  22191. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22192. * to enhance interoperability with other engines.
  22193. */
  22194. Light.FALLOFF_GLTF = 2;
  22195. /**
  22196. * Falloff Standard: light is falling off like in the standard material
  22197. * to enhance interoperability with other materials.
  22198. */
  22199. Light.FALLOFF_STANDARD = 3;
  22200. //lightmapMode Consts
  22201. /**
  22202. * If every light affecting the material is in this lightmapMode,
  22203. * material.lightmapTexture adds or multiplies
  22204. * (depends on material.useLightmapAsShadowmap)
  22205. * after every other light calculations.
  22206. */
  22207. Light.LIGHTMAP_DEFAULT = 0;
  22208. /**
  22209. * material.lightmapTexture as only diffuse lighting from this light
  22210. * adds only specular lighting from this light
  22211. * adds dynamic shadows
  22212. */
  22213. Light.LIGHTMAP_SPECULAR = 1;
  22214. /**
  22215. * material.lightmapTexture as only lighting
  22216. * no light calculation from this light
  22217. * only adds dynamic shadows from this light
  22218. */
  22219. Light.LIGHTMAP_SHADOWSONLY = 2;
  22220. // Intensity Mode Consts
  22221. /**
  22222. * Each light type uses the default quantity according to its type:
  22223. * point/spot lights use luminous intensity
  22224. * directional lights use illuminance
  22225. */
  22226. Light.INTENSITYMODE_AUTOMATIC = 0;
  22227. /**
  22228. * lumen (lm)
  22229. */
  22230. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22231. /**
  22232. * candela (lm/sr)
  22233. */
  22234. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22235. /**
  22236. * lux (lm/m^2)
  22237. */
  22238. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22239. /**
  22240. * nit (cd/m^2)
  22241. */
  22242. Light.INTENSITYMODE_LUMINANCE = 4;
  22243. // Light types ids const.
  22244. /**
  22245. * Light type const id of the point light.
  22246. */
  22247. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22248. /**
  22249. * Light type const id of the directional light.
  22250. */
  22251. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22252. /**
  22253. * Light type const id of the spot light.
  22254. */
  22255. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22256. /**
  22257. * Light type const id of the hemispheric light.
  22258. */
  22259. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22260. __decorate([
  22261. BABYLON.serializeAsColor3()
  22262. ], Light.prototype, "diffuse", void 0);
  22263. __decorate([
  22264. BABYLON.serializeAsColor3()
  22265. ], Light.prototype, "specular", void 0);
  22266. __decorate([
  22267. BABYLON.serialize()
  22268. ], Light.prototype, "falloffType", void 0);
  22269. __decorate([
  22270. BABYLON.serialize()
  22271. ], Light.prototype, "intensity", void 0);
  22272. __decorate([
  22273. BABYLON.serialize()
  22274. ], Light.prototype, "range", null);
  22275. __decorate([
  22276. BABYLON.serialize()
  22277. ], Light.prototype, "intensityMode", null);
  22278. __decorate([
  22279. BABYLON.serialize()
  22280. ], Light.prototype, "radius", null);
  22281. __decorate([
  22282. BABYLON.serialize()
  22283. ], Light.prototype, "_renderPriority", void 0);
  22284. __decorate([
  22285. BABYLON.expandToProperty("_reorderLightsInScene")
  22286. ], Light.prototype, "renderPriority", void 0);
  22287. __decorate([
  22288. BABYLON.serialize("shadowEnabled")
  22289. ], Light.prototype, "_shadowEnabled", void 0);
  22290. __decorate([
  22291. BABYLON.serialize("excludeWithLayerMask")
  22292. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22293. __decorate([
  22294. BABYLON.serialize("includeOnlyWithLayerMask")
  22295. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22296. __decorate([
  22297. BABYLON.serialize("lightmapMode")
  22298. ], Light.prototype, "_lightmapMode", void 0);
  22299. return Light;
  22300. }(BABYLON.Node));
  22301. BABYLON.Light = Light;
  22302. })(BABYLON || (BABYLON = {}));
  22303. //# sourceMappingURL=babylon.light.js.map
  22304. var BABYLON;
  22305. (function (BABYLON) {
  22306. /**
  22307. * This is the base class of all the camera used in the application.
  22308. * @see http://doc.babylonjs.com/features/cameras
  22309. */
  22310. var Camera = /** @class */ (function (_super) {
  22311. __extends(Camera, _super);
  22312. /**
  22313. * Instantiates a new camera object.
  22314. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22315. * @see http://doc.babylonjs.com/features/cameras
  22316. * @param name Defines the name of the camera in the scene
  22317. * @param position Defines the position of the camera
  22318. * @param scene Defines the scene the camera belongs too
  22319. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22320. */
  22321. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22322. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22323. var _this = _super.call(this, name, scene) || this;
  22324. /**
  22325. * The vector the camera should consider as up.
  22326. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22327. */
  22328. _this.upVector = BABYLON.Vector3.Up();
  22329. /**
  22330. * Define the current limit on the left side for an orthographic camera
  22331. * In scene unit
  22332. */
  22333. _this.orthoLeft = null;
  22334. /**
  22335. * Define the current limit on the right side for an orthographic camera
  22336. * In scene unit
  22337. */
  22338. _this.orthoRight = null;
  22339. /**
  22340. * Define the current limit on the bottom side for an orthographic camera
  22341. * In scene unit
  22342. */
  22343. _this.orthoBottom = null;
  22344. /**
  22345. * Define the current limit on the top side for an orthographic camera
  22346. * In scene unit
  22347. */
  22348. _this.orthoTop = null;
  22349. /**
  22350. * Field Of View is set in Radians. (default is 0.8)
  22351. */
  22352. _this.fov = 0.8;
  22353. /**
  22354. * Define the minimum distance the camera can see from.
  22355. * This is important to note that the depth buffer are not infinite and the closer it starts
  22356. * the more your scene might encounter depth fighting issue.
  22357. */
  22358. _this.minZ = 1;
  22359. /**
  22360. * Define the maximum distance the camera can see to.
  22361. * This is important to note that the depth buffer are not infinite and the further it end
  22362. * the more your scene might encounter depth fighting issue.
  22363. */
  22364. _this.maxZ = 10000.0;
  22365. /**
  22366. * Define the default inertia of the camera.
  22367. * This helps giving a smooth feeling to the camera movement.
  22368. */
  22369. _this.inertia = 0.9;
  22370. /**
  22371. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22372. */
  22373. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22374. /**
  22375. * Define wether the camera is intermediate.
  22376. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22377. */
  22378. _this.isIntermediate = false;
  22379. /**
  22380. * Define the viewport of the camera.
  22381. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22382. */
  22383. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22384. /**
  22385. * Restricts the camera to viewing objects with the same layerMask.
  22386. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22387. */
  22388. _this.layerMask = 0x0FFFFFFF;
  22389. /**
  22390. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22391. */
  22392. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22393. /**
  22394. * Rig mode of the camera.
  22395. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22396. * This is normally controlled byt the camera themselves as internal use.
  22397. */
  22398. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22399. /**
  22400. * Defines the list of custom render target the camera should render to.
  22401. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22402. * else in the scene.
  22403. */
  22404. _this.customRenderTargets = new Array();
  22405. /**
  22406. * Observable triggered when the camera view matrix has changed.
  22407. */
  22408. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22409. /**
  22410. * Observable triggered when the camera Projection matrix has changed.
  22411. */
  22412. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22413. /**
  22414. * Observable triggered when the inputs have been processed.
  22415. */
  22416. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22417. /**
  22418. * Observable triggered when reset has been called and applied to the camera.
  22419. */
  22420. _this.onRestoreStateObservable = new BABYLON.Observable();
  22421. /** @hidden */
  22422. _this._rigCameras = new Array();
  22423. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22424. /** @hidden */
  22425. _this._skipRendering = false;
  22426. /** @hidden */
  22427. _this._projectionMatrix = new BABYLON.Matrix();
  22428. /** @hidden */
  22429. _this._postProcesses = new Array();
  22430. /** @hidden */
  22431. _this._activeMeshes = new BABYLON.SmartArray(256);
  22432. _this._globalPosition = BABYLON.Vector3.Zero();
  22433. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22434. _this._doNotComputeProjectionMatrix = false;
  22435. _this._transformMatrix = BABYLON.Matrix.Zero();
  22436. _this._refreshFrustumPlanes = true;
  22437. _this.getScene().addCamera(_this);
  22438. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22439. _this.getScene().activeCamera = _this;
  22440. }
  22441. _this.position = position;
  22442. return _this;
  22443. }
  22444. /**
  22445. * Store current camera state (fov, position, etc..)
  22446. * @returns the camera
  22447. */
  22448. Camera.prototype.storeState = function () {
  22449. this._stateStored = true;
  22450. this._storedFov = this.fov;
  22451. return this;
  22452. };
  22453. /**
  22454. * Restores the camera state values if it has been stored. You must call storeState() first
  22455. */
  22456. Camera.prototype._restoreStateValues = function () {
  22457. if (!this._stateStored) {
  22458. return false;
  22459. }
  22460. this.fov = this._storedFov;
  22461. return true;
  22462. };
  22463. /**
  22464. * Restored camera state. You must call storeState() first.
  22465. * @returns true if restored and false otherwise
  22466. */
  22467. Camera.prototype.restoreState = function () {
  22468. if (this._restoreStateValues()) {
  22469. this.onRestoreStateObservable.notifyObservers(this);
  22470. return true;
  22471. }
  22472. return false;
  22473. };
  22474. /**
  22475. * Gets the class name of the camera.
  22476. * @returns the class name
  22477. */
  22478. Camera.prototype.getClassName = function () {
  22479. return "Camera";
  22480. };
  22481. /**
  22482. * Gets a string representation of the camera usefull for debug purpose.
  22483. * @param fullDetails Defines that a more verboe level of logging is required
  22484. * @returns the string representation
  22485. */
  22486. Camera.prototype.toString = function (fullDetails) {
  22487. var ret = "Name: " + this.name;
  22488. ret += ", type: " + this.getClassName();
  22489. if (this.animations) {
  22490. for (var i = 0; i < this.animations.length; i++) {
  22491. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22492. }
  22493. }
  22494. if (fullDetails) {
  22495. }
  22496. return ret;
  22497. };
  22498. Object.defineProperty(Camera.prototype, "globalPosition", {
  22499. /**
  22500. * Gets the current world space position of the camera.
  22501. */
  22502. get: function () {
  22503. return this._globalPosition;
  22504. },
  22505. enumerable: true,
  22506. configurable: true
  22507. });
  22508. /**
  22509. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  22510. * @returns the active meshe list
  22511. */
  22512. Camera.prototype.getActiveMeshes = function () {
  22513. return this._activeMeshes;
  22514. };
  22515. /**
  22516. * Check wether a mesh is part of the current active mesh list of the camera
  22517. * @param mesh Defines the mesh to check
  22518. * @returns true if active, false otherwise
  22519. */
  22520. Camera.prototype.isActiveMesh = function (mesh) {
  22521. return (this._activeMeshes.indexOf(mesh) !== -1);
  22522. };
  22523. /**
  22524. * Is this camera ready to be used/rendered
  22525. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22526. * @return true if the camera is ready
  22527. */
  22528. Camera.prototype.isReady = function (completeCheck) {
  22529. if (completeCheck === void 0) { completeCheck = false; }
  22530. if (completeCheck) {
  22531. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22532. var pp = _a[_i];
  22533. if (pp && !pp.isReady()) {
  22534. return false;
  22535. }
  22536. }
  22537. }
  22538. return _super.prototype.isReady.call(this, completeCheck);
  22539. };
  22540. /** @hidden */
  22541. Camera.prototype._initCache = function () {
  22542. _super.prototype._initCache.call(this);
  22543. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22544. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22545. this._cache.mode = undefined;
  22546. this._cache.minZ = undefined;
  22547. this._cache.maxZ = undefined;
  22548. this._cache.fov = undefined;
  22549. this._cache.fovMode = undefined;
  22550. this._cache.aspectRatio = undefined;
  22551. this._cache.orthoLeft = undefined;
  22552. this._cache.orthoRight = undefined;
  22553. this._cache.orthoBottom = undefined;
  22554. this._cache.orthoTop = undefined;
  22555. this._cache.renderWidth = undefined;
  22556. this._cache.renderHeight = undefined;
  22557. };
  22558. /** @hidden */
  22559. Camera.prototype._updateCache = function (ignoreParentClass) {
  22560. if (!ignoreParentClass) {
  22561. _super.prototype._updateCache.call(this);
  22562. }
  22563. this._cache.position.copyFrom(this.position);
  22564. this._cache.upVector.copyFrom(this.upVector);
  22565. };
  22566. /** @hidden */
  22567. Camera.prototype._isSynchronized = function () {
  22568. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22569. };
  22570. /** @hidden */
  22571. Camera.prototype._isSynchronizedViewMatrix = function () {
  22572. if (!_super.prototype._isSynchronized.call(this))
  22573. return false;
  22574. return this._cache.position.equals(this.position)
  22575. && this._cache.upVector.equals(this.upVector)
  22576. && this.isSynchronizedWithParent();
  22577. };
  22578. /** @hidden */
  22579. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22580. var check = this._cache.mode === this.mode
  22581. && this._cache.minZ === this.minZ
  22582. && this._cache.maxZ === this.maxZ;
  22583. if (!check) {
  22584. return false;
  22585. }
  22586. var engine = this.getEngine();
  22587. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22588. check = this._cache.fov === this.fov
  22589. && this._cache.fovMode === this.fovMode
  22590. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22591. }
  22592. else {
  22593. check = this._cache.orthoLeft === this.orthoLeft
  22594. && this._cache.orthoRight === this.orthoRight
  22595. && this._cache.orthoBottom === this.orthoBottom
  22596. && this._cache.orthoTop === this.orthoTop
  22597. && this._cache.renderWidth === engine.getRenderWidth()
  22598. && this._cache.renderHeight === engine.getRenderHeight();
  22599. }
  22600. return check;
  22601. };
  22602. /**
  22603. * Attach the input controls to a specific dom element to get the input from.
  22604. * @param element Defines the element the controls should be listened from
  22605. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  22606. */
  22607. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22608. };
  22609. /**
  22610. * Detach the current controls from the specified dom element.
  22611. * @param element Defines the element to stop listening the inputs from
  22612. */
  22613. Camera.prototype.detachControl = function (element) {
  22614. };
  22615. /**
  22616. * Update the camera state according to the different inputs gathered during the frame.
  22617. */
  22618. Camera.prototype.update = function () {
  22619. this._checkInputs();
  22620. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22621. this._updateRigCameras();
  22622. }
  22623. };
  22624. /** @hidden */
  22625. Camera.prototype._checkInputs = function () {
  22626. this.onAfterCheckInputsObservable.notifyObservers(this);
  22627. };
  22628. Object.defineProperty(Camera.prototype, "rigCameras", {
  22629. /** @hidden */
  22630. get: function () {
  22631. return this._rigCameras;
  22632. },
  22633. enumerable: true,
  22634. configurable: true
  22635. });
  22636. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22637. get: function () {
  22638. return this._rigPostProcess;
  22639. },
  22640. enumerable: true,
  22641. configurable: true
  22642. });
  22643. /**
  22644. * Internal, gets the first post proces.
  22645. * @returns the first post process to be run on this camera.
  22646. */
  22647. Camera.prototype._getFirstPostProcess = function () {
  22648. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22649. if (this._postProcesses[ppIndex] !== null) {
  22650. return this._postProcesses[ppIndex];
  22651. }
  22652. }
  22653. return null;
  22654. };
  22655. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22656. // invalidate framebuffer
  22657. var firstPostProcess = this._getFirstPostProcess();
  22658. if (firstPostProcess) {
  22659. firstPostProcess.markTextureDirty();
  22660. }
  22661. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22662. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22663. var cam = this._rigCameras[i];
  22664. var rigPostProcess = cam._rigPostProcess;
  22665. // for VR rig, there does not have to be a post process
  22666. if (rigPostProcess) {
  22667. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22668. if (isPass) {
  22669. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22670. cam.isIntermediate = this._postProcesses.length === 0;
  22671. }
  22672. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22673. rigPostProcess.markTextureDirty();
  22674. }
  22675. else {
  22676. cam._postProcesses = this._postProcesses.slice(0);
  22677. }
  22678. }
  22679. };
  22680. /**
  22681. * Attach a post process to the camera.
  22682. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22683. * @param postProcess The post process to attach to the camera
  22684. * @param insertAt The position of the post process in case several of them are in use in the scene
  22685. * @returns the position the post process has been inserted at
  22686. */
  22687. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22688. if (insertAt === void 0) { insertAt = null; }
  22689. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22690. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22691. return 0;
  22692. }
  22693. if (insertAt == null || insertAt < 0) {
  22694. this._postProcesses.push(postProcess);
  22695. }
  22696. else if (this._postProcesses[insertAt] === null) {
  22697. this._postProcesses[insertAt] = postProcess;
  22698. }
  22699. else {
  22700. this._postProcesses.splice(insertAt, 0, postProcess);
  22701. }
  22702. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22703. return this._postProcesses.indexOf(postProcess);
  22704. };
  22705. /**
  22706. * Detach a post process to the camera.
  22707. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22708. * @param postProcess The post process to detach from the camera
  22709. */
  22710. Camera.prototype.detachPostProcess = function (postProcess) {
  22711. var idx = this._postProcesses.indexOf(postProcess);
  22712. if (idx !== -1) {
  22713. this._postProcesses[idx] = null;
  22714. }
  22715. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22716. };
  22717. /**
  22718. * Gets the current world matrix of the camera
  22719. */
  22720. Camera.prototype.getWorldMatrix = function () {
  22721. if (this._isSynchronizedViewMatrix()) {
  22722. return this._worldMatrix;
  22723. }
  22724. // Getting the the view matrix will also compute the world matrix.
  22725. this.getViewMatrix();
  22726. return this._worldMatrix;
  22727. };
  22728. /** @hidden */
  22729. Camera.prototype._getViewMatrix = function () {
  22730. return BABYLON.Matrix.Identity();
  22731. };
  22732. /**
  22733. * Gets the current view matrix of the camera.
  22734. * @param force forces the camera to recompute the matrix without looking at the cached state
  22735. * @returns the view matrix
  22736. */
  22737. Camera.prototype.getViewMatrix = function (force) {
  22738. if (!force && this._isSynchronizedViewMatrix()) {
  22739. return this._computedViewMatrix;
  22740. }
  22741. this.updateCache();
  22742. this._computedViewMatrix = this._getViewMatrix();
  22743. this._currentRenderId = this.getScene().getRenderId();
  22744. this._childRenderId = this._currentRenderId;
  22745. this._refreshFrustumPlanes = true;
  22746. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22747. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22748. }
  22749. this.onViewMatrixChangedObservable.notifyObservers(this);
  22750. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22751. return this._computedViewMatrix;
  22752. };
  22753. /**
  22754. * Freeze the projection matrix.
  22755. * It will prevent the cache check of the camera projection compute and can speed up perf
  22756. * if no parameter of the camera are meant to change
  22757. * @param projection Defines manually a projection if necessary
  22758. */
  22759. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22760. this._doNotComputeProjectionMatrix = true;
  22761. if (projection !== undefined) {
  22762. this._projectionMatrix = projection;
  22763. }
  22764. };
  22765. ;
  22766. /**
  22767. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  22768. */
  22769. Camera.prototype.unfreezeProjectionMatrix = function () {
  22770. this._doNotComputeProjectionMatrix = false;
  22771. };
  22772. ;
  22773. /**
  22774. * Gets the current projection matrix of the camera.
  22775. * @param force forces the camera to recompute the matrix without looking at the cached state
  22776. * @returns the projection matrix
  22777. */
  22778. Camera.prototype.getProjectionMatrix = function (force) {
  22779. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22780. return this._projectionMatrix;
  22781. }
  22782. // Cache
  22783. this._cache.mode = this.mode;
  22784. this._cache.minZ = this.minZ;
  22785. this._cache.maxZ = this.maxZ;
  22786. // Matrix
  22787. this._refreshFrustumPlanes = true;
  22788. var engine = this.getEngine();
  22789. var scene = this.getScene();
  22790. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22791. this._cache.fov = this.fov;
  22792. this._cache.fovMode = this.fovMode;
  22793. this._cache.aspectRatio = engine.getAspectRatio(this);
  22794. if (this.minZ <= 0) {
  22795. this.minZ = 0.1;
  22796. }
  22797. if (scene.useRightHandedSystem) {
  22798. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22799. }
  22800. else {
  22801. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22802. }
  22803. }
  22804. else {
  22805. var halfWidth = engine.getRenderWidth() / 2.0;
  22806. var halfHeight = engine.getRenderHeight() / 2.0;
  22807. if (scene.useRightHandedSystem) {
  22808. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22809. }
  22810. else {
  22811. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22812. }
  22813. this._cache.orthoLeft = this.orthoLeft;
  22814. this._cache.orthoRight = this.orthoRight;
  22815. this._cache.orthoBottom = this.orthoBottom;
  22816. this._cache.orthoTop = this.orthoTop;
  22817. this._cache.renderWidth = engine.getRenderWidth();
  22818. this._cache.renderHeight = engine.getRenderHeight();
  22819. }
  22820. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22821. return this._projectionMatrix;
  22822. };
  22823. /**
  22824. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22825. * @returns a Matrix
  22826. */
  22827. Camera.prototype.getTransformationMatrix = function () {
  22828. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22829. return this._transformMatrix;
  22830. };
  22831. Camera.prototype._updateFrustumPlanes = function () {
  22832. if (!this._refreshFrustumPlanes) {
  22833. return;
  22834. }
  22835. this.getTransformationMatrix();
  22836. if (!this._frustumPlanes) {
  22837. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22838. }
  22839. else {
  22840. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22841. }
  22842. this._refreshFrustumPlanes = false;
  22843. };
  22844. /**
  22845. * Checks if a cullable object (mesh...) is in the camera frustum
  22846. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  22847. * @param target The object to check
  22848. * @returns true if the object is in frustum otherwise false
  22849. */
  22850. Camera.prototype.isInFrustum = function (target) {
  22851. this._updateFrustumPlanes();
  22852. return target.isInFrustum(this._frustumPlanes);
  22853. };
  22854. /**
  22855. * Checks if a cullable object (mesh...) is in the camera frustum
  22856. * Unlike isInFrustum this cheks the full bounding box
  22857. * @param target The object to check
  22858. * @returns true if the object is in frustum otherwise false
  22859. */
  22860. Camera.prototype.isCompletelyInFrustum = function (target) {
  22861. this._updateFrustumPlanes();
  22862. return target.isCompletelyInFrustum(this._frustumPlanes);
  22863. };
  22864. /**
  22865. * Gets a ray in the forward direction from the camera.
  22866. * @param length Defines the length of the ray to create
  22867. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  22868. * @param origin Defines the start point of the ray which defaults to the camera position
  22869. * @returns the forward ray
  22870. */
  22871. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22872. if (length === void 0) { length = 100; }
  22873. if (!transform) {
  22874. transform = this.getWorldMatrix();
  22875. }
  22876. if (!origin) {
  22877. origin = this.position;
  22878. }
  22879. var forward = new BABYLON.Vector3(0, 0, 1);
  22880. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22881. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22882. return new BABYLON.Ray(origin, direction, length);
  22883. };
  22884. /**
  22885. * Releases resources associated with this node.
  22886. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22887. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22888. */
  22889. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22890. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22891. // Observables
  22892. this.onViewMatrixChangedObservable.clear();
  22893. this.onProjectionMatrixChangedObservable.clear();
  22894. this.onAfterCheckInputsObservable.clear();
  22895. this.onRestoreStateObservable.clear();
  22896. // Inputs
  22897. if (this.inputs) {
  22898. this.inputs.clear();
  22899. }
  22900. // Animations
  22901. this.getScene().stopAnimation(this);
  22902. // Remove from scene
  22903. this.getScene().removeCamera(this);
  22904. while (this._rigCameras.length > 0) {
  22905. var camera = this._rigCameras.pop();
  22906. if (camera) {
  22907. camera.dispose();
  22908. }
  22909. }
  22910. // Postprocesses
  22911. if (this._rigPostProcess) {
  22912. this._rigPostProcess.dispose(this);
  22913. this._rigPostProcess = null;
  22914. this._postProcesses = [];
  22915. }
  22916. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22917. this._rigPostProcess = null;
  22918. this._postProcesses = [];
  22919. }
  22920. else {
  22921. var i = this._postProcesses.length;
  22922. while (--i >= 0) {
  22923. var postProcess = this._postProcesses[i];
  22924. if (postProcess) {
  22925. postProcess.dispose(this);
  22926. }
  22927. }
  22928. }
  22929. // Render targets
  22930. var i = this.customRenderTargets.length;
  22931. while (--i >= 0) {
  22932. this.customRenderTargets[i].dispose();
  22933. }
  22934. this.customRenderTargets = [];
  22935. // Active Meshes
  22936. this._activeMeshes.dispose();
  22937. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22938. };
  22939. Object.defineProperty(Camera.prototype, "leftCamera", {
  22940. /**
  22941. * Gets the left camera of a rig setup in case of Rigged Camera
  22942. */
  22943. get: function () {
  22944. if (this._rigCameras.length < 1) {
  22945. return null;
  22946. }
  22947. return this._rigCameras[0];
  22948. },
  22949. enumerable: true,
  22950. configurable: true
  22951. });
  22952. Object.defineProperty(Camera.prototype, "rightCamera", {
  22953. /**
  22954. * Gets the right camera of a rig setup in case of Rigged Camera
  22955. */
  22956. get: function () {
  22957. if (this._rigCameras.length < 2) {
  22958. return null;
  22959. }
  22960. return this._rigCameras[1];
  22961. },
  22962. enumerable: true,
  22963. configurable: true
  22964. });
  22965. /**
  22966. * Gets the left camera target of a rig setup in case of Rigged Camera
  22967. * @returns the target position
  22968. */
  22969. Camera.prototype.getLeftTarget = function () {
  22970. if (this._rigCameras.length < 1) {
  22971. return null;
  22972. }
  22973. return this._rigCameras[0].getTarget();
  22974. };
  22975. /**
  22976. * Gets the right camera target of a rig setup in case of Rigged Camera
  22977. * @returns the target position
  22978. */
  22979. Camera.prototype.getRightTarget = function () {
  22980. if (this._rigCameras.length < 2) {
  22981. return null;
  22982. }
  22983. return this._rigCameras[1].getTarget();
  22984. };
  22985. /**
  22986. * @hidden
  22987. */
  22988. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22989. if (this.cameraRigMode === mode) {
  22990. return;
  22991. }
  22992. while (this._rigCameras.length > 0) {
  22993. var camera = this._rigCameras.pop();
  22994. if (camera) {
  22995. camera.dispose();
  22996. }
  22997. }
  22998. this.cameraRigMode = mode;
  22999. this._cameraRigParams = {};
  23000. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23001. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23002. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23003. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23004. // create the rig cameras, unless none
  23005. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23006. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23007. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23008. if (leftCamera && rightCamera) {
  23009. this._rigCameras.push(leftCamera);
  23010. this._rigCameras.push(rightCamera);
  23011. }
  23012. }
  23013. switch (this.cameraRigMode) {
  23014. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23015. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23016. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23017. break;
  23018. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23019. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23020. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23021. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23022. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23023. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23024. break;
  23025. case Camera.RIG_MODE_VR:
  23026. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23027. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23028. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23029. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23030. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23031. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23032. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23033. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23034. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23035. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23036. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23037. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23038. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23039. if (metrics.compensateDistortion) {
  23040. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23041. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23042. }
  23043. break;
  23044. case Camera.RIG_MODE_WEBVR:
  23045. if (rigParams.vrDisplay) {
  23046. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23047. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23048. //Left eye
  23049. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23050. this._rigCameras[0].setCameraRigParameter("left", true);
  23051. //leaving this for future reference
  23052. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23053. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23054. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23055. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23056. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23057. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23058. this._rigCameras[0].parent = this;
  23059. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23060. //Right eye
  23061. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23062. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23063. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23064. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23065. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23066. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23067. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23068. this._rigCameras[1].parent = this;
  23069. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23070. if (Camera.UseAlternateWebVRRendering) {
  23071. this._rigCameras[1]._skipRendering = true;
  23072. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23073. }
  23074. }
  23075. break;
  23076. }
  23077. this._cascadePostProcessesToRigCams();
  23078. this.update();
  23079. };
  23080. Camera.prototype._getVRProjectionMatrix = function () {
  23081. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23082. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23083. return this._projectionMatrix;
  23084. };
  23085. Camera.prototype._updateCameraRotationMatrix = function () {
  23086. //Here for WebVR
  23087. };
  23088. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23089. //Here for WebVR
  23090. };
  23091. /**
  23092. * This function MUST be overwritten by the different WebVR cameras available.
  23093. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23094. */
  23095. Camera.prototype._getWebVRProjectionMatrix = function () {
  23096. return BABYLON.Matrix.Identity();
  23097. };
  23098. /**
  23099. * This function MUST be overwritten by the different WebVR cameras available.
  23100. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23101. */
  23102. Camera.prototype._getWebVRViewMatrix = function () {
  23103. return BABYLON.Matrix.Identity();
  23104. };
  23105. /** @hidden */
  23106. Camera.prototype.setCameraRigParameter = function (name, value) {
  23107. if (!this._cameraRigParams) {
  23108. this._cameraRigParams = {};
  23109. }
  23110. this._cameraRigParams[name] = value;
  23111. //provisionnally:
  23112. if (name === "interaxialDistance") {
  23113. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23114. }
  23115. };
  23116. /**
  23117. * needs to be overridden by children so sub has required properties to be copied
  23118. * @hidden
  23119. */
  23120. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23121. return null;
  23122. };
  23123. /**
  23124. * May need to be overridden by children
  23125. * @hidden
  23126. */
  23127. Camera.prototype._updateRigCameras = function () {
  23128. for (var i = 0; i < this._rigCameras.length; i++) {
  23129. this._rigCameras[i].minZ = this.minZ;
  23130. this._rigCameras[i].maxZ = this.maxZ;
  23131. this._rigCameras[i].fov = this.fov;
  23132. }
  23133. // only update viewport when ANAGLYPH
  23134. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23135. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23136. }
  23137. };
  23138. /** @hidden */
  23139. Camera.prototype._setupInputs = function () {
  23140. };
  23141. /**
  23142. * Serialiaze the camera setup to a json represention
  23143. * @returns the JSON representation
  23144. */
  23145. Camera.prototype.serialize = function () {
  23146. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23147. // Type
  23148. serializationObject.type = this.getClassName();
  23149. // Parent
  23150. if (this.parent) {
  23151. serializationObject.parentId = this.parent.id;
  23152. }
  23153. if (this.inputs) {
  23154. this.inputs.serialize(serializationObject);
  23155. }
  23156. // Animations
  23157. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23158. serializationObject.ranges = this.serializeAnimationRanges();
  23159. return serializationObject;
  23160. };
  23161. /**
  23162. * Clones the current camera.
  23163. * @param name The cloned camera name
  23164. * @returns the cloned camera
  23165. */
  23166. Camera.prototype.clone = function (name) {
  23167. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23168. };
  23169. /**
  23170. * Gets the direction of the camera relative to a given local axis.
  23171. * @param localAxis Defines the reference axis to provide a relative direction.
  23172. * @return the direction
  23173. */
  23174. Camera.prototype.getDirection = function (localAxis) {
  23175. var result = BABYLON.Vector3.Zero();
  23176. this.getDirectionToRef(localAxis, result);
  23177. return result;
  23178. };
  23179. /**
  23180. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23181. * @param localAxis Defines the reference axis to provide a relative direction.
  23182. * @param result Defines the vector to store the result in
  23183. */
  23184. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23185. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23186. };
  23187. /**
  23188. * Gets a camera constructor for a given camera type
  23189. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23190. * @param name The name of the camera the result will be able to instantiate
  23191. * @param scene The scene the result will construct the camera in
  23192. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23193. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23194. * @returns a factory method to construc the camera
  23195. */
  23196. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23197. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23198. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23199. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23200. interaxial_distance: interaxial_distance,
  23201. isStereoscopicSideBySide: isStereoscopicSideBySide
  23202. });
  23203. if (constructorFunc) {
  23204. return constructorFunc;
  23205. }
  23206. // Default to universal camera
  23207. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23208. };
  23209. /**
  23210. * Compute the world matrix of the camera.
  23211. * @returns the camera workd matrix
  23212. */
  23213. Camera.prototype.computeWorldMatrix = function () {
  23214. return this.getWorldMatrix();
  23215. };
  23216. /**
  23217. * Parse a JSON and creates the camera from the parsed information
  23218. * @param parsedCamera The JSON to parse
  23219. * @param scene The scene to instantiate the camera in
  23220. * @returns the newly constructed camera
  23221. */
  23222. Camera.Parse = function (parsedCamera, scene) {
  23223. var type = parsedCamera.type;
  23224. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23225. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23226. // Parent
  23227. if (parsedCamera.parentId) {
  23228. camera._waitingParentId = parsedCamera.parentId;
  23229. }
  23230. //If camera has an input manager, let it parse inputs settings
  23231. if (camera.inputs) {
  23232. camera.inputs.parse(parsedCamera);
  23233. camera._setupInputs();
  23234. }
  23235. if (camera.setPosition) { // need to force position
  23236. camera.position.copyFromFloats(0, 0, 0);
  23237. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23238. }
  23239. // Target
  23240. if (parsedCamera.target) {
  23241. if (camera.setTarget) {
  23242. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23243. }
  23244. }
  23245. // Apply 3d rig, when found
  23246. if (parsedCamera.cameraRigMode) {
  23247. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23248. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23249. }
  23250. // Animations
  23251. if (parsedCamera.animations) {
  23252. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23253. var parsedAnimation = parsedCamera.animations[animationIndex];
  23254. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23255. }
  23256. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23257. }
  23258. if (parsedCamera.autoAnimate) {
  23259. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23260. }
  23261. return camera;
  23262. };
  23263. /**
  23264. * This is the default projection mode used by the cameras.
  23265. * It helps recreating a feeling of perspective and better appreciate depth.
  23266. * This is the best way to simulate real life cameras.
  23267. */
  23268. Camera.PERSPECTIVE_CAMERA = 0;
  23269. /**
  23270. * This helps creating camera with an orthographic mode.
  23271. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  23272. */
  23273. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23274. /**
  23275. * This is the default FOV mode for perspective cameras.
  23276. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23277. */
  23278. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23279. /**
  23280. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23281. */
  23282. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23283. /**
  23284. * This specifies ther is no need for a camera rig.
  23285. * Basically only one eye is rendered corresponding to the camera.
  23286. */
  23287. Camera.RIG_MODE_NONE = 0;
  23288. /**
  23289. * Simulates a camera Rig with one blue eye and one red eye.
  23290. * This can be use with 3d blue and red glasses.
  23291. */
  23292. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23293. /**
  23294. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23295. */
  23296. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23297. /**
  23298. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23299. */
  23300. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23301. /**
  23302. * Defines that both eyes of the camera will be rendered over under each other.
  23303. */
  23304. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23305. /**
  23306. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23307. */
  23308. Camera.RIG_MODE_VR = 20;
  23309. /**
  23310. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23311. */
  23312. Camera.RIG_MODE_WEBVR = 21;
  23313. /**
  23314. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23315. */
  23316. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23317. /**
  23318. * @hidden
  23319. * Might be removed once multiview will be a thing
  23320. */
  23321. Camera.UseAlternateWebVRRendering = false;
  23322. __decorate([
  23323. BABYLON.serializeAsVector3()
  23324. ], Camera.prototype, "position", void 0);
  23325. __decorate([
  23326. BABYLON.serializeAsVector3()
  23327. ], Camera.prototype, "upVector", void 0);
  23328. __decorate([
  23329. BABYLON.serialize()
  23330. ], Camera.prototype, "orthoLeft", void 0);
  23331. __decorate([
  23332. BABYLON.serialize()
  23333. ], Camera.prototype, "orthoRight", void 0);
  23334. __decorate([
  23335. BABYLON.serialize()
  23336. ], Camera.prototype, "orthoBottom", void 0);
  23337. __decorate([
  23338. BABYLON.serialize()
  23339. ], Camera.prototype, "orthoTop", void 0);
  23340. __decorate([
  23341. BABYLON.serialize()
  23342. ], Camera.prototype, "fov", void 0);
  23343. __decorate([
  23344. BABYLON.serialize()
  23345. ], Camera.prototype, "minZ", void 0);
  23346. __decorate([
  23347. BABYLON.serialize()
  23348. ], Camera.prototype, "maxZ", void 0);
  23349. __decorate([
  23350. BABYLON.serialize()
  23351. ], Camera.prototype, "inertia", void 0);
  23352. __decorate([
  23353. BABYLON.serialize()
  23354. ], Camera.prototype, "mode", void 0);
  23355. __decorate([
  23356. BABYLON.serialize()
  23357. ], Camera.prototype, "layerMask", void 0);
  23358. __decorate([
  23359. BABYLON.serialize()
  23360. ], Camera.prototype, "fovMode", void 0);
  23361. __decorate([
  23362. BABYLON.serialize()
  23363. ], Camera.prototype, "cameraRigMode", void 0);
  23364. __decorate([
  23365. BABYLON.serialize()
  23366. ], Camera.prototype, "interaxialDistance", void 0);
  23367. __decorate([
  23368. BABYLON.serialize()
  23369. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23370. return Camera;
  23371. }(BABYLON.Node));
  23372. BABYLON.Camera = Camera;
  23373. })(BABYLON || (BABYLON = {}));
  23374. //# sourceMappingURL=babylon.camera.js.map
  23375. var BABYLON;
  23376. (function (BABYLON) {
  23377. /**
  23378. * This is the manager responsible of all the rendering for meshes sprites and particles.
  23379. * It is enable to manage the different groups as well as the different necessary sort functions.
  23380. * This should not be used directly aside of the few static configurations
  23381. */
  23382. var RenderingManager = /** @class */ (function () {
  23383. /**
  23384. * Instantiates a new rendering group for a particular scene
  23385. * @param scene Defines the scene the groups belongs to
  23386. */
  23387. function RenderingManager(scene) {
  23388. /**
  23389. * @hidden
  23390. */
  23391. this._useSceneAutoClearSetup = false;
  23392. this._renderingGroups = new Array();
  23393. this._autoClearDepthStencil = {};
  23394. this._customOpaqueSortCompareFn = {};
  23395. this._customAlphaTestSortCompareFn = {};
  23396. this._customTransparentSortCompareFn = {};
  23397. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23398. this._scene = scene;
  23399. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23400. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23401. }
  23402. }
  23403. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23404. if (depth === void 0) { depth = true; }
  23405. if (stencil === void 0) { stencil = true; }
  23406. if (this._depthStencilBufferAlreadyCleaned) {
  23407. return;
  23408. }
  23409. this._scene.getEngine().clear(null, false, depth, stencil);
  23410. this._depthStencilBufferAlreadyCleaned = true;
  23411. };
  23412. /**
  23413. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  23414. * @hidden
  23415. */
  23416. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23417. // Update the observable context (not null as it only goes away on dispose)
  23418. var info = this._renderingGroupInfo;
  23419. info.scene = this._scene;
  23420. info.camera = this._scene.activeCamera;
  23421. // Dispatch sprites
  23422. if (this._scene.spriteManagers && renderSprites) {
  23423. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23424. var manager = this._scene.spriteManagers[index];
  23425. this.dispatchSprites(manager);
  23426. }
  23427. }
  23428. // Render
  23429. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23430. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23431. var renderingGroup = this._renderingGroups[index];
  23432. if (!renderingGroup)
  23433. continue;
  23434. var renderingGroupMask = Math.pow(2, index);
  23435. info.renderingGroupId = index;
  23436. // Before Observable
  23437. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23438. // Clear depth/stencil if needed
  23439. if (RenderingManager.AUTOCLEAR) {
  23440. var autoClear = this._useSceneAutoClearSetup ?
  23441. this._scene.getAutoClearDepthStencilSetup(index) :
  23442. this._autoClearDepthStencil[index];
  23443. if (autoClear && autoClear.autoClear) {
  23444. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23445. }
  23446. }
  23447. // Render
  23448. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23449. var step = _a[_i];
  23450. step.action(index);
  23451. }
  23452. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23453. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23454. var step = _c[_b];
  23455. step.action(index);
  23456. }
  23457. // After Observable
  23458. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23459. }
  23460. };
  23461. /**
  23462. * Resets the different information of the group to prepare a new frame
  23463. * @hidden
  23464. */
  23465. RenderingManager.prototype.reset = function () {
  23466. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23467. var renderingGroup = this._renderingGroups[index];
  23468. if (renderingGroup) {
  23469. renderingGroup.prepare();
  23470. }
  23471. }
  23472. };
  23473. /**
  23474. * Dispose and release the group and its associated resources.
  23475. * @hidden
  23476. */
  23477. RenderingManager.prototype.dispose = function () {
  23478. this.freeRenderingGroups();
  23479. this._renderingGroups.length = 0;
  23480. this._renderingGroupInfo = null;
  23481. };
  23482. /**
  23483. * Clear the info related to rendering groups preventing retention points during dispose.
  23484. */
  23485. RenderingManager.prototype.freeRenderingGroups = function () {
  23486. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23487. var renderingGroup = this._renderingGroups[index];
  23488. if (renderingGroup) {
  23489. renderingGroup.dispose();
  23490. }
  23491. }
  23492. };
  23493. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23494. if (this._renderingGroups[renderingGroupId] === undefined) {
  23495. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23496. }
  23497. };
  23498. /**
  23499. * Add a sprite manager to the rendering manager in order to render it this frame.
  23500. * @param spriteManager Define the sprite manager to render
  23501. */
  23502. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23503. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23504. this._prepareRenderingGroup(renderingGroupId);
  23505. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23506. };
  23507. /**
  23508. * Add a particle system to the rendering manager in order to render it this frame.
  23509. * @param particleSystem Define the particle system to render
  23510. */
  23511. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23512. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23513. this._prepareRenderingGroup(renderingGroupId);
  23514. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23515. };
  23516. /**
  23517. * Add a submesh to the manager in order to render it this frame
  23518. * @param subMesh The submesh to dispatch
  23519. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23520. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23521. */
  23522. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23523. if (mesh === undefined) {
  23524. mesh = subMesh.getMesh();
  23525. }
  23526. var renderingGroupId = mesh.renderingGroupId || 0;
  23527. this._prepareRenderingGroup(renderingGroupId);
  23528. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23529. };
  23530. /**
  23531. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23532. * This allowed control for front to back rendering or reversly depending of the special needs.
  23533. *
  23534. * @param renderingGroupId The rendering group id corresponding to its index
  23535. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23536. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23537. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23538. */
  23539. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23540. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23541. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23542. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23543. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23544. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23545. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23546. if (this._renderingGroups[renderingGroupId]) {
  23547. var group = this._renderingGroups[renderingGroupId];
  23548. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23549. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23550. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23551. }
  23552. };
  23553. /**
  23554. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23555. *
  23556. * @param renderingGroupId The rendering group id corresponding to its index
  23557. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23558. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23559. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23560. */
  23561. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23562. if (depth === void 0) { depth = true; }
  23563. if (stencil === void 0) { stencil = true; }
  23564. this._autoClearDepthStencil[renderingGroupId] = {
  23565. autoClear: autoClearDepthStencil,
  23566. depth: depth,
  23567. stencil: stencil
  23568. };
  23569. };
  23570. /**
  23571. * Gets the current auto clear configuration for one rendering group of the rendering
  23572. * manager.
  23573. * @param index the rendering group index to get the information for
  23574. * @returns The auto clear setup for the requested rendering group
  23575. */
  23576. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23577. return this._autoClearDepthStencil[index];
  23578. };
  23579. /**
  23580. * The max id used for rendering groups (not included)
  23581. */
  23582. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23583. /**
  23584. * The min id used for rendering groups (included)
  23585. */
  23586. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23587. /**
  23588. * Used to globally prevent autoclearing scenes.
  23589. */
  23590. RenderingManager.AUTOCLEAR = true;
  23591. return RenderingManager;
  23592. }());
  23593. BABYLON.RenderingManager = RenderingManager;
  23594. })(BABYLON || (BABYLON = {}));
  23595. //# sourceMappingURL=babylon.renderingManager.js.map
  23596. var BABYLON;
  23597. (function (BABYLON) {
  23598. /**
  23599. * This represents the object necessary to create a rendering group.
  23600. * This is exclusively used and created by the rendering manager.
  23601. * To modify the behavior, you use the available helpers in your scene or meshes.
  23602. * @hidden
  23603. */
  23604. var RenderingGroup = /** @class */ (function () {
  23605. /**
  23606. * Creates a new rendering group.
  23607. * @param index The rendering group index
  23608. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23609. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23610. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23611. */
  23612. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23613. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23614. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23615. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23616. this.index = index;
  23617. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23618. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23619. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23620. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23621. this._particleSystems = new BABYLON.SmartArray(256);
  23622. this._spriteManagers = new BABYLON.SmartArray(256);
  23623. this._edgesRenderers = new BABYLON.SmartArray(16);
  23624. this._scene = scene;
  23625. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23626. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23627. this.transparentSortCompareFn = transparentSortCompareFn;
  23628. }
  23629. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23630. /**
  23631. * Set the opaque sort comparison function.
  23632. * If null the sub meshes will be render in the order they were created
  23633. */
  23634. set: function (value) {
  23635. this._opaqueSortCompareFn = value;
  23636. if (value) {
  23637. this._renderOpaque = this.renderOpaqueSorted;
  23638. }
  23639. else {
  23640. this._renderOpaque = RenderingGroup.renderUnsorted;
  23641. }
  23642. },
  23643. enumerable: true,
  23644. configurable: true
  23645. });
  23646. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23647. /**
  23648. * Set the alpha test sort comparison function.
  23649. * If null the sub meshes will be render in the order they were created
  23650. */
  23651. set: function (value) {
  23652. this._alphaTestSortCompareFn = value;
  23653. if (value) {
  23654. this._renderAlphaTest = this.renderAlphaTestSorted;
  23655. }
  23656. else {
  23657. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23658. }
  23659. },
  23660. enumerable: true,
  23661. configurable: true
  23662. });
  23663. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23664. /**
  23665. * Set the transparent sort comparison function.
  23666. * If null the sub meshes will be render in the order they were created
  23667. */
  23668. set: function (value) {
  23669. if (value) {
  23670. this._transparentSortCompareFn = value;
  23671. }
  23672. else {
  23673. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23674. }
  23675. this._renderTransparent = this.renderTransparentSorted;
  23676. },
  23677. enumerable: true,
  23678. configurable: true
  23679. });
  23680. /**
  23681. * Render all the sub meshes contained in the group.
  23682. * @param customRenderFunction Used to override the default render behaviour of the group.
  23683. * @returns true if rendered some submeshes.
  23684. */
  23685. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23686. if (customRenderFunction) {
  23687. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23688. return;
  23689. }
  23690. var engine = this._scene.getEngine();
  23691. // Depth only
  23692. if (this._depthOnlySubMeshes.length !== 0) {
  23693. engine.setColorWrite(false);
  23694. this._renderAlphaTest(this._depthOnlySubMeshes);
  23695. engine.setColorWrite(true);
  23696. }
  23697. // Opaque
  23698. if (this._opaqueSubMeshes.length !== 0) {
  23699. this._renderOpaque(this._opaqueSubMeshes);
  23700. }
  23701. // Alpha test
  23702. if (this._alphaTestSubMeshes.length !== 0) {
  23703. this._renderAlphaTest(this._alphaTestSubMeshes);
  23704. }
  23705. var stencilState = engine.getStencilBuffer();
  23706. engine.setStencilBuffer(false);
  23707. // Sprites
  23708. if (renderSprites) {
  23709. this._renderSprites();
  23710. }
  23711. // Particles
  23712. if (renderParticles) {
  23713. this._renderParticles(activeMeshes);
  23714. }
  23715. if (this.onBeforeTransparentRendering) {
  23716. this.onBeforeTransparentRendering();
  23717. }
  23718. // Transparent
  23719. if (this._transparentSubMeshes.length !== 0) {
  23720. this._renderTransparent(this._transparentSubMeshes);
  23721. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23722. }
  23723. // Set back stencil to false in case it changes before the edge renderer.
  23724. engine.setStencilBuffer(false);
  23725. // Edges
  23726. if (this._edgesRenderers.length) {
  23727. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23728. this._edgesRenderers.data[edgesRendererIndex].render();
  23729. }
  23730. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23731. }
  23732. // Restore Stencil state.
  23733. engine.setStencilBuffer(stencilState);
  23734. };
  23735. /**
  23736. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23737. * @param subMeshes The submeshes to render
  23738. */
  23739. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23740. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23741. };
  23742. /**
  23743. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23744. * @param subMeshes The submeshes to render
  23745. */
  23746. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23747. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23748. };
  23749. /**
  23750. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23751. * @param subMeshes The submeshes to render
  23752. */
  23753. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23754. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23755. };
  23756. /**
  23757. * Renders the submeshes in a specified order.
  23758. * @param subMeshes The submeshes to sort before render
  23759. * @param sortCompareFn The comparison function use to sort
  23760. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23761. * @param transparent Specifies to activate blending if true
  23762. */
  23763. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23764. var subIndex = 0;
  23765. var subMesh;
  23766. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23767. for (; subIndex < subMeshes.length; subIndex++) {
  23768. subMesh = subMeshes.data[subIndex];
  23769. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23770. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23771. }
  23772. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23773. if (sortCompareFn) {
  23774. sortedArray.sort(sortCompareFn);
  23775. }
  23776. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23777. subMesh = sortedArray[subIndex];
  23778. if (transparent) {
  23779. var material = subMesh.getMaterial();
  23780. if (material && material.needDepthPrePass) {
  23781. var engine = material.getScene().getEngine();
  23782. engine.setColorWrite(false);
  23783. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23784. subMesh.render(false);
  23785. engine.setColorWrite(true);
  23786. }
  23787. }
  23788. subMesh.render(transparent);
  23789. }
  23790. };
  23791. /**
  23792. * Renders the submeshes in the order they were dispatched (no sort applied).
  23793. * @param subMeshes The submeshes to render
  23794. */
  23795. RenderingGroup.renderUnsorted = function (subMeshes) {
  23796. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23797. var submesh = subMeshes.data[subIndex];
  23798. submesh.render(false);
  23799. }
  23800. };
  23801. /**
  23802. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23803. * are rendered back to front if in the same alpha index.
  23804. *
  23805. * @param a The first submesh
  23806. * @param b The second submesh
  23807. * @returns The result of the comparison
  23808. */
  23809. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23810. // Alpha index first
  23811. if (a._alphaIndex > b._alphaIndex) {
  23812. return 1;
  23813. }
  23814. if (a._alphaIndex < b._alphaIndex) {
  23815. return -1;
  23816. }
  23817. // Then distance to camera
  23818. return RenderingGroup.backToFrontSortCompare(a, b);
  23819. };
  23820. /**
  23821. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23822. * are rendered back to front.
  23823. *
  23824. * @param a The first submesh
  23825. * @param b The second submesh
  23826. * @returns The result of the comparison
  23827. */
  23828. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23829. // Then distance to camera
  23830. if (a._distanceToCamera < b._distanceToCamera) {
  23831. return 1;
  23832. }
  23833. if (a._distanceToCamera > b._distanceToCamera) {
  23834. return -1;
  23835. }
  23836. return 0;
  23837. };
  23838. /**
  23839. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23840. * are rendered front to back (prevent overdraw).
  23841. *
  23842. * @param a The first submesh
  23843. * @param b The second submesh
  23844. * @returns The result of the comparison
  23845. */
  23846. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23847. // Then distance to camera
  23848. if (a._distanceToCamera < b._distanceToCamera) {
  23849. return -1;
  23850. }
  23851. if (a._distanceToCamera > b._distanceToCamera) {
  23852. return 1;
  23853. }
  23854. return 0;
  23855. };
  23856. /**
  23857. * Resets the different lists of submeshes to prepare a new frame.
  23858. */
  23859. RenderingGroup.prototype.prepare = function () {
  23860. this._opaqueSubMeshes.reset();
  23861. this._transparentSubMeshes.reset();
  23862. this._alphaTestSubMeshes.reset();
  23863. this._depthOnlySubMeshes.reset();
  23864. this._particleSystems.reset();
  23865. this._spriteManagers.reset();
  23866. this._edgesRenderers.reset();
  23867. };
  23868. RenderingGroup.prototype.dispose = function () {
  23869. this._opaqueSubMeshes.dispose();
  23870. this._transparentSubMeshes.dispose();
  23871. this._alphaTestSubMeshes.dispose();
  23872. this._depthOnlySubMeshes.dispose();
  23873. this._particleSystems.dispose();
  23874. this._spriteManagers.dispose();
  23875. this._edgesRenderers.dispose();
  23876. };
  23877. /**
  23878. * Inserts the submesh in its correct queue depending on its material.
  23879. * @param subMesh The submesh to dispatch
  23880. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23881. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23882. */
  23883. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23884. // Get mesh and materials if not provided
  23885. if (mesh === undefined) {
  23886. mesh = subMesh.getMesh();
  23887. }
  23888. if (material === undefined) {
  23889. material = subMesh.getMaterial();
  23890. }
  23891. if (material === null || material === undefined) {
  23892. return;
  23893. }
  23894. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23895. this._transparentSubMeshes.push(subMesh);
  23896. }
  23897. else if (material.needAlphaTesting()) { // Alpha test
  23898. if (material.needDepthPrePass) {
  23899. this._depthOnlySubMeshes.push(subMesh);
  23900. }
  23901. this._alphaTestSubMeshes.push(subMesh);
  23902. }
  23903. else {
  23904. if (material.needDepthPrePass) {
  23905. this._depthOnlySubMeshes.push(subMesh);
  23906. }
  23907. this._opaqueSubMeshes.push(subMesh); // Opaque
  23908. }
  23909. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23910. this._edgesRenderers.push(mesh._edgesRenderer);
  23911. }
  23912. };
  23913. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23914. this._spriteManagers.push(spriteManager);
  23915. };
  23916. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23917. this._particleSystems.push(particleSystem);
  23918. };
  23919. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23920. if (this._particleSystems.length === 0) {
  23921. return;
  23922. }
  23923. // Particles
  23924. var activeCamera = this._scene.activeCamera;
  23925. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23926. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23927. var particleSystem = this._particleSystems.data[particleIndex];
  23928. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23929. continue;
  23930. }
  23931. var emitter = particleSystem.emitter;
  23932. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23933. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23934. }
  23935. }
  23936. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23937. };
  23938. RenderingGroup.prototype._renderSprites = function () {
  23939. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23940. return;
  23941. }
  23942. // Sprites
  23943. var activeCamera = this._scene.activeCamera;
  23944. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23945. for (var id = 0; id < this._spriteManagers.length; id++) {
  23946. var spriteManager = this._spriteManagers.data[id];
  23947. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23948. spriteManager.render();
  23949. }
  23950. }
  23951. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23952. };
  23953. return RenderingGroup;
  23954. }());
  23955. BABYLON.RenderingGroup = RenderingGroup;
  23956. })(BABYLON || (BABYLON = {}));
  23957. //# sourceMappingURL=babylon.renderingGroup.js.map
  23958. var BABYLON;
  23959. (function (BABYLON) {
  23960. /**
  23961. * Groups all the scene component constants in one place to ease maintenance.
  23962. * @hidden
  23963. */
  23964. var SceneComponentConstants = /** @class */ (function () {
  23965. function SceneComponentConstants() {
  23966. }
  23967. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23968. SceneComponentConstants.NAME_LAYER = "Layer";
  23969. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23970. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23971. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23972. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23973. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23974. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23975. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23976. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23977. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23978. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23979. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23980. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23981. SceneComponentConstants.NAME_OCTREE = "Octree";
  23982. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  23983. SceneComponentConstants.NAME_AUDIO = "Audio";
  23984. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23985. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23986. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23987. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23988. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23989. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23990. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23991. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23992. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23993. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23994. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  23995. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23996. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23997. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23998. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23999. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24000. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24001. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24002. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24003. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24004. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24005. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24006. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24007. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24008. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24009. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24010. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24011. return SceneComponentConstants;
  24012. }());
  24013. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24014. /**
  24015. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24016. * @hidden
  24017. */
  24018. var Stage = /** @class */ (function (_super) {
  24019. __extends(Stage, _super);
  24020. /**
  24021. * Hide ctor from the rest of the world.
  24022. * @param items The items to add.
  24023. */
  24024. function Stage(items) {
  24025. return _super.apply(this, items) || this;
  24026. }
  24027. /**
  24028. * Creates a new Stage.
  24029. * @returns A new instance of a Stage
  24030. */
  24031. Stage.Create = function () {
  24032. return Object.create(Stage.prototype);
  24033. };
  24034. /**
  24035. * Registers a step in an ordered way in the targeted stage.
  24036. * @param index Defines the position to register the step in
  24037. * @param component Defines the component attached to the step
  24038. * @param action Defines the action to launch during the step
  24039. */
  24040. Stage.prototype.registerStep = function (index, component, action) {
  24041. var i = 0;
  24042. var maxIndex = Number.MAX_VALUE;
  24043. for (; i < this.length && i < maxIndex; i++) {
  24044. var step = this[i];
  24045. maxIndex = step.index;
  24046. }
  24047. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24048. };
  24049. /**
  24050. * Clears all the steps from the stage.
  24051. */
  24052. Stage.prototype.clear = function () {
  24053. this.length = 0;
  24054. };
  24055. return Stage;
  24056. }(Array));
  24057. BABYLON.Stage = Stage;
  24058. })(BABYLON || (BABYLON = {}));
  24059. //# sourceMappingURL=babylon.sceneComponent.js.map
  24060. var BABYLON;
  24061. (function (BABYLON) {
  24062. /**
  24063. * Base class of the scene acting as a container for the different elements composing a scene.
  24064. * This class is dynamically extended by the different components of the scene increasing
  24065. * flexibility and reducing coupling
  24066. */
  24067. var AbstractScene = /** @class */ (function () {
  24068. function AbstractScene() {
  24069. /**
  24070. * Gets the list of root nodes (ie. nodes with no parent)
  24071. */
  24072. this.rootNodes = new Array();
  24073. /** All of the cameras added to this scene
  24074. * @see http://doc.babylonjs.com/babylon101/cameras
  24075. */
  24076. this.cameras = new Array();
  24077. /**
  24078. * All of the lights added to this scene
  24079. * @see http://doc.babylonjs.com/babylon101/lights
  24080. */
  24081. this.lights = new Array();
  24082. /**
  24083. * All of the (abstract) meshes added to this scene
  24084. */
  24085. this.meshes = new Array();
  24086. /**
  24087. * The list of skeletons added to the scene
  24088. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24089. */
  24090. this.skeletons = new Array();
  24091. /**
  24092. * All of the particle systems added to this scene
  24093. * @see http://doc.babylonjs.com/babylon101/particles
  24094. */
  24095. this.particleSystems = new Array();
  24096. /**
  24097. * Gets a list of Animations associated with the scene
  24098. */
  24099. this.animations = [];
  24100. /**
  24101. * All of the animation groups added to this scene
  24102. * @see http://doc.babylonjs.com/how_to/group
  24103. */
  24104. this.animationGroups = new Array();
  24105. /**
  24106. * All of the multi-materials added to this scene
  24107. * @see http://doc.babylonjs.com/how_to/multi_materials
  24108. */
  24109. this.multiMaterials = new Array();
  24110. /**
  24111. * All of the materials added to this scene
  24112. * @see http://doc.babylonjs.com/babylon101/materials
  24113. */
  24114. this.materials = new Array();
  24115. /**
  24116. * The list of morph target managers added to the scene
  24117. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24118. */
  24119. this.morphTargetManagers = new Array();
  24120. /**
  24121. * The list of geometries used in the scene.
  24122. */
  24123. this.geometries = new Array();
  24124. /**
  24125. * All of the tranform nodes added to this scene
  24126. * @see http://doc.babylonjs.com/how_to/transformnode
  24127. */
  24128. this.transformNodes = new Array();
  24129. /**
  24130. * ActionManagers available on the scene.
  24131. */
  24132. this.actionManagers = new Array();
  24133. /**
  24134. * Textures to keep.
  24135. */
  24136. this.textures = new Array();
  24137. }
  24138. /**
  24139. * Adds a parser in the list of available ones
  24140. * @param name Defines the name of the parser
  24141. * @param parser Defines the parser to add
  24142. */
  24143. AbstractScene.AddParser = function (name, parser) {
  24144. this._BabylonFileParsers[name] = parser;
  24145. };
  24146. /**
  24147. * Gets a general parser from the list of avaialble ones
  24148. * @param name Defines the name of the parser
  24149. * @returns the requested parser or null
  24150. */
  24151. AbstractScene.GetParser = function (name) {
  24152. if (this._BabylonFileParsers[name]) {
  24153. return this._BabylonFileParsers[name];
  24154. }
  24155. return null;
  24156. };
  24157. /**
  24158. * Adds n individual parser in the list of available ones
  24159. * @param name Defines the name of the parser
  24160. * @param parser Defines the parser to add
  24161. */
  24162. AbstractScene.AddIndividualParser = function (name, parser) {
  24163. this._IndividualBabylonFileParsers[name] = parser;
  24164. };
  24165. /**
  24166. * Gets an individual parser from the list of avaialble ones
  24167. * @param name Defines the name of the parser
  24168. * @returns the requested parser or null
  24169. */
  24170. AbstractScene.GetIndividualParser = function (name) {
  24171. if (this._IndividualBabylonFileParsers[name]) {
  24172. return this._IndividualBabylonFileParsers[name];
  24173. }
  24174. return null;
  24175. };
  24176. /**
  24177. * Parser json data and populate both a scene and its associated container object
  24178. * @param jsonData Defines the data to parse
  24179. * @param scene Defines the scene to parse the data for
  24180. * @param container Defines the container attached to the parsing sequence
  24181. * @param rootUrl Defines the root url of the data
  24182. */
  24183. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24184. for (var parserName in this._BabylonFileParsers) {
  24185. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24186. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24187. }
  24188. }
  24189. };
  24190. /**
  24191. * Stores the list of available parsers in the application.
  24192. */
  24193. AbstractScene._BabylonFileParsers = {};
  24194. /**
  24195. * Stores the list of available individual parsers in the application.
  24196. */
  24197. AbstractScene._IndividualBabylonFileParsers = {};
  24198. return AbstractScene;
  24199. }());
  24200. BABYLON.AbstractScene = AbstractScene;
  24201. })(BABYLON || (BABYLON = {}));
  24202. //# sourceMappingURL=babylon.abstractScene.js.map
  24203. var BABYLON;
  24204. (function (BABYLON) {
  24205. /** @hidden */
  24206. var ClickInfo = /** @class */ (function () {
  24207. function ClickInfo() {
  24208. this._singleClick = false;
  24209. this._doubleClick = false;
  24210. this._hasSwiped = false;
  24211. this._ignore = false;
  24212. }
  24213. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24214. get: function () {
  24215. return this._singleClick;
  24216. },
  24217. set: function (b) {
  24218. this._singleClick = b;
  24219. },
  24220. enumerable: true,
  24221. configurable: true
  24222. });
  24223. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24224. get: function () {
  24225. return this._doubleClick;
  24226. },
  24227. set: function (b) {
  24228. this._doubleClick = b;
  24229. },
  24230. enumerable: true,
  24231. configurable: true
  24232. });
  24233. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24234. get: function () {
  24235. return this._hasSwiped;
  24236. },
  24237. set: function (b) {
  24238. this._hasSwiped = b;
  24239. },
  24240. enumerable: true,
  24241. configurable: true
  24242. });
  24243. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24244. get: function () {
  24245. return this._ignore;
  24246. },
  24247. set: function (b) {
  24248. this._ignore = b;
  24249. },
  24250. enumerable: true,
  24251. configurable: true
  24252. });
  24253. return ClickInfo;
  24254. }());
  24255. /**
  24256. * This class is used by the onRenderingGroupObservable
  24257. */
  24258. var RenderingGroupInfo = /** @class */ (function () {
  24259. function RenderingGroupInfo() {
  24260. }
  24261. return RenderingGroupInfo;
  24262. }());
  24263. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24264. /**
  24265. * Represents a scene to be rendered by the engine.
  24266. * @see http://doc.babylonjs.com/features/scene
  24267. */
  24268. var Scene = /** @class */ (function (_super) {
  24269. __extends(Scene, _super);
  24270. /**
  24271. * Creates a new Scene
  24272. * @param engine defines the engine to use to render this scene
  24273. */
  24274. function Scene(engine) {
  24275. var _this = _super.call(this) || this;
  24276. // Members
  24277. /**
  24278. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24279. */
  24280. _this.autoClear = true;
  24281. /**
  24282. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24283. */
  24284. _this.autoClearDepthAndStencil = true;
  24285. /**
  24286. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24287. */
  24288. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24289. /**
  24290. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24291. */
  24292. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24293. _this._forceWireframe = false;
  24294. _this._forcePointsCloud = false;
  24295. /**
  24296. * Gets or sets a boolean indicating if animations are enabled
  24297. */
  24298. _this.animationsEnabled = true;
  24299. _this._animationPropertiesOverride = null;
  24300. /**
  24301. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24302. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24303. */
  24304. _this.useConstantAnimationDeltaTime = false;
  24305. /**
  24306. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24307. * Please note that it requires to run a ray cast through the scene on every frame
  24308. */
  24309. _this.constantlyUpdateMeshUnderPointer = false;
  24310. /**
  24311. * Defines the HTML cursor to use when hovering over interactive elements
  24312. */
  24313. _this.hoverCursor = "pointer";
  24314. /**
  24315. * Defines the HTML default cursor to use (empty by default)
  24316. */
  24317. _this.defaultCursor = "";
  24318. /**
  24319. * This is used to call preventDefault() on pointer down
  24320. * in order to block unwanted artifacts like system double clicks
  24321. */
  24322. _this.preventDefaultOnPointerDown = true;
  24323. // Metadata
  24324. /**
  24325. * Gets or sets user defined metadata
  24326. */
  24327. _this.metadata = null;
  24328. /**
  24329. * Use this array to add regular expressions used to disable offline support for specific urls
  24330. */
  24331. _this.disableOfflineSupportExceptionRules = new Array();
  24332. /**
  24333. * An event triggered when the scene is disposed.
  24334. */
  24335. _this.onDisposeObservable = new BABYLON.Observable();
  24336. _this._onDisposeObserver = null;
  24337. /**
  24338. * An event triggered before rendering the scene (right after animations and physics)
  24339. */
  24340. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24341. _this._onBeforeRenderObserver = null;
  24342. /**
  24343. * An event triggered after rendering the scene
  24344. */
  24345. _this.onAfterRenderObservable = new BABYLON.Observable();
  24346. _this._onAfterRenderObserver = null;
  24347. /**
  24348. * An event triggered before animating the scene
  24349. */
  24350. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24351. /**
  24352. * An event triggered after animations processing
  24353. */
  24354. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24355. /**
  24356. * An event triggered before draw calls are ready to be sent
  24357. */
  24358. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24359. /**
  24360. * An event triggered after draw calls have been sent
  24361. */
  24362. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24363. /**
  24364. * An event triggered when the scene is ready
  24365. */
  24366. _this.onReadyObservable = new BABYLON.Observable();
  24367. /**
  24368. * An event triggered before rendering a camera
  24369. */
  24370. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24371. _this._onBeforeCameraRenderObserver = null;
  24372. /**
  24373. * An event triggered after rendering a camera
  24374. */
  24375. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24376. _this._onAfterCameraRenderObserver = null;
  24377. /**
  24378. * An event triggered when active meshes evaluation is about to start
  24379. */
  24380. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24381. /**
  24382. * An event triggered when active meshes evaluation is done
  24383. */
  24384. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24385. /**
  24386. * An event triggered when particles rendering is about to start
  24387. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24388. */
  24389. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24390. /**
  24391. * An event triggered when particles rendering is done
  24392. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24393. */
  24394. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24395. /**
  24396. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24397. */
  24398. _this.onDataLoadedObservable = new BABYLON.Observable();
  24399. /**
  24400. * An event triggered when a camera is created
  24401. */
  24402. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24403. /**
  24404. * An event triggered when a camera is removed
  24405. */
  24406. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24407. /**
  24408. * An event triggered when a light is created
  24409. */
  24410. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24411. /**
  24412. * An event triggered when a light is removed
  24413. */
  24414. _this.onLightRemovedObservable = new BABYLON.Observable();
  24415. /**
  24416. * An event triggered when a geometry is created
  24417. */
  24418. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24419. /**
  24420. * An event triggered when a geometry is removed
  24421. */
  24422. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24423. /**
  24424. * An event triggered when a transform node is created
  24425. */
  24426. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24427. /**
  24428. * An event triggered when a transform node is removed
  24429. */
  24430. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24431. /**
  24432. * An event triggered when a mesh is created
  24433. */
  24434. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24435. /**
  24436. * An event triggered when a mesh is removed
  24437. */
  24438. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24439. /**
  24440. * An event triggered when a material is created
  24441. */
  24442. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  24443. /**
  24444. * An event triggered when a material is removed
  24445. */
  24446. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  24447. /**
  24448. * An event triggered when a texture is created
  24449. */
  24450. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  24451. /**
  24452. * An event triggered when a texture is removed
  24453. */
  24454. _this.onTextureRemovedObservable = new BABYLON.Observable();
  24455. /**
  24456. * An event triggered when render targets are about to be rendered
  24457. * Can happen multiple times per frame.
  24458. */
  24459. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24460. /**
  24461. * An event triggered when render targets were rendered.
  24462. * Can happen multiple times per frame.
  24463. */
  24464. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24465. /**
  24466. * An event triggered before calculating deterministic simulation step
  24467. */
  24468. _this.onBeforeStepObservable = new BABYLON.Observable();
  24469. /**
  24470. * An event triggered after calculating deterministic simulation step
  24471. */
  24472. _this.onAfterStepObservable = new BABYLON.Observable();
  24473. /**
  24474. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24475. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24476. * 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)
  24477. */
  24478. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24479. /**
  24480. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24481. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24482. * 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)
  24483. */
  24484. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24485. /**
  24486. * This Observable will when a mesh has been imported into the scene.
  24487. */
  24488. _this.onMeshImportedObservable = new BABYLON.Observable();
  24489. // Animations
  24490. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24491. /**
  24492. * 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).
  24493. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24494. */
  24495. _this.onPrePointerObservable = new BABYLON.Observable();
  24496. /**
  24497. * Observable event triggered each time an input event is received from the rendering canvas
  24498. */
  24499. _this.onPointerObservable = new BABYLON.Observable();
  24500. _this._meshPickProceed = false;
  24501. _this._currentPickResult = null;
  24502. _this._previousPickResult = null;
  24503. _this._totalPointersPressed = 0;
  24504. _this._doubleClickOccured = false;
  24505. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24506. _this.cameraToUseForPointers = null;
  24507. _this._pointerX = 0;
  24508. _this._pointerY = 0;
  24509. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24510. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24511. _this._startingPointerTime = 0;
  24512. _this._previousStartingPointerTime = 0;
  24513. _this._pointerCaptures = {};
  24514. // Deterministic lockstep
  24515. _this._timeAccumulator = 0;
  24516. _this._currentStepId = 0;
  24517. _this._currentInternalStep = 0;
  24518. // Keyboard
  24519. /**
  24520. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24521. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24522. */
  24523. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24524. /**
  24525. * Observable event triggered each time an keyboard event is received from the hosting window
  24526. */
  24527. _this.onKeyboardObservable = new BABYLON.Observable();
  24528. // Coordinates system
  24529. _this._useRightHandedSystem = false;
  24530. // Fog
  24531. _this._fogEnabled = true;
  24532. _this._fogMode = Scene.FOGMODE_NONE;
  24533. /**
  24534. * Gets or sets the fog color to use
  24535. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24536. */
  24537. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24538. /**
  24539. * Gets or sets the fog density to use
  24540. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24541. */
  24542. _this.fogDensity = 0.1;
  24543. /**
  24544. * Gets or sets the fog start distance to use
  24545. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24546. */
  24547. _this.fogStart = 0;
  24548. /**
  24549. * Gets or sets the fog end distance to use
  24550. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24551. */
  24552. _this.fogEnd = 1000.0;
  24553. // Lights
  24554. _this._shadowsEnabled = true;
  24555. _this._lightsEnabled = true;
  24556. /** All of the active cameras added to this scene. */
  24557. _this.activeCameras = new Array();
  24558. // Textures
  24559. _this._texturesEnabled = true;
  24560. // Particles
  24561. /**
  24562. * Gets or sets a boolean indicating if particles are enabled on this scene
  24563. */
  24564. _this.particlesEnabled = true;
  24565. // Sprites
  24566. /**
  24567. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24568. */
  24569. _this.spritesEnabled = true;
  24570. // Skeletons
  24571. _this._skeletonsEnabled = true;
  24572. // Lens flares
  24573. /**
  24574. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24575. */
  24576. _this.lensFlaresEnabled = true;
  24577. // Collisions
  24578. /**
  24579. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24580. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24581. */
  24582. _this.collisionsEnabled = true;
  24583. /**
  24584. * Defines the gravity applied to this scene (used only for collisions)
  24585. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24586. */
  24587. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24588. // Postprocesses
  24589. /**
  24590. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24591. */
  24592. _this.postProcessesEnabled = true;
  24593. /**
  24594. * The list of postprocesses added to the scene
  24595. */
  24596. _this.postProcesses = new Array();
  24597. // Customs render targets
  24598. /**
  24599. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24600. */
  24601. _this.renderTargetsEnabled = true;
  24602. /**
  24603. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24604. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24605. */
  24606. _this.dumpNextRenderTargets = false;
  24607. /**
  24608. * The list of user defined render targets added to the scene
  24609. */
  24610. _this.customRenderTargets = new Array();
  24611. /**
  24612. * Gets the list of meshes imported to the scene through SceneLoader
  24613. */
  24614. _this.importedMeshesFiles = new Array();
  24615. // Probes
  24616. /**
  24617. * Gets or sets a boolean indicating if probes are enabled on this scene
  24618. */
  24619. _this.probesEnabled = true;
  24620. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24621. // Procedural textures
  24622. /**
  24623. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24624. */
  24625. _this.proceduralTexturesEnabled = true;
  24626. // Performance counters
  24627. _this._totalVertices = new BABYLON.PerfCounter();
  24628. /** @hidden */
  24629. _this._activeIndices = new BABYLON.PerfCounter();
  24630. /** @hidden */
  24631. _this._activeParticles = new BABYLON.PerfCounter();
  24632. /** @hidden */
  24633. _this._activeBones = new BABYLON.PerfCounter();
  24634. _this._animationTime = 0;
  24635. /**
  24636. * Gets or sets a general scale for animation speed
  24637. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24638. */
  24639. _this.animationTimeScale = 1;
  24640. _this._renderId = 0;
  24641. _this._frameId = 0;
  24642. _this._executeWhenReadyTimeoutId = -1;
  24643. _this._intermediateRendering = false;
  24644. _this._viewUpdateFlag = -1;
  24645. _this._projectionUpdateFlag = -1;
  24646. _this._alternateViewUpdateFlag = -1;
  24647. _this._alternateProjectionUpdateFlag = -1;
  24648. /** @hidden */
  24649. _this._toBeDisposed = new Array(256);
  24650. _this._activeRequests = new Array();
  24651. _this._pendingData = new Array();
  24652. _this._isDisposed = false;
  24653. /**
  24654. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24655. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24656. */
  24657. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24658. _this._activeMeshes = new BABYLON.SmartArray(256);
  24659. _this._processedMaterials = new BABYLON.SmartArray(256);
  24660. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24661. /** @hidden */
  24662. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24663. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24664. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24665. /** @hidden */
  24666. _this._activeAnimatables = new Array();
  24667. _this._transformMatrix = BABYLON.Matrix.Zero();
  24668. _this._useAlternateCameraConfiguration = false;
  24669. _this._alternateRendering = false;
  24670. /**
  24671. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24672. * This is useful if there are more lights that the maximum simulteanous authorized
  24673. */
  24674. _this.requireLightSorting = false;
  24675. /**
  24676. * @hidden
  24677. * Backing store of defined scene components.
  24678. */
  24679. _this._components = [];
  24680. /**
  24681. * @hidden
  24682. * Backing store of defined scene components.
  24683. */
  24684. _this._serializableComponents = [];
  24685. /**
  24686. * List of components to register on the next registration step.
  24687. */
  24688. _this._transientComponents = [];
  24689. /**
  24690. * @hidden
  24691. * Defines the actions happening before camera updates.
  24692. */
  24693. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24694. /**
  24695. * @hidden
  24696. * Defines the actions happening before clear the canvas.
  24697. */
  24698. _this._beforeClearStage = BABYLON.Stage.Create();
  24699. /**
  24700. * @hidden
  24701. * Defines the actions when collecting render targets for the frame.
  24702. */
  24703. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24704. /**
  24705. * @hidden
  24706. * Defines the actions happening for one camera in the frame.
  24707. */
  24708. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24709. /**
  24710. * @hidden
  24711. * Defines the actions happening during the per mesh ready checks.
  24712. */
  24713. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24714. /**
  24715. * @hidden
  24716. * Defines the actions happening before evaluate active mesh checks.
  24717. */
  24718. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24719. /**
  24720. * @hidden
  24721. * Defines the actions happening during the evaluate sub mesh checks.
  24722. */
  24723. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24724. /**
  24725. * @hidden
  24726. * Defines the actions happening during the active mesh stage.
  24727. */
  24728. _this._activeMeshStage = BABYLON.Stage.Create();
  24729. /**
  24730. * @hidden
  24731. * Defines the actions happening during the per camera render target step.
  24732. */
  24733. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24734. /**
  24735. * @hidden
  24736. * Defines the actions happening just before the active camera is drawing.
  24737. */
  24738. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24739. /**
  24740. * @hidden
  24741. * Defines the actions happening just before a rendering group is drawing.
  24742. */
  24743. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24744. /**
  24745. * @hidden
  24746. * Defines the actions happening just before a mesh is drawing.
  24747. */
  24748. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24749. /**
  24750. * @hidden
  24751. * Defines the actions happening just after a mesh has been drawn.
  24752. */
  24753. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24754. /**
  24755. * @hidden
  24756. * Defines the actions happening just after a rendering group has been drawn.
  24757. */
  24758. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24759. /**
  24760. * @hidden
  24761. * Defines the actions happening just after the active camera has been drawn.
  24762. */
  24763. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24764. /**
  24765. * @hidden
  24766. * Defines the actions happening just after rendering all cameras and computing intersections.
  24767. */
  24768. _this._afterRenderStage = BABYLON.Stage.Create();
  24769. /**
  24770. * @hidden
  24771. * Defines the actions happening when a pointer move event happens.
  24772. */
  24773. _this._pointerMoveStage = BABYLON.Stage.Create();
  24774. /**
  24775. * @hidden
  24776. * Defines the actions happening when a pointer down event happens.
  24777. */
  24778. _this._pointerDownStage = BABYLON.Stage.Create();
  24779. /**
  24780. * @hidden
  24781. * Defines the actions happening when a pointer up event happens.
  24782. */
  24783. _this._pointerUpStage = BABYLON.Stage.Create();
  24784. _this._defaultMeshCandidates = {
  24785. data: [],
  24786. length: 0
  24787. };
  24788. _this._defaultSubMeshCandidates = {
  24789. data: [],
  24790. length: 0
  24791. };
  24792. _this._activeMeshesFrozen = false;
  24793. /** @hidden */
  24794. _this._allowPostProcessClearColor = true;
  24795. /**
  24796. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24797. */
  24798. _this.getDeterministicFrameTime = function () {
  24799. return 1000.0 / 60.0; // frame time in ms
  24800. };
  24801. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24802. _this._blockMaterialDirtyMechanism = false;
  24803. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24804. _this._engine.scenes.push(_this);
  24805. _this._uid = null;
  24806. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24807. if (BABYLON.PostProcessManager) {
  24808. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24809. }
  24810. if (BABYLON.Tools.IsWindowObjectExist()) {
  24811. _this.attachControl();
  24812. }
  24813. //collision coordinator initialization. For now legacy per default.
  24814. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24815. // Uniform Buffer
  24816. _this._createUbo();
  24817. // Default Image processing definition
  24818. if (BABYLON.ImageProcessingConfiguration) {
  24819. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24820. }
  24821. _this.setDefaultCandidateProviders();
  24822. return _this;
  24823. }
  24824. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24825. /**
  24826. * Texture used in all pbr material as the reflection texture.
  24827. * As in the majority of the scene they are the same (exception for multi room and so on),
  24828. * this is easier to reference from here than from all the materials.
  24829. */
  24830. get: function () {
  24831. return this._environmentTexture;
  24832. },
  24833. /**
  24834. * Texture used in all pbr material as the reflection texture.
  24835. * As in the majority of the scene they are the same (exception for multi room and so on),
  24836. * this is easier to set here than in all the materials.
  24837. */
  24838. set: function (value) {
  24839. if (this._environmentTexture === value) {
  24840. return;
  24841. }
  24842. this._environmentTexture = value;
  24843. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24844. },
  24845. enumerable: true,
  24846. configurable: true
  24847. });
  24848. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24849. /**
  24850. * Default image processing configuration used either in the rendering
  24851. * Forward main pass or through the imageProcessingPostProcess if present.
  24852. * As in the majority of the scene they are the same (exception for multi camera),
  24853. * this is easier to reference from here than from all the materials and post process.
  24854. *
  24855. * No setter as we it is a shared configuration, you can set the values instead.
  24856. */
  24857. get: function () {
  24858. return this._imageProcessingConfiguration;
  24859. },
  24860. enumerable: true,
  24861. configurable: true
  24862. });
  24863. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24864. get: function () {
  24865. return this._forceWireframe;
  24866. },
  24867. /**
  24868. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24869. */
  24870. set: function (value) {
  24871. if (this._forceWireframe === value) {
  24872. return;
  24873. }
  24874. this._forceWireframe = value;
  24875. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24876. },
  24877. enumerable: true,
  24878. configurable: true
  24879. });
  24880. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24881. get: function () {
  24882. return this._forcePointsCloud;
  24883. },
  24884. /**
  24885. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24886. */
  24887. set: function (value) {
  24888. if (this._forcePointsCloud === value) {
  24889. return;
  24890. }
  24891. this._forcePointsCloud = value;
  24892. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24893. },
  24894. enumerable: true,
  24895. configurable: true
  24896. });
  24897. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24898. /**
  24899. * Gets or sets the animation properties override
  24900. */
  24901. get: function () {
  24902. return this._animationPropertiesOverride;
  24903. },
  24904. set: function (value) {
  24905. this._animationPropertiesOverride = value;
  24906. },
  24907. enumerable: true,
  24908. configurable: true
  24909. });
  24910. Object.defineProperty(Scene.prototype, "onDispose", {
  24911. /** Sets a function to be executed when this scene is disposed. */
  24912. set: function (callback) {
  24913. if (this._onDisposeObserver) {
  24914. this.onDisposeObservable.remove(this._onDisposeObserver);
  24915. }
  24916. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24917. },
  24918. enumerable: true,
  24919. configurable: true
  24920. });
  24921. Object.defineProperty(Scene.prototype, "beforeRender", {
  24922. /** Sets a function to be executed before rendering this scene */
  24923. set: function (callback) {
  24924. if (this._onBeforeRenderObserver) {
  24925. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24926. }
  24927. if (callback) {
  24928. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24929. }
  24930. },
  24931. enumerable: true,
  24932. configurable: true
  24933. });
  24934. Object.defineProperty(Scene.prototype, "afterRender", {
  24935. /** Sets a function to be executed after rendering this scene */
  24936. set: function (callback) {
  24937. if (this._onAfterRenderObserver) {
  24938. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24939. }
  24940. if (callback) {
  24941. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24942. }
  24943. },
  24944. enumerable: true,
  24945. configurable: true
  24946. });
  24947. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24948. /** Sets a function to be executed before rendering a camera*/
  24949. set: function (callback) {
  24950. if (this._onBeforeCameraRenderObserver) {
  24951. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24952. }
  24953. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24954. },
  24955. enumerable: true,
  24956. configurable: true
  24957. });
  24958. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24959. /** Sets a function to be executed after rendering a camera*/
  24960. set: function (callback) {
  24961. if (this._onAfterCameraRenderObserver) {
  24962. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24963. }
  24964. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24965. },
  24966. enumerable: true,
  24967. configurable: true
  24968. });
  24969. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24970. /**
  24971. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24972. */
  24973. get: function () {
  24974. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24975. },
  24976. enumerable: true,
  24977. configurable: true
  24978. });
  24979. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24980. get: function () {
  24981. return this._useRightHandedSystem;
  24982. },
  24983. /**
  24984. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24985. */
  24986. set: function (value) {
  24987. if (this._useRightHandedSystem === value) {
  24988. return;
  24989. }
  24990. this._useRightHandedSystem = value;
  24991. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24992. },
  24993. enumerable: true,
  24994. configurable: true
  24995. });
  24996. /**
  24997. * Sets the step Id used by deterministic lock step
  24998. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24999. * @param newStepId defines the step Id
  25000. */
  25001. Scene.prototype.setStepId = function (newStepId) {
  25002. this._currentStepId = newStepId;
  25003. };
  25004. ;
  25005. /**
  25006. * Gets the step Id used by deterministic lock step
  25007. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25008. * @returns the step Id
  25009. */
  25010. Scene.prototype.getStepId = function () {
  25011. return this._currentStepId;
  25012. };
  25013. ;
  25014. /**
  25015. * Gets the internal step used by deterministic lock step
  25016. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25017. * @returns the internal step
  25018. */
  25019. Scene.prototype.getInternalStep = function () {
  25020. return this._currentInternalStep;
  25021. };
  25022. ;
  25023. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25024. get: function () {
  25025. return this._fogEnabled;
  25026. },
  25027. /**
  25028. * Gets or sets a boolean indicating if fog is enabled on this scene
  25029. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25030. */
  25031. set: function (value) {
  25032. if (this._fogEnabled === value) {
  25033. return;
  25034. }
  25035. this._fogEnabled = value;
  25036. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25037. },
  25038. enumerable: true,
  25039. configurable: true
  25040. });
  25041. Object.defineProperty(Scene.prototype, "fogMode", {
  25042. get: function () {
  25043. return this._fogMode;
  25044. },
  25045. /**
  25046. * Gets or sets the fog mode to use
  25047. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25048. */
  25049. set: function (value) {
  25050. if (this._fogMode === value) {
  25051. return;
  25052. }
  25053. this._fogMode = value;
  25054. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25055. },
  25056. enumerable: true,
  25057. configurable: true
  25058. });
  25059. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25060. get: function () {
  25061. return this._shadowsEnabled;
  25062. },
  25063. /**
  25064. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25065. */
  25066. set: function (value) {
  25067. if (this._shadowsEnabled === value) {
  25068. return;
  25069. }
  25070. this._shadowsEnabled = value;
  25071. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25072. },
  25073. enumerable: true,
  25074. configurable: true
  25075. });
  25076. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25077. get: function () {
  25078. return this._lightsEnabled;
  25079. },
  25080. /**
  25081. * Gets or sets a boolean indicating if lights are enabled on this scene
  25082. */
  25083. set: function (value) {
  25084. if (this._lightsEnabled === value) {
  25085. return;
  25086. }
  25087. this._lightsEnabled = value;
  25088. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25089. },
  25090. enumerable: true,
  25091. configurable: true
  25092. });
  25093. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25094. /** The default material used on meshes when no material is affected */
  25095. get: function () {
  25096. if (!this._defaultMaterial) {
  25097. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25098. }
  25099. return this._defaultMaterial;
  25100. },
  25101. /** The default material used on meshes when no material is affected */
  25102. set: function (value) {
  25103. this._defaultMaterial = value;
  25104. },
  25105. enumerable: true,
  25106. configurable: true
  25107. });
  25108. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25109. get: function () {
  25110. return this._texturesEnabled;
  25111. },
  25112. /**
  25113. * Gets or sets a boolean indicating if textures are enabled on this scene
  25114. */
  25115. set: function (value) {
  25116. if (this._texturesEnabled === value) {
  25117. return;
  25118. }
  25119. this._texturesEnabled = value;
  25120. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25121. },
  25122. enumerable: true,
  25123. configurable: true
  25124. });
  25125. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25126. get: function () {
  25127. return this._skeletonsEnabled;
  25128. },
  25129. /**
  25130. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25131. */
  25132. set: function (value) {
  25133. if (this._skeletonsEnabled === value) {
  25134. return;
  25135. }
  25136. this._skeletonsEnabled = value;
  25137. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25138. },
  25139. enumerable: true,
  25140. configurable: true
  25141. });
  25142. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25143. /** @hidden */
  25144. get: function () {
  25145. return this._alternateRendering;
  25146. },
  25147. enumerable: true,
  25148. configurable: true
  25149. });
  25150. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25151. /**
  25152. * Gets the list of frustum planes (built from the active camera)
  25153. */
  25154. get: function () {
  25155. return this._frustumPlanes;
  25156. },
  25157. enumerable: true,
  25158. configurable: true
  25159. });
  25160. /**
  25161. * Registers the transient components if needed.
  25162. */
  25163. Scene.prototype._registerTransientComponents = function () {
  25164. // Register components that have been associated lately to the scene.
  25165. if (this._transientComponents.length > 0) {
  25166. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25167. var component = _a[_i];
  25168. component.register();
  25169. }
  25170. this._transientComponents = [];
  25171. }
  25172. };
  25173. /**
  25174. * @hidden
  25175. * Add a component to the scene.
  25176. * Note that the ccomponent could be registered on th next frame if this is called after
  25177. * the register component stage.
  25178. * @param component Defines the component to add to the scene
  25179. */
  25180. Scene.prototype._addComponent = function (component) {
  25181. this._components.push(component);
  25182. this._transientComponents.push(component);
  25183. var serializableComponent = component;
  25184. if (serializableComponent.addFromContainer) {
  25185. this._serializableComponents.push(serializableComponent);
  25186. }
  25187. };
  25188. /**
  25189. * @hidden
  25190. * Gets a component from the scene.
  25191. * @param name defines the name of the component to retrieve
  25192. * @returns the component or null if not present
  25193. */
  25194. Scene.prototype._getComponent = function (name) {
  25195. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25196. var component = _a[_i];
  25197. if (component.name === name) {
  25198. return component;
  25199. }
  25200. }
  25201. return null;
  25202. };
  25203. /**
  25204. * @hidden
  25205. */
  25206. Scene.prototype._getDefaultMeshCandidates = function () {
  25207. this._defaultMeshCandidates.data = this.meshes;
  25208. this._defaultMeshCandidates.length = this.meshes.length;
  25209. return this._defaultMeshCandidates;
  25210. };
  25211. /**
  25212. * @hidden
  25213. */
  25214. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25215. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25216. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25217. return this._defaultSubMeshCandidates;
  25218. };
  25219. /**
  25220. * Sets the default candidate providers for the scene.
  25221. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25222. * and getCollidingSubMeshCandidates to their default function
  25223. */
  25224. Scene.prototype.setDefaultCandidateProviders = function () {
  25225. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25226. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25227. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25228. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25229. };
  25230. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25231. /**
  25232. * Gets a boolean indicating if collisions are processed on a web worker
  25233. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25234. */
  25235. get: function () {
  25236. return this._workerCollisions;
  25237. },
  25238. set: function (enabled) {
  25239. if (!BABYLON.CollisionCoordinatorLegacy) {
  25240. return;
  25241. }
  25242. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25243. this._workerCollisions = enabled;
  25244. if (this.collisionCoordinator) {
  25245. this.collisionCoordinator.destroy();
  25246. }
  25247. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25248. this.collisionCoordinator.init(this);
  25249. },
  25250. enumerable: true,
  25251. configurable: true
  25252. });
  25253. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25254. /**
  25255. * Gets the mesh that is currently under the pointer
  25256. */
  25257. get: function () {
  25258. return this._pointerOverMesh;
  25259. },
  25260. enumerable: true,
  25261. configurable: true
  25262. });
  25263. Object.defineProperty(Scene.prototype, "pointerX", {
  25264. /**
  25265. * Gets the current on-screen X position of the pointer
  25266. */
  25267. get: function () {
  25268. return this._pointerX;
  25269. },
  25270. enumerable: true,
  25271. configurable: true
  25272. });
  25273. Object.defineProperty(Scene.prototype, "pointerY", {
  25274. /**
  25275. * Gets the current on-screen Y position of the pointer
  25276. */
  25277. get: function () {
  25278. return this._pointerY;
  25279. },
  25280. enumerable: true,
  25281. configurable: true
  25282. });
  25283. /**
  25284. * Gets the cached material (ie. the latest rendered one)
  25285. * @returns the cached material
  25286. */
  25287. Scene.prototype.getCachedMaterial = function () {
  25288. return this._cachedMaterial;
  25289. };
  25290. /**
  25291. * Gets the cached effect (ie. the latest rendered one)
  25292. * @returns the cached effect
  25293. */
  25294. Scene.prototype.getCachedEffect = function () {
  25295. return this._cachedEffect;
  25296. };
  25297. /**
  25298. * Gets the cached visibility state (ie. the latest rendered one)
  25299. * @returns the cached visibility state
  25300. */
  25301. Scene.prototype.getCachedVisibility = function () {
  25302. return this._cachedVisibility;
  25303. };
  25304. /**
  25305. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25306. * @param material defines the current material
  25307. * @param effect defines the current effect
  25308. * @param visibility defines the current visibility state
  25309. * @returns true if one parameter is not cached
  25310. */
  25311. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25312. if (visibility === void 0) { visibility = 1; }
  25313. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25314. };
  25315. /**
  25316. * Gets the engine associated with the scene
  25317. * @returns an Engine
  25318. */
  25319. Scene.prototype.getEngine = function () {
  25320. return this._engine;
  25321. };
  25322. /**
  25323. * Gets the total number of vertices rendered per frame
  25324. * @returns the total number of vertices rendered per frame
  25325. */
  25326. Scene.prototype.getTotalVertices = function () {
  25327. return this._totalVertices.current;
  25328. };
  25329. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25330. /**
  25331. * Gets the performance counter for total vertices
  25332. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25333. */
  25334. get: function () {
  25335. return this._totalVertices;
  25336. },
  25337. enumerable: true,
  25338. configurable: true
  25339. });
  25340. /**
  25341. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25342. * @returns the total number of active indices rendered per frame
  25343. */
  25344. Scene.prototype.getActiveIndices = function () {
  25345. return this._activeIndices.current;
  25346. };
  25347. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25348. /**
  25349. * Gets the performance counter for active indices
  25350. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25351. */
  25352. get: function () {
  25353. return this._activeIndices;
  25354. },
  25355. enumerable: true,
  25356. configurable: true
  25357. });
  25358. /**
  25359. * Gets the total number of active particles rendered per frame
  25360. * @returns the total number of active particles rendered per frame
  25361. */
  25362. Scene.prototype.getActiveParticles = function () {
  25363. return this._activeParticles.current;
  25364. };
  25365. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25366. /**
  25367. * Gets the performance counter for active particles
  25368. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25369. */
  25370. get: function () {
  25371. return this._activeParticles;
  25372. },
  25373. enumerable: true,
  25374. configurable: true
  25375. });
  25376. /**
  25377. * Gets the total number of active bones rendered per frame
  25378. * @returns the total number of active bones rendered per frame
  25379. */
  25380. Scene.prototype.getActiveBones = function () {
  25381. return this._activeBones.current;
  25382. };
  25383. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25384. /**
  25385. * Gets the performance counter for active bones
  25386. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25387. */
  25388. get: function () {
  25389. return this._activeBones;
  25390. },
  25391. enumerable: true,
  25392. configurable: true
  25393. });
  25394. /** @hidden */
  25395. Scene.prototype.getInterFramePerfCounter = function () {
  25396. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25397. return 0;
  25398. };
  25399. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25400. /** @hidden */
  25401. get: function () {
  25402. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25403. return null;
  25404. },
  25405. enumerable: true,
  25406. configurable: true
  25407. });
  25408. /** @hidden */
  25409. Scene.prototype.getLastFrameDuration = function () {
  25410. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25411. return 0;
  25412. };
  25413. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25414. /** @hidden */
  25415. get: function () {
  25416. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25417. return null;
  25418. },
  25419. enumerable: true,
  25420. configurable: true
  25421. });
  25422. /** @hidden */
  25423. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25424. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25425. return 0;
  25426. };
  25427. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25428. /** @hidden */
  25429. get: function () {
  25430. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25431. return null;
  25432. },
  25433. enumerable: true,
  25434. configurable: true
  25435. });
  25436. /**
  25437. * Gets the array of active meshes
  25438. * @returns an array of AbstractMesh
  25439. */
  25440. Scene.prototype.getActiveMeshes = function () {
  25441. return this._activeMeshes;
  25442. };
  25443. /** @hidden */
  25444. Scene.prototype.getRenderTargetsDuration = function () {
  25445. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25446. return 0;
  25447. };
  25448. /** @hidden */
  25449. Scene.prototype.getRenderDuration = function () {
  25450. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25451. return 0;
  25452. };
  25453. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25454. /** @hidden */
  25455. get: function () {
  25456. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25457. return null;
  25458. },
  25459. enumerable: true,
  25460. configurable: true
  25461. });
  25462. /** @hidden */
  25463. Scene.prototype.getParticlesDuration = function () {
  25464. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25465. return 0;
  25466. };
  25467. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25468. /** @hidden */
  25469. get: function () {
  25470. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25471. return null;
  25472. },
  25473. enumerable: true,
  25474. configurable: true
  25475. });
  25476. /** @hidden */
  25477. Scene.prototype.getSpritesDuration = function () {
  25478. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25479. return 0;
  25480. };
  25481. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25482. /** @hidden */
  25483. get: function () {
  25484. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25485. return null;
  25486. },
  25487. enumerable: true,
  25488. configurable: true
  25489. });
  25490. /**
  25491. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25492. * @returns a number
  25493. */
  25494. Scene.prototype.getAnimationRatio = function () {
  25495. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25496. };
  25497. /**
  25498. * Gets an unique Id for the current render phase
  25499. * @returns a number
  25500. */
  25501. Scene.prototype.getRenderId = function () {
  25502. return this._renderId;
  25503. };
  25504. /**
  25505. * Gets an unique Id for the current frame
  25506. * @returns a number
  25507. */
  25508. Scene.prototype.getFrameId = function () {
  25509. return this._frameId;
  25510. };
  25511. /** Call this function if you want to manually increment the render Id*/
  25512. Scene.prototype.incrementRenderId = function () {
  25513. this._renderId++;
  25514. };
  25515. Scene.prototype._updatePointerPosition = function (evt) {
  25516. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25517. if (!canvasRect) {
  25518. return;
  25519. }
  25520. this._pointerX = evt.clientX - canvasRect.left;
  25521. this._pointerY = evt.clientY - canvasRect.top;
  25522. this._unTranslatedPointerX = this._pointerX;
  25523. this._unTranslatedPointerY = this._pointerY;
  25524. };
  25525. Scene.prototype._createUbo = function () {
  25526. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25527. this._sceneUbo.addUniform("viewProjection", 16);
  25528. this._sceneUbo.addUniform("view", 16);
  25529. };
  25530. Scene.prototype._createAlternateUbo = function () {
  25531. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25532. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25533. this._alternateSceneUbo.addUniform("view", 16);
  25534. };
  25535. // Pointers handling
  25536. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25537. if (pointerInfo.pickInfo) {
  25538. if (!pointerInfo.pickInfo.ray) {
  25539. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25540. }
  25541. }
  25542. };
  25543. /**
  25544. * Use this method to simulate a pointer move on a mesh
  25545. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25546. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25547. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25548. * @returns the current scene
  25549. */
  25550. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25551. var evt = new PointerEvent("pointermove", pointerEventInit);
  25552. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25553. return this;
  25554. }
  25555. return this._processPointerMove(pickResult, evt);
  25556. };
  25557. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25558. var canvas = this._engine.getRenderingCanvas();
  25559. if (!canvas) {
  25560. return this;
  25561. }
  25562. // Restore pointer
  25563. canvas.style.cursor = this.defaultCursor;
  25564. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25565. if (isMeshPicked) {
  25566. this.setPointerOverMesh(pickResult.pickedMesh);
  25567. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25568. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25569. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25570. }
  25571. else {
  25572. canvas.style.cursor = this.hoverCursor;
  25573. }
  25574. }
  25575. }
  25576. else {
  25577. this.setPointerOverMesh(null);
  25578. }
  25579. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25580. var step = _a[_i];
  25581. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25582. }
  25583. if (pickResult) {
  25584. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25585. if (this.onPointerMove) {
  25586. this.onPointerMove(evt, pickResult, type);
  25587. }
  25588. if (this.onPointerObservable.hasObservers()) {
  25589. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25590. this._setRayOnPointerInfo(pi);
  25591. this.onPointerObservable.notifyObservers(pi, type);
  25592. }
  25593. }
  25594. return this;
  25595. };
  25596. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25597. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25598. if (pickResult) {
  25599. pi.ray = pickResult.ray;
  25600. }
  25601. this.onPrePointerObservable.notifyObservers(pi, type);
  25602. if (pi.skipOnPointerObservable) {
  25603. return true;
  25604. }
  25605. else {
  25606. return false;
  25607. }
  25608. };
  25609. /**
  25610. * Use this method to simulate a pointer down on a mesh
  25611. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25612. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25613. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25614. * @returns the current scene
  25615. */
  25616. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25617. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25618. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25619. return this;
  25620. }
  25621. return this._processPointerDown(pickResult, evt);
  25622. };
  25623. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25624. var _this = this;
  25625. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25626. this._pickedDownMesh = pickResult.pickedMesh;
  25627. var actionManager = pickResult.pickedMesh.actionManager;
  25628. if (actionManager) {
  25629. if (actionManager.hasPickTriggers) {
  25630. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25631. switch (evt.button) {
  25632. case 0:
  25633. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25634. break;
  25635. case 1:
  25636. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25637. break;
  25638. case 2:
  25639. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25640. break;
  25641. }
  25642. }
  25643. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25644. window.setTimeout(function () {
  25645. 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);
  25646. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25647. if (_this._totalPointersPressed !== 0 &&
  25648. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25649. !_this._isPointerSwiping()) {
  25650. _this._startingPointerTime = 0;
  25651. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25652. }
  25653. }
  25654. }, Scene.LongPressDelay);
  25655. }
  25656. }
  25657. }
  25658. else {
  25659. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25660. var step = _a[_i];
  25661. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25662. }
  25663. }
  25664. if (pickResult) {
  25665. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25666. if (this.onPointerDown) {
  25667. this.onPointerDown(evt, pickResult, type);
  25668. }
  25669. if (this.onPointerObservable.hasObservers()) {
  25670. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25671. this._setRayOnPointerInfo(pi);
  25672. this.onPointerObservable.notifyObservers(pi, type);
  25673. }
  25674. }
  25675. return this;
  25676. };
  25677. /**
  25678. * Use this method to simulate a pointer up on a mesh
  25679. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25680. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25681. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25682. * @returns the current scene
  25683. */
  25684. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25685. var evt = new PointerEvent("pointerup", pointerEventInit);
  25686. var clickInfo = new ClickInfo();
  25687. clickInfo.singleClick = true;
  25688. clickInfo.ignore = true;
  25689. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25690. return this;
  25691. }
  25692. return this._processPointerUp(pickResult, evt, clickInfo);
  25693. };
  25694. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25695. if (pickResult && pickResult && pickResult.pickedMesh) {
  25696. this._pickedUpMesh = pickResult.pickedMesh;
  25697. if (this._pickedDownMesh === this._pickedUpMesh) {
  25698. if (this.onPointerPick) {
  25699. this.onPointerPick(evt, pickResult);
  25700. }
  25701. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25702. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25703. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25704. this._setRayOnPointerInfo(pi);
  25705. this.onPointerObservable.notifyObservers(pi, type_1);
  25706. }
  25707. }
  25708. if (pickResult.pickedMesh.actionManager) {
  25709. if (clickInfo.ignore) {
  25710. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25711. }
  25712. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25713. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25714. }
  25715. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25716. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25717. }
  25718. }
  25719. }
  25720. else {
  25721. if (!clickInfo.ignore) {
  25722. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25723. var step = _a[_i];
  25724. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25725. }
  25726. }
  25727. }
  25728. if (this._pickedDownMesh &&
  25729. this._pickedDownMesh.actionManager &&
  25730. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25731. this._pickedDownMesh !== this._pickedUpMesh) {
  25732. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25733. }
  25734. var type = BABYLON.PointerEventTypes.POINTERUP;
  25735. if (this.onPointerObservable.hasObservers()) {
  25736. if (!clickInfo.ignore) {
  25737. if (!clickInfo.hasSwiped) {
  25738. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25739. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25740. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25741. this._setRayOnPointerInfo(pi);
  25742. this.onPointerObservable.notifyObservers(pi, type_2);
  25743. }
  25744. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25745. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25746. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25747. this._setRayOnPointerInfo(pi);
  25748. this.onPointerObservable.notifyObservers(pi, type_3);
  25749. }
  25750. }
  25751. }
  25752. else {
  25753. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25754. this._setRayOnPointerInfo(pi);
  25755. this.onPointerObservable.notifyObservers(pi, type);
  25756. }
  25757. }
  25758. if (this.onPointerUp) {
  25759. this.onPointerUp(evt, pickResult, type);
  25760. }
  25761. return this;
  25762. };
  25763. /**
  25764. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25765. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25766. * @returns true if the pointer was captured
  25767. */
  25768. Scene.prototype.isPointerCaptured = function (pointerId) {
  25769. if (pointerId === void 0) { pointerId = 0; }
  25770. return this._pointerCaptures[pointerId];
  25771. };
  25772. /** @hidden */
  25773. Scene.prototype._isPointerSwiping = function () {
  25774. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25775. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25776. };
  25777. /**
  25778. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25779. * @param attachUp defines if you want to attach events to pointerup
  25780. * @param attachDown defines if you want to attach events to pointerdown
  25781. * @param attachMove defines if you want to attach events to pointermove
  25782. */
  25783. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25784. var _this = this;
  25785. if (attachUp === void 0) { attachUp = true; }
  25786. if (attachDown === void 0) { attachDown = true; }
  25787. if (attachMove === void 0) { attachMove = true; }
  25788. this._initActionManager = function (act, clickInfo) {
  25789. if (!_this._meshPickProceed) {
  25790. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25791. _this._currentPickResult = pickResult;
  25792. if (pickResult) {
  25793. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25794. }
  25795. _this._meshPickProceed = true;
  25796. }
  25797. return act;
  25798. };
  25799. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25800. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25801. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25802. btn !== _this._previousButtonPressed) {
  25803. _this._doubleClickOccured = false;
  25804. clickInfo.singleClick = true;
  25805. clickInfo.ignore = false;
  25806. cb(clickInfo, _this._currentPickResult);
  25807. }
  25808. };
  25809. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25810. var clickInfo = new ClickInfo();
  25811. _this._currentPickResult = null;
  25812. var act = null;
  25813. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25814. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25815. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25816. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25817. act = _this._initActionManager(act, clickInfo);
  25818. if (act)
  25819. checkPicking = act.hasPickTriggers;
  25820. }
  25821. if (checkPicking) {
  25822. var btn = evt.button;
  25823. clickInfo.hasSwiped = _this._isPointerSwiping();
  25824. if (!clickInfo.hasSwiped) {
  25825. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25826. if (!checkSingleClickImmediately) {
  25827. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25828. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25829. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25830. act = _this._initActionManager(act, clickInfo);
  25831. if (act)
  25832. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25833. }
  25834. }
  25835. if (checkSingleClickImmediately) {
  25836. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25837. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25838. btn !== _this._previousButtonPressed) {
  25839. clickInfo.singleClick = true;
  25840. cb(clickInfo, _this._currentPickResult);
  25841. }
  25842. }
  25843. // at least one double click is required to be check and exclusive double click is enabled
  25844. else {
  25845. // wait that no double click has been raised during the double click delay
  25846. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25847. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25848. }
  25849. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25850. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25851. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25852. act = _this._initActionManager(act, clickInfo);
  25853. if (act)
  25854. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25855. }
  25856. if (checkDoubleClick) {
  25857. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25858. if (btn === _this._previousButtonPressed &&
  25859. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25860. !_this._doubleClickOccured) {
  25861. // pointer has not moved for 2 clicks, it's a double click
  25862. if (!clickInfo.hasSwiped &&
  25863. !_this._isPointerSwiping()) {
  25864. _this._previousStartingPointerTime = 0;
  25865. _this._doubleClickOccured = true;
  25866. clickInfo.doubleClick = true;
  25867. clickInfo.ignore = false;
  25868. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25869. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25870. }
  25871. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25872. cb(clickInfo, _this._currentPickResult);
  25873. }
  25874. // if the two successive clicks are too far, it's just two simple clicks
  25875. else {
  25876. _this._doubleClickOccured = false;
  25877. _this._previousStartingPointerTime = _this._startingPointerTime;
  25878. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25879. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25880. _this._previousButtonPressed = btn;
  25881. if (Scene.ExclusiveDoubleClickMode) {
  25882. if (_this._previousDelayedSimpleClickTimeout) {
  25883. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25884. }
  25885. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25886. cb(clickInfo, _this._previousPickResult);
  25887. }
  25888. else {
  25889. cb(clickInfo, _this._currentPickResult);
  25890. }
  25891. }
  25892. }
  25893. // just the first click of the double has been raised
  25894. else {
  25895. _this._doubleClickOccured = false;
  25896. _this._previousStartingPointerTime = _this._startingPointerTime;
  25897. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25898. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25899. _this._previousButtonPressed = btn;
  25900. }
  25901. }
  25902. }
  25903. }
  25904. clickInfo.ignore = true;
  25905. cb(clickInfo, _this._currentPickResult);
  25906. };
  25907. this._onPointerMove = function (evt) {
  25908. _this._updatePointerPosition(evt);
  25909. // PreObservable support
  25910. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25911. return;
  25912. }
  25913. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25914. return;
  25915. }
  25916. if (!_this.pointerMovePredicate) {
  25917. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25918. }
  25919. // Meshes
  25920. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25921. _this._processPointerMove(pickResult, evt);
  25922. };
  25923. this._onPointerDown = function (evt) {
  25924. _this._totalPointersPressed++;
  25925. _this._pickedDownMesh = null;
  25926. _this._meshPickProceed = false;
  25927. _this._updatePointerPosition(evt);
  25928. if (_this.preventDefaultOnPointerDown && canvas) {
  25929. evt.preventDefault();
  25930. canvas.focus();
  25931. }
  25932. // PreObservable support
  25933. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25934. return;
  25935. }
  25936. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25937. return;
  25938. }
  25939. _this._pointerCaptures[evt.pointerId] = true;
  25940. _this._startingPointerPosition.x = _this._pointerX;
  25941. _this._startingPointerPosition.y = _this._pointerY;
  25942. _this._startingPointerTime = Date.now();
  25943. if (!_this.pointerDownPredicate) {
  25944. _this.pointerDownPredicate = function (mesh) {
  25945. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25946. };
  25947. }
  25948. // Meshes
  25949. _this._pickedDownMesh = null;
  25950. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25951. _this._processPointerDown(pickResult, evt);
  25952. };
  25953. this._onPointerUp = function (evt) {
  25954. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25955. return; // So we need to test it the pointer down was pressed before.
  25956. }
  25957. _this._totalPointersPressed--;
  25958. _this._pickedUpMesh = null;
  25959. _this._meshPickProceed = false;
  25960. _this._updatePointerPosition(evt);
  25961. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25962. // PreObservable support
  25963. if (_this.onPrePointerObservable.hasObservers()) {
  25964. if (!clickInfo.ignore) {
  25965. if (!clickInfo.hasSwiped) {
  25966. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25967. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25968. return;
  25969. }
  25970. }
  25971. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25972. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25973. return;
  25974. }
  25975. }
  25976. }
  25977. }
  25978. else {
  25979. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25980. return;
  25981. }
  25982. }
  25983. }
  25984. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25985. return;
  25986. }
  25987. _this._pointerCaptures[evt.pointerId] = false;
  25988. if (!_this.pointerUpPredicate) {
  25989. _this.pointerUpPredicate = function (mesh) {
  25990. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25991. };
  25992. }
  25993. // Meshes
  25994. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25995. _this._initActionManager(null, clickInfo);
  25996. }
  25997. if (!pickResult) {
  25998. pickResult = _this._currentPickResult;
  25999. }
  26000. _this._processPointerUp(pickResult, evt, clickInfo);
  26001. _this._previousPickResult = _this._currentPickResult;
  26002. });
  26003. };
  26004. this._onKeyDown = function (evt) {
  26005. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26006. if (_this.onPreKeyboardObservable.hasObservers()) {
  26007. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26008. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26009. if (pi.skipOnPointerObservable) {
  26010. return;
  26011. }
  26012. }
  26013. if (_this.onKeyboardObservable.hasObservers()) {
  26014. var pi = new BABYLON.KeyboardInfo(type, evt);
  26015. _this.onKeyboardObservable.notifyObservers(pi, type);
  26016. }
  26017. if (_this.actionManager) {
  26018. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26019. }
  26020. };
  26021. this._onKeyUp = function (evt) {
  26022. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26023. if (_this.onPreKeyboardObservable.hasObservers()) {
  26024. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26025. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26026. if (pi.skipOnPointerObservable) {
  26027. return;
  26028. }
  26029. }
  26030. if (_this.onKeyboardObservable.hasObservers()) {
  26031. var pi = new BABYLON.KeyboardInfo(type, evt);
  26032. _this.onKeyboardObservable.notifyObservers(pi, type);
  26033. }
  26034. if (_this.actionManager) {
  26035. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26036. }
  26037. };
  26038. var engine = this.getEngine();
  26039. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26040. if (!canvas) {
  26041. return;
  26042. }
  26043. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26044. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26045. });
  26046. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26047. if (!canvas) {
  26048. return;
  26049. }
  26050. canvas.removeEventListener("keydown", _this._onKeyDown);
  26051. canvas.removeEventListener("keyup", _this._onKeyUp);
  26052. });
  26053. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26054. var canvas = this._engine.getRenderingCanvas();
  26055. if (!canvas) {
  26056. return;
  26057. }
  26058. if (attachMove) {
  26059. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26060. // Wheel
  26061. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26062. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26063. }
  26064. if (attachDown) {
  26065. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26066. }
  26067. if (attachUp) {
  26068. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26069. }
  26070. canvas.tabIndex = 1;
  26071. };
  26072. /** Detaches all event handlers*/
  26073. Scene.prototype.detachControl = function () {
  26074. var engine = this.getEngine();
  26075. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26076. var canvas = engine.getRenderingCanvas();
  26077. if (!canvas) {
  26078. return;
  26079. }
  26080. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26081. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26082. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26083. if (this._onCanvasBlurObserver) {
  26084. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26085. }
  26086. if (this._onCanvasFocusObserver) {
  26087. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26088. }
  26089. // Wheel
  26090. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26091. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26092. // Keyboard
  26093. canvas.removeEventListener("keydown", this._onKeyDown);
  26094. canvas.removeEventListener("keyup", this._onKeyUp);
  26095. // Observables
  26096. this.onKeyboardObservable.clear();
  26097. this.onPreKeyboardObservable.clear();
  26098. this.onPointerObservable.clear();
  26099. this.onPrePointerObservable.clear();
  26100. };
  26101. /**
  26102. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26103. * Delay loaded resources are not taking in account
  26104. * @return true if all required resources are ready
  26105. */
  26106. Scene.prototype.isReady = function () {
  26107. if (this._isDisposed) {
  26108. return false;
  26109. }
  26110. if (this._pendingData.length > 0) {
  26111. return false;
  26112. }
  26113. var index;
  26114. var engine = this.getEngine();
  26115. // Geometries
  26116. for (index = 0; index < this.geometries.length; index++) {
  26117. var geometry = this.geometries[index];
  26118. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26119. return false;
  26120. }
  26121. }
  26122. // Meshes
  26123. for (index = 0; index < this.meshes.length; index++) {
  26124. var mesh = this.meshes[index];
  26125. if (!mesh.isEnabled()) {
  26126. continue;
  26127. }
  26128. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26129. continue;
  26130. }
  26131. if (!mesh.isReady(true)) {
  26132. return false;
  26133. }
  26134. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26135. // Is Ready For Mesh
  26136. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26137. var step = _a[_i];
  26138. if (!step.action(mesh, hardwareInstancedRendering)) {
  26139. return false;
  26140. }
  26141. }
  26142. }
  26143. // Post-processes
  26144. if (this.activeCameras && this.activeCameras.length > 0) {
  26145. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26146. var camera = _c[_b];
  26147. if (!camera.isReady(true)) {
  26148. return false;
  26149. }
  26150. }
  26151. }
  26152. else if (this.activeCamera) {
  26153. if (!this.activeCamera.isReady(true)) {
  26154. return false;
  26155. }
  26156. }
  26157. // Particles
  26158. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26159. var particleSystem = _e[_d];
  26160. if (!particleSystem.isReady()) {
  26161. return false;
  26162. }
  26163. }
  26164. return true;
  26165. };
  26166. /** Resets all cached information relative to material (including effect and visibility) */
  26167. Scene.prototype.resetCachedMaterial = function () {
  26168. this._cachedMaterial = null;
  26169. this._cachedEffect = null;
  26170. this._cachedVisibility = null;
  26171. };
  26172. /**
  26173. * Registers a function to be called before every frame render
  26174. * @param func defines the function to register
  26175. */
  26176. Scene.prototype.registerBeforeRender = function (func) {
  26177. this.onBeforeRenderObservable.add(func);
  26178. };
  26179. /**
  26180. * Unregisters a function called before every frame render
  26181. * @param func defines the function to unregister
  26182. */
  26183. Scene.prototype.unregisterBeforeRender = function (func) {
  26184. this.onBeforeRenderObservable.removeCallback(func);
  26185. };
  26186. /**
  26187. * Registers a function to be called after every frame render
  26188. * @param func defines the function to register
  26189. */
  26190. Scene.prototype.registerAfterRender = function (func) {
  26191. this.onAfterRenderObservable.add(func);
  26192. };
  26193. /**
  26194. * Unregisters a function called after every frame render
  26195. * @param func defines the function to unregister
  26196. */
  26197. Scene.prototype.unregisterAfterRender = function (func) {
  26198. this.onAfterRenderObservable.removeCallback(func);
  26199. };
  26200. Scene.prototype._executeOnceBeforeRender = function (func) {
  26201. var _this = this;
  26202. var execFunc = function () {
  26203. func();
  26204. setTimeout(function () {
  26205. _this.unregisterBeforeRender(execFunc);
  26206. });
  26207. };
  26208. this.registerBeforeRender(execFunc);
  26209. };
  26210. /**
  26211. * The provided function will run before render once and will be disposed afterwards.
  26212. * A timeout delay can be provided so that the function will be executed in N ms.
  26213. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26214. * @param func The function to be executed.
  26215. * @param timeout optional delay in ms
  26216. */
  26217. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26218. var _this = this;
  26219. if (timeout !== undefined) {
  26220. setTimeout(function () {
  26221. _this._executeOnceBeforeRender(func);
  26222. }, timeout);
  26223. }
  26224. else {
  26225. this._executeOnceBeforeRender(func);
  26226. }
  26227. };
  26228. /** @hidden */
  26229. Scene.prototype._addPendingData = function (data) {
  26230. this._pendingData.push(data);
  26231. };
  26232. /** @hidden */
  26233. Scene.prototype._removePendingData = function (data) {
  26234. var wasLoading = this.isLoading;
  26235. var index = this._pendingData.indexOf(data);
  26236. if (index !== -1) {
  26237. this._pendingData.splice(index, 1);
  26238. }
  26239. if (wasLoading && !this.isLoading) {
  26240. this.onDataLoadedObservable.notifyObservers(this);
  26241. }
  26242. };
  26243. /**
  26244. * Returns the number of items waiting to be loaded
  26245. * @returns the number of items waiting to be loaded
  26246. */
  26247. Scene.prototype.getWaitingItemsCount = function () {
  26248. return this._pendingData.length;
  26249. };
  26250. Object.defineProperty(Scene.prototype, "isLoading", {
  26251. /**
  26252. * Returns a boolean indicating if the scene is still loading data
  26253. */
  26254. get: function () {
  26255. return this._pendingData.length > 0;
  26256. },
  26257. enumerable: true,
  26258. configurable: true
  26259. });
  26260. /**
  26261. * Registers a function to be executed when the scene is ready
  26262. * @param {Function} func - the function to be executed
  26263. */
  26264. Scene.prototype.executeWhenReady = function (func) {
  26265. var _this = this;
  26266. this.onReadyObservable.add(func);
  26267. if (this._executeWhenReadyTimeoutId !== -1) {
  26268. return;
  26269. }
  26270. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26271. _this._checkIsReady();
  26272. }, 150);
  26273. };
  26274. /**
  26275. * Returns a promise that resolves when the scene is ready
  26276. * @returns A promise that resolves when the scene is ready
  26277. */
  26278. Scene.prototype.whenReadyAsync = function () {
  26279. var _this = this;
  26280. return new Promise(function (resolve) {
  26281. _this.executeWhenReady(function () {
  26282. resolve();
  26283. });
  26284. });
  26285. };
  26286. /** @hidden */
  26287. Scene.prototype._checkIsReady = function () {
  26288. var _this = this;
  26289. this._registerTransientComponents();
  26290. if (this.isReady()) {
  26291. this.onReadyObservable.notifyObservers(this);
  26292. this.onReadyObservable.clear();
  26293. this._executeWhenReadyTimeoutId = -1;
  26294. return;
  26295. }
  26296. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26297. _this._checkIsReady();
  26298. }, 150);
  26299. };
  26300. // Animations
  26301. /**
  26302. * Will start the animation sequence of a given target
  26303. * @param target defines the target
  26304. * @param from defines from which frame should animation start
  26305. * @param to defines until which frame should animation run.
  26306. * @param weight defines the weight to apply to the animation (1.0 by default)
  26307. * @param loop defines if the animation loops
  26308. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26309. * @param onAnimationEnd defines the function to be executed when the animation ends
  26310. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26311. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26312. * @returns the animatable object created for this animation
  26313. */
  26314. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26315. if (weight === void 0) { weight = 1.0; }
  26316. if (speedRatio === void 0) { speedRatio = 1.0; }
  26317. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26318. returnedAnimatable.weight = weight;
  26319. return returnedAnimatable;
  26320. };
  26321. /**
  26322. * Will start the animation sequence of a given target
  26323. * @param target defines the target
  26324. * @param from defines from which frame should animation start
  26325. * @param to defines until which frame should animation run.
  26326. * @param loop defines if the animation loops
  26327. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26328. * @param onAnimationEnd defines the function to be executed when the animation ends
  26329. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26330. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26331. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26332. * @returns the animatable object created for this animation
  26333. */
  26334. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26335. if (speedRatio === void 0) { speedRatio = 1.0; }
  26336. if (stopCurrent === void 0) { stopCurrent = true; }
  26337. if (from > to && speedRatio > 0) {
  26338. speedRatio *= -1;
  26339. }
  26340. if (stopCurrent) {
  26341. this.stopAnimation(target, undefined, targetMask);
  26342. }
  26343. if (!animatable) {
  26344. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26345. }
  26346. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26347. // Local animations
  26348. if (target.animations && shouldRunTargetAnimations) {
  26349. animatable.appendAnimations(target, target.animations);
  26350. }
  26351. // Children animations
  26352. if (target.getAnimatables) {
  26353. var animatables = target.getAnimatables();
  26354. for (var index = 0; index < animatables.length; index++) {
  26355. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26356. }
  26357. }
  26358. animatable.reset();
  26359. return animatable;
  26360. };
  26361. /**
  26362. * Begin a new animation on a given node
  26363. * @param target defines the target where the animation will take place
  26364. * @param animations defines the list of animations to start
  26365. * @param from defines the initial value
  26366. * @param to defines the final value
  26367. * @param loop defines if you want animation to loop (off by default)
  26368. * @param speedRatio defines the speed ratio to apply to all animations
  26369. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26370. * @returns the list of created animatables
  26371. */
  26372. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26373. if (speedRatio === undefined) {
  26374. speedRatio = 1.0;
  26375. }
  26376. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26377. return animatable;
  26378. };
  26379. /**
  26380. * Begin a new animation on a given node and its hierarchy
  26381. * @param target defines the root node where the animation will take place
  26382. * @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.
  26383. * @param animations defines the list of animations to start
  26384. * @param from defines the initial value
  26385. * @param to defines the final value
  26386. * @param loop defines if you want animation to loop (off by default)
  26387. * @param speedRatio defines the speed ratio to apply to all animations
  26388. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26389. * @returns the list of animatables created for all nodes
  26390. */
  26391. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26392. var children = target.getDescendants(directDescendantsOnly);
  26393. var result = [];
  26394. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26395. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26396. var child = children_1[_i];
  26397. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26398. }
  26399. return result;
  26400. };
  26401. /**
  26402. * Gets the animatable associated with a specific target
  26403. * @param target defines the target of the animatable
  26404. * @returns the required animatable if found
  26405. */
  26406. Scene.prototype.getAnimatableByTarget = function (target) {
  26407. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26408. if (this._activeAnimatables[index].target === target) {
  26409. return this._activeAnimatables[index];
  26410. }
  26411. }
  26412. return null;
  26413. };
  26414. /**
  26415. * Gets all animatables associated with a given target
  26416. * @param target defines the target to look animatables for
  26417. * @returns an array of Animatables
  26418. */
  26419. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26420. var result = [];
  26421. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26422. if (this._activeAnimatables[index].target === target) {
  26423. result.push(this._activeAnimatables[index]);
  26424. }
  26425. }
  26426. return result;
  26427. };
  26428. Object.defineProperty(Scene.prototype, "animatables", {
  26429. /**
  26430. * Gets all animatable attached to the scene
  26431. */
  26432. get: function () {
  26433. return this._activeAnimatables;
  26434. },
  26435. enumerable: true,
  26436. configurable: true
  26437. });
  26438. /**
  26439. * Will stop the animation of the given target
  26440. * @param target - the target
  26441. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26442. * @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)
  26443. */
  26444. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26445. var animatables = this.getAllAnimatablesByTarget(target);
  26446. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26447. var animatable = animatables_1[_i];
  26448. animatable.stop(animationName, targetMask);
  26449. }
  26450. };
  26451. /**
  26452. * Stops and removes all animations that have been applied to the scene
  26453. */
  26454. Scene.prototype.stopAllAnimations = function () {
  26455. if (this._activeAnimatables) {
  26456. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26457. this._activeAnimatables[i].stop();
  26458. }
  26459. this._activeAnimatables = [];
  26460. }
  26461. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26462. var group = _a[_i];
  26463. group.stop();
  26464. }
  26465. };
  26466. Scene.prototype._animate = function () {
  26467. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26468. return;
  26469. }
  26470. // Getting time
  26471. var now = BABYLON.Tools.Now;
  26472. if (!this._animationTimeLast) {
  26473. if (this._pendingData.length > 0) {
  26474. return;
  26475. }
  26476. this._animationTimeLast = now;
  26477. }
  26478. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26479. this._animationTime += deltaTime;
  26480. this._animationTimeLast = now;
  26481. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26482. this._activeAnimatables[index]._animate(this._animationTime);
  26483. }
  26484. // Late animation bindings
  26485. this._processLateAnimationBindings();
  26486. };
  26487. /** @hidden */
  26488. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26489. var target = runtimeAnimation.target;
  26490. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26491. if (!target._lateAnimationHolders) {
  26492. target._lateAnimationHolders = {};
  26493. }
  26494. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26495. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26496. totalWeight: 0,
  26497. animations: [],
  26498. originalValue: originalValue
  26499. };
  26500. }
  26501. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26502. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26503. };
  26504. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26505. var normalizer = 1.0;
  26506. var finalPosition = BABYLON.Tmp.Vector3[0];
  26507. var finalScaling = BABYLON.Tmp.Vector3[1];
  26508. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26509. var startIndex = 0;
  26510. var originalAnimation = holder.animations[0];
  26511. var originalValue = holder.originalValue;
  26512. var scale = 1;
  26513. if (holder.totalWeight < 1.0) {
  26514. // We need to mix the original value in
  26515. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26516. scale = 1.0 - holder.totalWeight;
  26517. }
  26518. else {
  26519. startIndex = 1;
  26520. // We need to normalize the weights
  26521. normalizer = holder.totalWeight;
  26522. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26523. scale = originalAnimation.weight / normalizer;
  26524. if (scale == 1) {
  26525. return originalAnimation.currentValue;
  26526. }
  26527. }
  26528. finalScaling.scaleInPlace(scale);
  26529. finalPosition.scaleInPlace(scale);
  26530. finalQuaternion.scaleInPlace(scale);
  26531. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26532. var runtimeAnimation = holder.animations[animIndex];
  26533. var scale = runtimeAnimation.weight / normalizer;
  26534. var currentPosition = BABYLON.Tmp.Vector3[2];
  26535. var currentScaling = BABYLON.Tmp.Vector3[3];
  26536. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26537. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26538. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26539. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26540. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26541. }
  26542. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26543. return originalAnimation._workValue;
  26544. };
  26545. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26546. var originalAnimation = holder.animations[0];
  26547. var originalValue = holder.originalValue;
  26548. if (holder.animations.length === 1) {
  26549. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26550. return refQuaternion;
  26551. }
  26552. var normalizer = 1.0;
  26553. var quaternions;
  26554. var weights;
  26555. if (holder.totalWeight < 1.0) {
  26556. var scale = 1.0 - holder.totalWeight;
  26557. quaternions = [];
  26558. weights = [];
  26559. quaternions.push(originalValue);
  26560. weights.push(scale);
  26561. }
  26562. else {
  26563. if (holder.animations.length === 2) { // Slerp as soon as we can
  26564. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26565. return refQuaternion;
  26566. }
  26567. quaternions = [];
  26568. weights = [];
  26569. normalizer = holder.totalWeight;
  26570. }
  26571. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26572. var runtimeAnimation = holder.animations[animIndex];
  26573. quaternions.push(runtimeAnimation.currentValue);
  26574. weights.push(runtimeAnimation.weight / normalizer);
  26575. }
  26576. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26577. var cumulativeAmount = 0;
  26578. var cumulativeQuaternion = null;
  26579. for (var index = 0; index < quaternions.length;) {
  26580. if (!cumulativeQuaternion) {
  26581. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26582. cumulativeQuaternion = refQuaternion;
  26583. cumulativeAmount = weights[index] + weights[index + 1];
  26584. index += 2;
  26585. continue;
  26586. }
  26587. cumulativeAmount += weights[index];
  26588. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26589. index++;
  26590. }
  26591. return cumulativeQuaternion;
  26592. };
  26593. Scene.prototype._processLateAnimationBindings = function () {
  26594. if (!this._registeredForLateAnimationBindings.length) {
  26595. return;
  26596. }
  26597. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26598. var target = this._registeredForLateAnimationBindings.data[index];
  26599. for (var path in target._lateAnimationHolders) {
  26600. var holder = target._lateAnimationHolders[path];
  26601. var originalAnimation = holder.animations[0];
  26602. var originalValue = holder.originalValue;
  26603. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26604. var finalValue = target[path];
  26605. if (matrixDecomposeMode) {
  26606. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26607. }
  26608. else {
  26609. var quaternionMode = originalValue.w !== undefined;
  26610. if (quaternionMode) {
  26611. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26612. }
  26613. else {
  26614. var startIndex = 0;
  26615. var normalizer = 1.0;
  26616. if (holder.totalWeight < 1.0) {
  26617. // We need to mix the original value in
  26618. if (originalValue.scale) {
  26619. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26620. }
  26621. else {
  26622. finalValue = originalValue * (1.0 - holder.totalWeight);
  26623. }
  26624. }
  26625. else {
  26626. // We need to normalize the weights
  26627. normalizer = holder.totalWeight;
  26628. var scale_1 = originalAnimation.weight / normalizer;
  26629. if (scale_1 !== 1) {
  26630. if (originalAnimation.currentValue.scale) {
  26631. finalValue = originalAnimation.currentValue.scale(scale_1);
  26632. }
  26633. else {
  26634. finalValue = originalAnimation.currentValue * scale_1;
  26635. }
  26636. }
  26637. else {
  26638. finalValue = originalAnimation.currentValue;
  26639. }
  26640. startIndex = 1;
  26641. }
  26642. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26643. var runtimeAnimation = holder.animations[animIndex];
  26644. var scale = runtimeAnimation.weight / normalizer;
  26645. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26646. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26647. }
  26648. else {
  26649. finalValue += runtimeAnimation.currentValue * scale;
  26650. }
  26651. }
  26652. }
  26653. }
  26654. target[path] = finalValue;
  26655. }
  26656. target._lateAnimationHolders = {};
  26657. }
  26658. this._registeredForLateAnimationBindings.reset();
  26659. };
  26660. // Matrix
  26661. /** @hidden */
  26662. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26663. this._useAlternateCameraConfiguration = active;
  26664. };
  26665. /**
  26666. * Gets the current view matrix
  26667. * @returns a Matrix
  26668. */
  26669. Scene.prototype.getViewMatrix = function () {
  26670. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26671. };
  26672. /**
  26673. * Gets the current projection matrix
  26674. * @returns a Matrix
  26675. */
  26676. Scene.prototype.getProjectionMatrix = function () {
  26677. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26678. };
  26679. /**
  26680. * Gets the current transform matrix
  26681. * @returns a Matrix made of View * Projection
  26682. */
  26683. Scene.prototype.getTransformMatrix = function () {
  26684. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26685. };
  26686. /**
  26687. * Sets the current transform matrix
  26688. * @param view defines the View matrix to use
  26689. * @param projection defines the Projection matrix to use
  26690. */
  26691. Scene.prototype.setTransformMatrix = function (view, projection) {
  26692. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26693. return;
  26694. }
  26695. this._viewUpdateFlag = view.updateFlag;
  26696. this._projectionUpdateFlag = projection.updateFlag;
  26697. this._viewMatrix = view;
  26698. this._projectionMatrix = projection;
  26699. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26700. // Update frustum
  26701. if (!this._frustumPlanes) {
  26702. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26703. }
  26704. else {
  26705. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26706. }
  26707. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26708. var otherCamera = this.activeCamera._alternateCamera;
  26709. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26710. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26711. }
  26712. if (this._sceneUbo.useUbo) {
  26713. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26714. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26715. this._sceneUbo.update();
  26716. }
  26717. };
  26718. /** @hidden */
  26719. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26720. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26721. return;
  26722. }
  26723. this._alternateViewUpdateFlag = view.updateFlag;
  26724. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26725. this._alternateViewMatrix = view;
  26726. this._alternateProjectionMatrix = projection;
  26727. if (!this._alternateTransformMatrix) {
  26728. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26729. }
  26730. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26731. if (!this._alternateSceneUbo) {
  26732. this._createAlternateUbo();
  26733. }
  26734. if (this._alternateSceneUbo.useUbo) {
  26735. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26736. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26737. this._alternateSceneUbo.update();
  26738. }
  26739. };
  26740. /**
  26741. * Gets the uniform buffer used to store scene data
  26742. * @returns a UniformBuffer
  26743. */
  26744. Scene.prototype.getSceneUniformBuffer = function () {
  26745. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26746. };
  26747. /**
  26748. * Gets an unique (relatively to the current scene) Id
  26749. * @returns an unique number for the scene
  26750. */
  26751. Scene.prototype.getUniqueId = function () {
  26752. var result = Scene._uniqueIdCounter;
  26753. Scene._uniqueIdCounter++;
  26754. return result;
  26755. };
  26756. /**
  26757. * Add a mesh to the list of scene's meshes
  26758. * @param newMesh defines the mesh to add
  26759. * @param recursive if all child meshes should also be added to the scene
  26760. */
  26761. Scene.prototype.addMesh = function (newMesh, recursive) {
  26762. var _this = this;
  26763. if (recursive === void 0) { recursive = false; }
  26764. this.meshes.push(newMesh);
  26765. //notify the collision coordinator
  26766. if (this.collisionCoordinator) {
  26767. this.collisionCoordinator.onMeshAdded(newMesh);
  26768. }
  26769. newMesh._resyncLightSources();
  26770. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26771. if (recursive) {
  26772. newMesh.getChildMeshes().forEach(function (m) {
  26773. _this.addMesh(m);
  26774. });
  26775. }
  26776. };
  26777. /**
  26778. * Remove a mesh for the list of scene's meshes
  26779. * @param toRemove defines the mesh to remove
  26780. * @param recursive if all child meshes should also be removed from the scene
  26781. * @returns the index where the mesh was in the mesh list
  26782. */
  26783. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26784. var _this = this;
  26785. if (recursive === void 0) { recursive = false; }
  26786. var index = this.meshes.indexOf(toRemove);
  26787. if (index !== -1) {
  26788. // Remove from the scene if mesh found
  26789. this.meshes.splice(index, 1);
  26790. }
  26791. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26792. if (recursive) {
  26793. toRemove.getChildMeshes().forEach(function (m) {
  26794. _this.removeMesh(m);
  26795. });
  26796. }
  26797. return index;
  26798. };
  26799. /**
  26800. * Add a transform node to the list of scene's transform nodes
  26801. * @param newTransformNode defines the transform node to add
  26802. */
  26803. Scene.prototype.addTransformNode = function (newTransformNode) {
  26804. this.transformNodes.push(newTransformNode);
  26805. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26806. };
  26807. /**
  26808. * Remove a transform node for the list of scene's transform nodes
  26809. * @param toRemove defines the transform node to remove
  26810. * @returns the index where the transform node was in the transform node list
  26811. */
  26812. Scene.prototype.removeTransformNode = function (toRemove) {
  26813. var index = this.transformNodes.indexOf(toRemove);
  26814. if (index !== -1) {
  26815. // Remove from the scene if found
  26816. this.transformNodes.splice(index, 1);
  26817. }
  26818. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26819. return index;
  26820. };
  26821. /**
  26822. * Remove a skeleton for the list of scene's skeletons
  26823. * @param toRemove defines the skeleton to remove
  26824. * @returns the index where the skeleton was in the skeleton list
  26825. */
  26826. Scene.prototype.removeSkeleton = function (toRemove) {
  26827. var index = this.skeletons.indexOf(toRemove);
  26828. if (index !== -1) {
  26829. // Remove from the scene if found
  26830. this.skeletons.splice(index, 1);
  26831. }
  26832. return index;
  26833. };
  26834. /**
  26835. * Remove a morph target for the list of scene's morph targets
  26836. * @param toRemove defines the morph target to remove
  26837. * @returns the index where the morph target was in the morph target list
  26838. */
  26839. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26840. var index = this.morphTargetManagers.indexOf(toRemove);
  26841. if (index !== -1) {
  26842. // Remove from the scene if found
  26843. this.morphTargetManagers.splice(index, 1);
  26844. }
  26845. return index;
  26846. };
  26847. /**
  26848. * Remove a light for the list of scene's lights
  26849. * @param toRemove defines the light to remove
  26850. * @returns the index where the light was in the light list
  26851. */
  26852. Scene.prototype.removeLight = function (toRemove) {
  26853. var index = this.lights.indexOf(toRemove);
  26854. if (index !== -1) {
  26855. // Remove from meshes
  26856. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26857. var mesh = _a[_i];
  26858. mesh._removeLightSource(toRemove);
  26859. }
  26860. // Remove from the scene if mesh found
  26861. this.lights.splice(index, 1);
  26862. this.sortLightsByPriority();
  26863. }
  26864. this.onLightRemovedObservable.notifyObservers(toRemove);
  26865. return index;
  26866. };
  26867. /**
  26868. * Remove a camera for the list of scene's cameras
  26869. * @param toRemove defines the camera to remove
  26870. * @returns the index where the camera was in the camera list
  26871. */
  26872. Scene.prototype.removeCamera = function (toRemove) {
  26873. var index = this.cameras.indexOf(toRemove);
  26874. if (index !== -1) {
  26875. // Remove from the scene if mesh found
  26876. this.cameras.splice(index, 1);
  26877. }
  26878. // Remove from activeCameras
  26879. var index2 = this.activeCameras.indexOf(toRemove);
  26880. if (index2 !== -1) {
  26881. // Remove from the scene if mesh found
  26882. this.activeCameras.splice(index2, 1);
  26883. }
  26884. // Reset the activeCamera
  26885. if (this.activeCamera === toRemove) {
  26886. if (this.cameras.length > 0) {
  26887. this.activeCamera = this.cameras[0];
  26888. }
  26889. else {
  26890. this.activeCamera = null;
  26891. }
  26892. }
  26893. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26894. return index;
  26895. };
  26896. /**
  26897. * Remove a particle system for the list of scene's particle systems
  26898. * @param toRemove defines the particle system to remove
  26899. * @returns the index where the particle system was in the particle system list
  26900. */
  26901. Scene.prototype.removeParticleSystem = function (toRemove) {
  26902. var index = this.particleSystems.indexOf(toRemove);
  26903. if (index !== -1) {
  26904. this.particleSystems.splice(index, 1);
  26905. }
  26906. return index;
  26907. };
  26908. /**
  26909. * Remove a animation for the list of scene's animations
  26910. * @param toRemove defines the animation to remove
  26911. * @returns the index where the animation was in the animation list
  26912. */
  26913. Scene.prototype.removeAnimation = function (toRemove) {
  26914. var index = this.animations.indexOf(toRemove);
  26915. if (index !== -1) {
  26916. this.animations.splice(index, 1);
  26917. }
  26918. return index;
  26919. };
  26920. /**
  26921. * Removes the given animation group from this scene.
  26922. * @param toRemove The animation group to remove
  26923. * @returns The index of the removed animation group
  26924. */
  26925. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26926. var index = this.animationGroups.indexOf(toRemove);
  26927. if (index !== -1) {
  26928. this.animationGroups.splice(index, 1);
  26929. }
  26930. return index;
  26931. };
  26932. /**
  26933. * Removes the given multi-material from this scene.
  26934. * @param toRemove The multi-material to remove
  26935. * @returns The index of the removed multi-material
  26936. */
  26937. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26938. var index = this.multiMaterials.indexOf(toRemove);
  26939. if (index !== -1) {
  26940. this.multiMaterials.splice(index, 1);
  26941. }
  26942. return index;
  26943. };
  26944. /**
  26945. * Removes the given material from this scene.
  26946. * @param toRemove The material to remove
  26947. * @returns The index of the removed material
  26948. */
  26949. Scene.prototype.removeMaterial = function (toRemove) {
  26950. var index = this.materials.indexOf(toRemove);
  26951. if (index !== -1) {
  26952. this.materials.splice(index, 1);
  26953. }
  26954. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  26955. return index;
  26956. };
  26957. /**
  26958. * Removes the given action manager from this scene.
  26959. * @param toRemove The action manager to remove
  26960. * @returns The index of the removed action manager
  26961. */
  26962. Scene.prototype.removeActionManager = function (toRemove) {
  26963. var index = this.actionManagers.indexOf(toRemove);
  26964. if (index !== -1) {
  26965. this.actionManagers.splice(index, 1);
  26966. }
  26967. return index;
  26968. };
  26969. /**
  26970. * Removes the given texture from this scene.
  26971. * @param toRemove The texture to remove
  26972. * @returns The index of the removed texture
  26973. */
  26974. Scene.prototype.removeTexture = function (toRemove) {
  26975. var index = this.textures.indexOf(toRemove);
  26976. if (index !== -1) {
  26977. this.textures.splice(index, 1);
  26978. }
  26979. this.onTextureRemovedObservable.notifyObservers(toRemove);
  26980. return index;
  26981. };
  26982. /**
  26983. * Adds the given light to this scene
  26984. * @param newLight The light to add
  26985. */
  26986. Scene.prototype.addLight = function (newLight) {
  26987. this.lights.push(newLight);
  26988. this.sortLightsByPriority();
  26989. // Add light to all meshes (To support if the light is removed and then readded)
  26990. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26991. var mesh = _a[_i];
  26992. if (mesh._lightSources.indexOf(newLight) === -1) {
  26993. mesh._lightSources.push(newLight);
  26994. mesh._resyncLightSources();
  26995. }
  26996. }
  26997. this.onNewLightAddedObservable.notifyObservers(newLight);
  26998. };
  26999. /**
  27000. * Sorts the list list based on light priorities
  27001. */
  27002. Scene.prototype.sortLightsByPriority = function () {
  27003. if (this.requireLightSorting) {
  27004. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27005. }
  27006. };
  27007. /**
  27008. * Adds the given camera to this scene
  27009. * @param newCamera The camera to add
  27010. */
  27011. Scene.prototype.addCamera = function (newCamera) {
  27012. this.cameras.push(newCamera);
  27013. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27014. };
  27015. /**
  27016. * Adds the given skeleton to this scene
  27017. * @param newSkeleton The skeleton to add
  27018. */
  27019. Scene.prototype.addSkeleton = function (newSkeleton) {
  27020. this.skeletons.push(newSkeleton);
  27021. };
  27022. /**
  27023. * Adds the given particle system to this scene
  27024. * @param newParticleSystem The particle system to add
  27025. */
  27026. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27027. this.particleSystems.push(newParticleSystem);
  27028. };
  27029. /**
  27030. * Adds the given animation to this scene
  27031. * @param newAnimation The animation to add
  27032. */
  27033. Scene.prototype.addAnimation = function (newAnimation) {
  27034. this.animations.push(newAnimation);
  27035. };
  27036. /**
  27037. * Adds the given animation group to this scene.
  27038. * @param newAnimationGroup The animation group to add
  27039. */
  27040. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27041. this.animationGroups.push(newAnimationGroup);
  27042. };
  27043. /**
  27044. * Adds the given multi-material to this scene
  27045. * @param newMultiMaterial The multi-material to add
  27046. */
  27047. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27048. this.multiMaterials.push(newMultiMaterial);
  27049. };
  27050. /**
  27051. * Adds the given material to this scene
  27052. * @param newMaterial The material to add
  27053. */
  27054. Scene.prototype.addMaterial = function (newMaterial) {
  27055. this.materials.push(newMaterial);
  27056. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27057. };
  27058. /**
  27059. * Adds the given morph target to this scene
  27060. * @param newMorphTargetManager The morph target to add
  27061. */
  27062. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27063. this.morphTargetManagers.push(newMorphTargetManager);
  27064. };
  27065. /**
  27066. * Adds the given geometry to this scene
  27067. * @param newGeometry The geometry to add
  27068. */
  27069. Scene.prototype.addGeometry = function (newGeometry) {
  27070. this.geometries.push(newGeometry);
  27071. };
  27072. /**
  27073. * Adds the given action manager to this scene
  27074. * @param newActionManager The action manager to add
  27075. */
  27076. Scene.prototype.addActionManager = function (newActionManager) {
  27077. this.actionManagers.push(newActionManager);
  27078. };
  27079. /**
  27080. * Adds the given texture to this scene.
  27081. * @param newTexture The texture to add
  27082. */
  27083. Scene.prototype.addTexture = function (newTexture) {
  27084. this.textures.push(newTexture);
  27085. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27086. };
  27087. /**
  27088. * Switch active camera
  27089. * @param newCamera defines the new active camera
  27090. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27091. */
  27092. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27093. if (attachControl === void 0) { attachControl = true; }
  27094. var canvas = this._engine.getRenderingCanvas();
  27095. if (!canvas) {
  27096. return;
  27097. }
  27098. if (this.activeCamera) {
  27099. this.activeCamera.detachControl(canvas);
  27100. }
  27101. this.activeCamera = newCamera;
  27102. if (attachControl) {
  27103. newCamera.attachControl(canvas);
  27104. }
  27105. };
  27106. /**
  27107. * sets the active camera of the scene using its ID
  27108. * @param id defines the camera's ID
  27109. * @return the new active camera or null if none found.
  27110. */
  27111. Scene.prototype.setActiveCameraByID = function (id) {
  27112. var camera = this.getCameraByID(id);
  27113. if (camera) {
  27114. this.activeCamera = camera;
  27115. return camera;
  27116. }
  27117. return null;
  27118. };
  27119. /**
  27120. * sets the active camera of the scene using its name
  27121. * @param name defines the camera's name
  27122. * @returns the new active camera or null if none found.
  27123. */
  27124. Scene.prototype.setActiveCameraByName = function (name) {
  27125. var camera = this.getCameraByName(name);
  27126. if (camera) {
  27127. this.activeCamera = camera;
  27128. return camera;
  27129. }
  27130. return null;
  27131. };
  27132. /**
  27133. * get an animation group using its name
  27134. * @param name defines the material's name
  27135. * @return the animation group or null if none found.
  27136. */
  27137. Scene.prototype.getAnimationGroupByName = function (name) {
  27138. for (var index = 0; index < this.animationGroups.length; index++) {
  27139. if (this.animationGroups[index].name === name) {
  27140. return this.animationGroups[index];
  27141. }
  27142. }
  27143. return null;
  27144. };
  27145. /**
  27146. * get a material using its id
  27147. * @param id defines the material's ID
  27148. * @return the material or null if none found.
  27149. */
  27150. Scene.prototype.getMaterialByID = function (id) {
  27151. for (var index = 0; index < this.materials.length; index++) {
  27152. if (this.materials[index].id === id) {
  27153. return this.materials[index];
  27154. }
  27155. }
  27156. return null;
  27157. };
  27158. /**
  27159. * Gets a material using its name
  27160. * @param name defines the material's name
  27161. * @return the material or null if none found.
  27162. */
  27163. Scene.prototype.getMaterialByName = function (name) {
  27164. for (var index = 0; index < this.materials.length; index++) {
  27165. if (this.materials[index].name === name) {
  27166. return this.materials[index];
  27167. }
  27168. }
  27169. return null;
  27170. };
  27171. /**
  27172. * Gets a camera using its id
  27173. * @param id defines the id to look for
  27174. * @returns the camera or null if not found
  27175. */
  27176. Scene.prototype.getCameraByID = function (id) {
  27177. for (var index = 0; index < this.cameras.length; index++) {
  27178. if (this.cameras[index].id === id) {
  27179. return this.cameras[index];
  27180. }
  27181. }
  27182. return null;
  27183. };
  27184. /**
  27185. * Gets a camera using its unique id
  27186. * @param uniqueId defines the unique id to look for
  27187. * @returns the camera or null if not found
  27188. */
  27189. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27190. for (var index = 0; index < this.cameras.length; index++) {
  27191. if (this.cameras[index].uniqueId === uniqueId) {
  27192. return this.cameras[index];
  27193. }
  27194. }
  27195. return null;
  27196. };
  27197. /**
  27198. * Gets a camera using its name
  27199. * @param name defines the camera's name
  27200. * @return the camera or null if none found.
  27201. */
  27202. Scene.prototype.getCameraByName = function (name) {
  27203. for (var index = 0; index < this.cameras.length; index++) {
  27204. if (this.cameras[index].name === name) {
  27205. return this.cameras[index];
  27206. }
  27207. }
  27208. return null;
  27209. };
  27210. /**
  27211. * Gets a bone using its id
  27212. * @param id defines the bone's id
  27213. * @return the bone or null if not found
  27214. */
  27215. Scene.prototype.getBoneByID = function (id) {
  27216. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27217. var skeleton = this.skeletons[skeletonIndex];
  27218. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27219. if (skeleton.bones[boneIndex].id === id) {
  27220. return skeleton.bones[boneIndex];
  27221. }
  27222. }
  27223. }
  27224. return null;
  27225. };
  27226. /**
  27227. * Gets a bone using its id
  27228. * @param name defines the bone's name
  27229. * @return the bone or null if not found
  27230. */
  27231. Scene.prototype.getBoneByName = function (name) {
  27232. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27233. var skeleton = this.skeletons[skeletonIndex];
  27234. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27235. if (skeleton.bones[boneIndex].name === name) {
  27236. return skeleton.bones[boneIndex];
  27237. }
  27238. }
  27239. }
  27240. return null;
  27241. };
  27242. /**
  27243. * Gets a light node using its name
  27244. * @param name defines the the light's name
  27245. * @return the light or null if none found.
  27246. */
  27247. Scene.prototype.getLightByName = function (name) {
  27248. for (var index = 0; index < this.lights.length; index++) {
  27249. if (this.lights[index].name === name) {
  27250. return this.lights[index];
  27251. }
  27252. }
  27253. return null;
  27254. };
  27255. /**
  27256. * Gets a light node using its id
  27257. * @param id defines the light's id
  27258. * @return the light or null if none found.
  27259. */
  27260. Scene.prototype.getLightByID = function (id) {
  27261. for (var index = 0; index < this.lights.length; index++) {
  27262. if (this.lights[index].id === id) {
  27263. return this.lights[index];
  27264. }
  27265. }
  27266. return null;
  27267. };
  27268. /**
  27269. * Gets a light node using its scene-generated unique ID
  27270. * @param uniqueId defines the light's unique id
  27271. * @return the light or null if none found.
  27272. */
  27273. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27274. for (var index = 0; index < this.lights.length; index++) {
  27275. if (this.lights[index].uniqueId === uniqueId) {
  27276. return this.lights[index];
  27277. }
  27278. }
  27279. return null;
  27280. };
  27281. /**
  27282. * Gets a particle system by id
  27283. * @param id defines the particle system id
  27284. * @return the corresponding system or null if none found
  27285. */
  27286. Scene.prototype.getParticleSystemByID = function (id) {
  27287. for (var index = 0; index < this.particleSystems.length; index++) {
  27288. if (this.particleSystems[index].id === id) {
  27289. return this.particleSystems[index];
  27290. }
  27291. }
  27292. return null;
  27293. };
  27294. /**
  27295. * Gets a geometry using its ID
  27296. * @param id defines the geometry's id
  27297. * @return the geometry or null if none found.
  27298. */
  27299. Scene.prototype.getGeometryByID = function (id) {
  27300. for (var index = 0; index < this.geometries.length; index++) {
  27301. if (this.geometries[index].id === id) {
  27302. return this.geometries[index];
  27303. }
  27304. }
  27305. return null;
  27306. };
  27307. /**
  27308. * Add a new geometry to this scene
  27309. * @param geometry defines the geometry to be added to the scene.
  27310. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27311. * @return a boolean defining if the geometry was added or not
  27312. */
  27313. Scene.prototype.pushGeometry = function (geometry, force) {
  27314. if (!force && this.getGeometryByID(geometry.id)) {
  27315. return false;
  27316. }
  27317. this.geometries.push(geometry);
  27318. //notify the collision coordinator
  27319. if (this.collisionCoordinator) {
  27320. this.collisionCoordinator.onGeometryAdded(geometry);
  27321. }
  27322. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27323. return true;
  27324. };
  27325. /**
  27326. * Removes an existing geometry
  27327. * @param geometry defines the geometry to be removed from the scene
  27328. * @return a boolean defining if the geometry was removed or not
  27329. */
  27330. Scene.prototype.removeGeometry = function (geometry) {
  27331. var index = this.geometries.indexOf(geometry);
  27332. if (index > -1) {
  27333. this.geometries.splice(index, 1);
  27334. //notify the collision coordinator
  27335. if (this.collisionCoordinator) {
  27336. this.collisionCoordinator.onGeometryDeleted(geometry);
  27337. }
  27338. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27339. return true;
  27340. }
  27341. return false;
  27342. };
  27343. /**
  27344. * Gets the list of geometries attached to the scene
  27345. * @returns an array of Geometry
  27346. */
  27347. Scene.prototype.getGeometries = function () {
  27348. return this.geometries;
  27349. };
  27350. /**
  27351. * Gets the first added mesh found of a given ID
  27352. * @param id defines the id to search for
  27353. * @return the mesh found or null if not found at all
  27354. */
  27355. Scene.prototype.getMeshByID = function (id) {
  27356. for (var index = 0; index < this.meshes.length; index++) {
  27357. if (this.meshes[index].id === id) {
  27358. return this.meshes[index];
  27359. }
  27360. }
  27361. return null;
  27362. };
  27363. /**
  27364. * Gets a list of meshes using their id
  27365. * @param id defines the id to search for
  27366. * @returns a list of meshes
  27367. */
  27368. Scene.prototype.getMeshesByID = function (id) {
  27369. return this.meshes.filter(function (m) {
  27370. return m.id === id;
  27371. });
  27372. };
  27373. /**
  27374. * Gets the first added transform node found of a given ID
  27375. * @param id defines the id to search for
  27376. * @return the found transform node or null if not found at all.
  27377. */
  27378. Scene.prototype.getTransformNodeByID = function (id) {
  27379. for (var index = 0; index < this.transformNodes.length; index++) {
  27380. if (this.transformNodes[index].id === id) {
  27381. return this.transformNodes[index];
  27382. }
  27383. }
  27384. return null;
  27385. };
  27386. /**
  27387. * Gets a list of transform nodes using their id
  27388. * @param id defines the id to search for
  27389. * @returns a list of transform nodes
  27390. */
  27391. Scene.prototype.getTransformNodesByID = function (id) {
  27392. return this.transformNodes.filter(function (m) {
  27393. return m.id === id;
  27394. });
  27395. };
  27396. /**
  27397. * Gets a mesh with its auto-generated unique id
  27398. * @param uniqueId defines the unique id to search for
  27399. * @return the found mesh or null if not found at all.
  27400. */
  27401. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27402. for (var index = 0; index < this.meshes.length; index++) {
  27403. if (this.meshes[index].uniqueId === uniqueId) {
  27404. return this.meshes[index];
  27405. }
  27406. }
  27407. return null;
  27408. };
  27409. /**
  27410. * Gets a the last added mesh using a given id
  27411. * @param id defines the id to search for
  27412. * @return the found mesh or null if not found at all.
  27413. */
  27414. Scene.prototype.getLastMeshByID = function (id) {
  27415. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27416. if (this.meshes[index].id === id) {
  27417. return this.meshes[index];
  27418. }
  27419. }
  27420. return null;
  27421. };
  27422. /**
  27423. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27424. * @param id defines the id to search for
  27425. * @return the found node or null if not found at all
  27426. */
  27427. Scene.prototype.getLastEntryByID = function (id) {
  27428. var index;
  27429. for (index = this.meshes.length - 1; index >= 0; index--) {
  27430. if (this.meshes[index].id === id) {
  27431. return this.meshes[index];
  27432. }
  27433. }
  27434. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27435. if (this.transformNodes[index].id === id) {
  27436. return this.transformNodes[index];
  27437. }
  27438. }
  27439. for (index = this.cameras.length - 1; index >= 0; index--) {
  27440. if (this.cameras[index].id === id) {
  27441. return this.cameras[index];
  27442. }
  27443. }
  27444. for (index = this.lights.length - 1; index >= 0; index--) {
  27445. if (this.lights[index].id === id) {
  27446. return this.lights[index];
  27447. }
  27448. }
  27449. return null;
  27450. };
  27451. /**
  27452. * Gets a node (Mesh, Camera, Light) using a given id
  27453. * @param id defines the id to search for
  27454. * @return the found node or null if not found at all
  27455. */
  27456. Scene.prototype.getNodeByID = function (id) {
  27457. var mesh = this.getMeshByID(id);
  27458. if (mesh) {
  27459. return mesh;
  27460. }
  27461. var light = this.getLightByID(id);
  27462. if (light) {
  27463. return light;
  27464. }
  27465. var camera = this.getCameraByID(id);
  27466. if (camera) {
  27467. return camera;
  27468. }
  27469. var bone = this.getBoneByID(id);
  27470. return bone;
  27471. };
  27472. /**
  27473. * Gets a node (Mesh, Camera, Light) using a given name
  27474. * @param name defines the name to search for
  27475. * @return the found node or null if not found at all.
  27476. */
  27477. Scene.prototype.getNodeByName = function (name) {
  27478. var mesh = this.getMeshByName(name);
  27479. if (mesh) {
  27480. return mesh;
  27481. }
  27482. var light = this.getLightByName(name);
  27483. if (light) {
  27484. return light;
  27485. }
  27486. var camera = this.getCameraByName(name);
  27487. if (camera) {
  27488. return camera;
  27489. }
  27490. var bone = this.getBoneByName(name);
  27491. return bone;
  27492. };
  27493. /**
  27494. * Gets a mesh using a given name
  27495. * @param name defines the name to search for
  27496. * @return the found mesh or null if not found at all.
  27497. */
  27498. Scene.prototype.getMeshByName = function (name) {
  27499. for (var index = 0; index < this.meshes.length; index++) {
  27500. if (this.meshes[index].name === name) {
  27501. return this.meshes[index];
  27502. }
  27503. }
  27504. return null;
  27505. };
  27506. /**
  27507. * Gets a transform node using a given name
  27508. * @param name defines the name to search for
  27509. * @return the found transform node or null if not found at all.
  27510. */
  27511. Scene.prototype.getTransformNodeByName = function (name) {
  27512. for (var index = 0; index < this.transformNodes.length; index++) {
  27513. if (this.transformNodes[index].name === name) {
  27514. return this.transformNodes[index];
  27515. }
  27516. }
  27517. return null;
  27518. };
  27519. /**
  27520. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27521. * @param id defines the id to search for
  27522. * @return the found skeleton or null if not found at all.
  27523. */
  27524. Scene.prototype.getLastSkeletonByID = function (id) {
  27525. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27526. if (this.skeletons[index].id === id) {
  27527. return this.skeletons[index];
  27528. }
  27529. }
  27530. return null;
  27531. };
  27532. /**
  27533. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27534. * @param id defines the id to search for
  27535. * @return the found skeleton or null if not found at all.
  27536. */
  27537. Scene.prototype.getSkeletonById = function (id) {
  27538. for (var index = 0; index < this.skeletons.length; index++) {
  27539. if (this.skeletons[index].id === id) {
  27540. return this.skeletons[index];
  27541. }
  27542. }
  27543. return null;
  27544. };
  27545. /**
  27546. * Gets a skeleton using a given name
  27547. * @param name defines the name to search for
  27548. * @return the found skeleton or null if not found at all.
  27549. */
  27550. Scene.prototype.getSkeletonByName = function (name) {
  27551. for (var index = 0; index < this.skeletons.length; index++) {
  27552. if (this.skeletons[index].name === name) {
  27553. return this.skeletons[index];
  27554. }
  27555. }
  27556. return null;
  27557. };
  27558. /**
  27559. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27560. * @param id defines the id to search for
  27561. * @return the found morph target manager or null if not found at all.
  27562. */
  27563. Scene.prototype.getMorphTargetManagerById = function (id) {
  27564. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27565. if (this.morphTargetManagers[index].uniqueId === id) {
  27566. return this.morphTargetManagers[index];
  27567. }
  27568. }
  27569. return null;
  27570. };
  27571. /**
  27572. * Gets a boolean indicating if the given mesh is active
  27573. * @param mesh defines the mesh to look for
  27574. * @returns true if the mesh is in the active list
  27575. */
  27576. Scene.prototype.isActiveMesh = function (mesh) {
  27577. return (this._activeMeshes.indexOf(mesh) !== -1);
  27578. };
  27579. Object.defineProperty(Scene.prototype, "uid", {
  27580. /**
  27581. * Return a unique id as a string which can serve as an identifier for the scene
  27582. */
  27583. get: function () {
  27584. if (!this._uid) {
  27585. this._uid = BABYLON.Tools.RandomId();
  27586. }
  27587. return this._uid;
  27588. },
  27589. enumerable: true,
  27590. configurable: true
  27591. });
  27592. /**
  27593. * Add an externaly attached data from its key.
  27594. * This method call will fail and return false, if such key already exists.
  27595. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27596. * @param key the unique key that identifies the data
  27597. * @param data the data object to associate to the key for this Engine instance
  27598. * @return true if no such key were already present and the data was added successfully, false otherwise
  27599. */
  27600. Scene.prototype.addExternalData = function (key, data) {
  27601. if (!this._externalData) {
  27602. this._externalData = new BABYLON.StringDictionary();
  27603. }
  27604. return this._externalData.add(key, data);
  27605. };
  27606. /**
  27607. * Get an externaly attached data from its key
  27608. * @param key the unique key that identifies the data
  27609. * @return the associated data, if present (can be null), or undefined if not present
  27610. */
  27611. Scene.prototype.getExternalData = function (key) {
  27612. if (!this._externalData) {
  27613. return null;
  27614. }
  27615. return this._externalData.get(key);
  27616. };
  27617. /**
  27618. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27619. * @param key the unique key that identifies the data
  27620. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27621. * @return the associated data, can be null if the factory returned null.
  27622. */
  27623. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27624. if (!this._externalData) {
  27625. this._externalData = new BABYLON.StringDictionary();
  27626. }
  27627. return this._externalData.getOrAddWithFactory(key, factory);
  27628. };
  27629. /**
  27630. * Remove an externaly attached data from the Engine instance
  27631. * @param key the unique key that identifies the data
  27632. * @return true if the data was successfully removed, false if it doesn't exist
  27633. */
  27634. Scene.prototype.removeExternalData = function (key) {
  27635. return this._externalData.remove(key);
  27636. };
  27637. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27638. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27639. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27640. var step = _a[_i];
  27641. step.action(mesh, subMesh);
  27642. }
  27643. var material = subMesh.getMaterial();
  27644. if (material !== null && material !== undefined) {
  27645. // Render targets
  27646. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27647. if (this._processedMaterials.indexOf(material) === -1) {
  27648. this._processedMaterials.push(material);
  27649. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27650. }
  27651. }
  27652. // Dispatch
  27653. this._activeIndices.addCount(subMesh.indexCount, false);
  27654. this._renderingManager.dispatch(subMesh, mesh, material);
  27655. }
  27656. }
  27657. };
  27658. /**
  27659. * Clear the processed materials smart array preventing retention point in material dispose.
  27660. */
  27661. Scene.prototype.freeProcessedMaterials = function () {
  27662. this._processedMaterials.dispose();
  27663. };
  27664. /**
  27665. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27666. */
  27667. Scene.prototype.freeActiveMeshes = function () {
  27668. this._activeMeshes.dispose();
  27669. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27670. this.activeCamera._activeMeshes.dispose();
  27671. }
  27672. if (this.activeCameras) {
  27673. for (var i = 0; i < this.activeCameras.length; i++) {
  27674. var activeCamera = this.activeCameras[i];
  27675. if (activeCamera && activeCamera._activeMeshes) {
  27676. activeCamera._activeMeshes.dispose();
  27677. }
  27678. }
  27679. }
  27680. };
  27681. /**
  27682. * Clear the info related to rendering groups preventing retention points during dispose.
  27683. */
  27684. Scene.prototype.freeRenderingGroups = function () {
  27685. if (this._renderingManager) {
  27686. this._renderingManager.freeRenderingGroups();
  27687. }
  27688. if (this.textures) {
  27689. for (var i = 0; i < this.textures.length; i++) {
  27690. var texture = this.textures[i];
  27691. if (texture && texture.renderList) {
  27692. texture.freeRenderingGroups();
  27693. }
  27694. }
  27695. }
  27696. };
  27697. /** @hidden */
  27698. Scene.prototype._isInIntermediateRendering = function () {
  27699. return this._intermediateRendering;
  27700. };
  27701. /**
  27702. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27703. * @returns the current scene
  27704. */
  27705. Scene.prototype.freezeActiveMeshes = function () {
  27706. if (!this.activeCamera) {
  27707. return this;
  27708. }
  27709. if (!this._frustumPlanes) {
  27710. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27711. }
  27712. this._evaluateActiveMeshes();
  27713. this._activeMeshesFrozen = true;
  27714. return this;
  27715. };
  27716. /**
  27717. * Use this function to restart evaluating active meshes on every frame
  27718. * @returns the current scene
  27719. */
  27720. Scene.prototype.unfreezeActiveMeshes = function () {
  27721. this._activeMeshesFrozen = false;
  27722. return this;
  27723. };
  27724. Scene.prototype._evaluateActiveMeshes = function () {
  27725. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27726. return;
  27727. }
  27728. if (!this.activeCamera) {
  27729. return;
  27730. }
  27731. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27732. this.activeCamera._activeMeshes.reset();
  27733. this._activeMeshes.reset();
  27734. this._renderingManager.reset();
  27735. this._processedMaterials.reset();
  27736. this._activeParticleSystems.reset();
  27737. this._activeSkeletons.reset();
  27738. this._softwareSkinnedMeshes.reset();
  27739. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27740. var step = _a[_i];
  27741. step.action();
  27742. }
  27743. // Determine mesh candidates
  27744. var meshes = this.getActiveMeshCandidates();
  27745. // Check each mesh
  27746. var len = meshes.length;
  27747. for (var i = 0; i < len; i++) {
  27748. var mesh = meshes.data[i];
  27749. if (mesh.isBlocked) {
  27750. continue;
  27751. }
  27752. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27753. if (!mesh.isReady() || !mesh.isEnabled()) {
  27754. continue;
  27755. }
  27756. mesh.computeWorldMatrix();
  27757. // Intersections
  27758. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27759. this._meshesForIntersections.pushNoDuplicate(mesh);
  27760. }
  27761. // Switch to current LOD
  27762. var meshLOD = mesh.getLOD(this.activeCamera);
  27763. if (meshLOD === undefined || meshLOD === null) {
  27764. continue;
  27765. }
  27766. mesh._preActivate();
  27767. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27768. this._activeMeshes.push(mesh);
  27769. this.activeCamera._activeMeshes.push(mesh);
  27770. mesh._activate(this._renderId);
  27771. if (meshLOD !== mesh) {
  27772. meshLOD._activate(this._renderId);
  27773. }
  27774. this._activeMesh(mesh, meshLOD);
  27775. }
  27776. }
  27777. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27778. // Particle systems
  27779. if (this.particlesEnabled) {
  27780. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27781. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27782. var particleSystem = this.particleSystems[particleIndex];
  27783. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27784. continue;
  27785. }
  27786. var emitter = particleSystem.emitter;
  27787. if (!emitter.position || emitter.isEnabled()) {
  27788. this._activeParticleSystems.push(particleSystem);
  27789. particleSystem.animate();
  27790. this._renderingManager.dispatchParticles(particleSystem);
  27791. }
  27792. }
  27793. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27794. }
  27795. };
  27796. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27797. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27798. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27799. mesh.skeleton.prepare();
  27800. }
  27801. if (!mesh.computeBonesUsingShaders) {
  27802. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27803. }
  27804. }
  27805. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27806. var step = _a[_i];
  27807. step.action(sourceMesh, mesh);
  27808. }
  27809. if (mesh !== undefined && mesh !== null
  27810. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27811. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27812. var len = subMeshes.length;
  27813. for (var i = 0; i < len; i++) {
  27814. var subMesh = subMeshes.data[i];
  27815. this._evaluateSubMesh(subMesh, mesh);
  27816. }
  27817. }
  27818. };
  27819. /**
  27820. * Update the transform matrix to update from the current active camera
  27821. * @param force defines a boolean used to force the update even if cache is up to date
  27822. */
  27823. Scene.prototype.updateTransformMatrix = function (force) {
  27824. if (!this.activeCamera) {
  27825. return;
  27826. }
  27827. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27828. };
  27829. /**
  27830. * 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)
  27831. * @param alternateCamera defines the camera to use
  27832. */
  27833. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27834. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27835. };
  27836. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27837. if (camera && camera._skipRendering) {
  27838. return;
  27839. }
  27840. var engine = this._engine;
  27841. this.activeCamera = camera;
  27842. if (!this.activeCamera)
  27843. throw new Error("Active camera not set");
  27844. // Viewport
  27845. engine.setViewport(this.activeCamera.viewport);
  27846. // Camera
  27847. this.resetCachedMaterial();
  27848. this._renderId++;
  27849. this.updateTransformMatrix();
  27850. if (camera._alternateCamera) {
  27851. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27852. this._alternateRendering = true;
  27853. }
  27854. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27855. // Meshes
  27856. this._evaluateActiveMeshes();
  27857. // Software skinning
  27858. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27859. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27860. mesh.applySkeleton(mesh.skeleton);
  27861. }
  27862. // Render targets
  27863. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27864. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27865. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27866. }
  27867. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27868. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27869. }
  27870. // Collects render targets from external components.
  27871. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27872. var step = _a[_i];
  27873. step.action(this._renderTargets);
  27874. }
  27875. if (this.renderTargetsEnabled) {
  27876. this._intermediateRendering = true;
  27877. if (this._renderTargets.length > 0) {
  27878. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27879. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27880. var renderTarget = this._renderTargets.data[renderIndex];
  27881. if (renderTarget._shouldRender()) {
  27882. this._renderId++;
  27883. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27884. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27885. }
  27886. }
  27887. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27888. this._renderId++;
  27889. }
  27890. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27891. var step = _c[_b];
  27892. step.action(this.activeCamera);
  27893. }
  27894. this._intermediateRendering = false;
  27895. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27896. }
  27897. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27898. // Prepare Frame
  27899. if (this.postProcessManager) {
  27900. this.postProcessManager._prepareFrame();
  27901. }
  27902. // Before Camera Draw
  27903. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27904. var step = _e[_d];
  27905. step.action(this.activeCamera);
  27906. }
  27907. // Render
  27908. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27909. this._renderingManager.render(null, null, true, true);
  27910. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27911. // After Camera Draw
  27912. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27913. var step = _g[_f];
  27914. step.action(this.activeCamera);
  27915. }
  27916. // Finalize frame
  27917. if (this.postProcessManager) {
  27918. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27919. }
  27920. // Reset some special arrays
  27921. this._renderTargets.reset();
  27922. this._alternateRendering = false;
  27923. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27924. };
  27925. Scene.prototype._processSubCameras = function (camera) {
  27926. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27927. this._renderForCamera(camera);
  27928. return;
  27929. }
  27930. // rig cameras
  27931. for (var index = 0; index < camera._rigCameras.length; index++) {
  27932. this._renderForCamera(camera._rigCameras[index], camera);
  27933. }
  27934. this.activeCamera = camera;
  27935. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27936. };
  27937. Scene.prototype._checkIntersections = function () {
  27938. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27939. var sourceMesh = this._meshesForIntersections.data[index];
  27940. if (!sourceMesh.actionManager) {
  27941. continue;
  27942. }
  27943. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27944. var action = sourceMesh.actionManager.actions[actionIndex];
  27945. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27946. var parameters = action.getTriggerParameter();
  27947. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27948. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27949. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27950. if (areIntersecting && currentIntersectionInProgress === -1) {
  27951. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27952. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27953. sourceMesh._intersectionsInProgress.push(otherMesh);
  27954. }
  27955. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27956. sourceMesh._intersectionsInProgress.push(otherMesh);
  27957. }
  27958. }
  27959. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27960. //They intersected, and now they don't.
  27961. //is this trigger an exit trigger? execute an event.
  27962. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27963. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27964. }
  27965. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27966. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27967. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27968. return otherMesh === parameterMesh;
  27969. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27970. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27971. }
  27972. }
  27973. }
  27974. }
  27975. }
  27976. };
  27977. /** @hidden */
  27978. Scene.prototype._advancePhysicsEngineStep = function (step) {
  27979. // Do nothing. Code will be replaced if physics engine component is referenced
  27980. };
  27981. /**
  27982. * Render the scene
  27983. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27984. */
  27985. Scene.prototype.render = function (updateCameras) {
  27986. if (updateCameras === void 0) { updateCameras = true; }
  27987. if (this.isDisposed) {
  27988. return;
  27989. }
  27990. this._frameId++;
  27991. // Register components that have been associated lately to the scene.
  27992. this._registerTransientComponents();
  27993. this._activeParticles.fetchNewFrame();
  27994. this._totalVertices.fetchNewFrame();
  27995. this._activeIndices.fetchNewFrame();
  27996. this._activeBones.fetchNewFrame();
  27997. this._meshesForIntersections.reset();
  27998. this.resetCachedMaterial();
  27999. this.onBeforeAnimationsObservable.notifyObservers(this);
  28000. // Actions
  28001. if (this.actionManager) {
  28002. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28003. }
  28004. if (this._engine.isDeterministicLockStep()) {
  28005. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28006. var defaultFPS = (60.0 / 1000.0);
  28007. var defaultFrameTime = this.getDeterministicFrameTime();
  28008. var stepsTaken = 0;
  28009. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28010. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28011. internalSteps = Math.min(internalSteps, maxSubSteps);
  28012. do {
  28013. this.onBeforeStepObservable.notifyObservers(this);
  28014. // Animations
  28015. this._animationRatio = defaultFrameTime * defaultFPS;
  28016. this._animate();
  28017. this.onAfterAnimationsObservable.notifyObservers(this);
  28018. // Physics
  28019. this._advancePhysicsEngineStep(defaultFrameTime);
  28020. this.onAfterStepObservable.notifyObservers(this);
  28021. this._currentStepId++;
  28022. stepsTaken++;
  28023. deltaTime -= defaultFrameTime;
  28024. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28025. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28026. }
  28027. else {
  28028. // Animations
  28029. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28030. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28031. this._animate();
  28032. this.onAfterAnimationsObservable.notifyObservers(this);
  28033. // Physics
  28034. this._advancePhysicsEngineStep(deltaTime);
  28035. }
  28036. // Before camera update steps
  28037. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28038. var step = _a[_i];
  28039. step.action();
  28040. }
  28041. // Update Cameras
  28042. if (updateCameras) {
  28043. if (this.activeCameras.length > 0) {
  28044. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28045. var camera = this.activeCameras[cameraIndex];
  28046. camera.update();
  28047. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28048. // rig cameras
  28049. for (var index = 0; index < camera._rigCameras.length; index++) {
  28050. camera._rigCameras[index].update();
  28051. }
  28052. }
  28053. }
  28054. }
  28055. else if (this.activeCamera) {
  28056. this.activeCamera.update();
  28057. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28058. // rig cameras
  28059. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28060. this.activeCamera._rigCameras[index].update();
  28061. }
  28062. }
  28063. }
  28064. }
  28065. // Before render
  28066. this.onBeforeRenderObservable.notifyObservers(this);
  28067. // Customs render targets
  28068. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28069. var engine = this.getEngine();
  28070. var currentActiveCamera = this.activeCamera;
  28071. if (this.renderTargetsEnabled) {
  28072. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28073. this._intermediateRendering = true;
  28074. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28075. var renderTarget = this.customRenderTargets[customIndex];
  28076. if (renderTarget._shouldRender()) {
  28077. this._renderId++;
  28078. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28079. if (!this.activeCamera)
  28080. throw new Error("Active camera not set");
  28081. // Viewport
  28082. engine.setViewport(this.activeCamera.viewport);
  28083. // Camera
  28084. this.updateTransformMatrix();
  28085. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28086. }
  28087. }
  28088. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28089. this._intermediateRendering = false;
  28090. this._renderId++;
  28091. }
  28092. // Restore back buffer
  28093. if (this.customRenderTargets.length > 0) {
  28094. engine.restoreDefaultFramebuffer();
  28095. }
  28096. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28097. this.activeCamera = currentActiveCamera;
  28098. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28099. var step = _c[_b];
  28100. step.action();
  28101. }
  28102. // Clear
  28103. if (this.autoClearDepthAndStencil || this.autoClear) {
  28104. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28105. }
  28106. // Collects render targets from external components.
  28107. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28108. var step = _e[_d];
  28109. step.action(this._renderTargets);
  28110. }
  28111. // Multi-cameras?
  28112. if (this.activeCameras.length > 0) {
  28113. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28114. if (cameraIndex > 0) {
  28115. this._engine.clear(null, false, true, true);
  28116. }
  28117. this._processSubCameras(this.activeCameras[cameraIndex]);
  28118. }
  28119. }
  28120. else {
  28121. if (!this.activeCamera) {
  28122. throw new Error("No camera defined");
  28123. }
  28124. this._processSubCameras(this.activeCamera);
  28125. }
  28126. // Intersection checks
  28127. this._checkIntersections();
  28128. // Executes the after render stage actions.
  28129. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28130. var step = _g[_f];
  28131. step.action();
  28132. }
  28133. // After render
  28134. if (this.afterRender) {
  28135. this.afterRender();
  28136. }
  28137. this.onAfterRenderObservable.notifyObservers(this);
  28138. // Cleaning
  28139. if (this._toBeDisposed.length) {
  28140. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28141. var data = this._toBeDisposed[index];
  28142. if (data) {
  28143. data.dispose();
  28144. }
  28145. }
  28146. this._toBeDisposed = [];
  28147. }
  28148. if (this.dumpNextRenderTargets) {
  28149. this.dumpNextRenderTargets = false;
  28150. }
  28151. this._activeBones.addCount(0, true);
  28152. this._activeIndices.addCount(0, true);
  28153. this._activeParticles.addCount(0, true);
  28154. };
  28155. /**
  28156. * Freeze all materials
  28157. * A frozen material will not be updatable but should be faster to render
  28158. */
  28159. Scene.prototype.freezeMaterials = function () {
  28160. for (var i = 0; i < this.materials.length; i++) {
  28161. this.materials[i].freeze();
  28162. }
  28163. };
  28164. /**
  28165. * Unfreeze all materials
  28166. * A frozen material will not be updatable but should be faster to render
  28167. */
  28168. Scene.prototype.unfreezeMaterials = function () {
  28169. for (var i = 0; i < this.materials.length; i++) {
  28170. this.materials[i].unfreeze();
  28171. }
  28172. };
  28173. /**
  28174. * Releases all held ressources
  28175. */
  28176. Scene.prototype.dispose = function () {
  28177. this.beforeRender = null;
  28178. this.afterRender = null;
  28179. this.skeletons = [];
  28180. this.morphTargetManagers = [];
  28181. this._transientComponents = [];
  28182. this._isReadyForMeshStage.clear();
  28183. this._beforeEvaluateActiveMeshStage.clear();
  28184. this._evaluateSubMeshStage.clear();
  28185. this._activeMeshStage.clear();
  28186. this._cameraDrawRenderTargetStage.clear();
  28187. this._beforeCameraDrawStage.clear();
  28188. this._beforeRenderingGroupDrawStage.clear();
  28189. this._beforeRenderingMeshStage.clear();
  28190. this._afterRenderingMeshStage.clear();
  28191. this._afterRenderingGroupDrawStage.clear();
  28192. this._afterCameraDrawStage.clear();
  28193. this._afterRenderStage.clear();
  28194. this._beforeCameraUpdateStage.clear();
  28195. this._beforeClearStage.clear();
  28196. this._gatherRenderTargetsStage.clear();
  28197. this._gatherActiveCameraRenderTargetsStage.clear();
  28198. this._pointerMoveStage.clear();
  28199. this._pointerDownStage.clear();
  28200. this._pointerUpStage.clear();
  28201. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28202. var component = _a[_i];
  28203. component.dispose();
  28204. }
  28205. this.importedMeshesFiles = new Array();
  28206. this.stopAllAnimations();
  28207. this.resetCachedMaterial();
  28208. // Smart arrays
  28209. if (this.activeCamera) {
  28210. this.activeCamera._activeMeshes.dispose();
  28211. this.activeCamera = null;
  28212. }
  28213. this._activeMeshes.dispose();
  28214. this._renderingManager.dispose();
  28215. this._processedMaterials.dispose();
  28216. this._activeParticleSystems.dispose();
  28217. this._activeSkeletons.dispose();
  28218. this._softwareSkinnedMeshes.dispose();
  28219. this._renderTargets.dispose();
  28220. this._registeredForLateAnimationBindings.dispose();
  28221. this._meshesForIntersections.dispose();
  28222. this._toBeDisposed = [];
  28223. // Abort active requests
  28224. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28225. var request = _c[_b];
  28226. request.abort();
  28227. }
  28228. // Events
  28229. this.onDisposeObservable.notifyObservers(this);
  28230. this.onDisposeObservable.clear();
  28231. this.onBeforeRenderObservable.clear();
  28232. this.onAfterRenderObservable.clear();
  28233. this.onBeforeRenderTargetsRenderObservable.clear();
  28234. this.onAfterRenderTargetsRenderObservable.clear();
  28235. this.onAfterStepObservable.clear();
  28236. this.onBeforeStepObservable.clear();
  28237. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28238. this.onAfterActiveMeshesEvaluationObservable.clear();
  28239. this.onBeforeParticlesRenderingObservable.clear();
  28240. this.onAfterParticlesRenderingObservable.clear();
  28241. this.onBeforeDrawPhaseObservable.clear();
  28242. this.onAfterDrawPhaseObservable.clear();
  28243. this.onBeforeAnimationsObservable.clear();
  28244. this.onAfterAnimationsObservable.clear();
  28245. this.onDataLoadedObservable.clear();
  28246. this.onBeforeRenderingGroupObservable.clear();
  28247. this.onAfterRenderingGroupObservable.clear();
  28248. this.onMeshImportedObservable.clear();
  28249. this.onBeforeCameraRenderObservable.clear();
  28250. this.onAfterCameraRenderObservable.clear();
  28251. this.onReadyObservable.clear();
  28252. this.onNewCameraAddedObservable.clear();
  28253. this.onCameraRemovedObservable.clear();
  28254. this.onNewLightAddedObservable.clear();
  28255. this.onLightRemovedObservable.clear();
  28256. this.onNewGeometryAddedObservable.clear();
  28257. this.onGeometryRemovedObservable.clear();
  28258. this.onNewTransformNodeAddedObservable.clear();
  28259. this.onTransformNodeRemovedObservable.clear();
  28260. this.onNewMeshAddedObservable.clear();
  28261. this.onMeshRemovedObservable.clear();
  28262. this.onNewMaterialAddedObservable.clear();
  28263. this.onMaterialRemovedObservable.clear();
  28264. this.onNewTextureAddedObservable.clear();
  28265. this.onTextureRemovedObservable.clear();
  28266. this.onPrePointerObservable.clear();
  28267. this.onPointerObservable.clear();
  28268. this.onPreKeyboardObservable.clear();
  28269. this.onKeyboardObservable.clear();
  28270. this.detachControl();
  28271. // Detach cameras
  28272. var canvas = this._engine.getRenderingCanvas();
  28273. if (canvas) {
  28274. var index;
  28275. for (index = 0; index < this.cameras.length; index++) {
  28276. this.cameras[index].detachControl(canvas);
  28277. }
  28278. }
  28279. // Release animation groups
  28280. while (this.animationGroups.length) {
  28281. this.animationGroups[0].dispose();
  28282. }
  28283. // Release lights
  28284. while (this.lights.length) {
  28285. this.lights[0].dispose();
  28286. }
  28287. // Release meshes
  28288. while (this.meshes.length) {
  28289. this.meshes[0].dispose(true);
  28290. }
  28291. while (this.transformNodes.length) {
  28292. this.removeTransformNode(this.transformNodes[0]);
  28293. }
  28294. // Release cameras
  28295. while (this.cameras.length) {
  28296. this.cameras[0].dispose();
  28297. }
  28298. // Release materials
  28299. if (this.defaultMaterial) {
  28300. this.defaultMaterial.dispose();
  28301. }
  28302. while (this.multiMaterials.length) {
  28303. this.multiMaterials[0].dispose();
  28304. }
  28305. while (this.materials.length) {
  28306. this.materials[0].dispose();
  28307. }
  28308. // Release particles
  28309. while (this.particleSystems.length) {
  28310. this.particleSystems[0].dispose();
  28311. }
  28312. // Release postProcesses
  28313. while (this.postProcesses.length) {
  28314. this.postProcesses[0].dispose();
  28315. }
  28316. // Release textures
  28317. while (this.textures.length) {
  28318. this.textures[0].dispose();
  28319. }
  28320. // Release UBO
  28321. this._sceneUbo.dispose();
  28322. if (this._alternateSceneUbo) {
  28323. this._alternateSceneUbo.dispose();
  28324. }
  28325. // Post-processes
  28326. this.postProcessManager.dispose();
  28327. // Remove from engine
  28328. index = this._engine.scenes.indexOf(this);
  28329. if (index > -1) {
  28330. this._engine.scenes.splice(index, 1);
  28331. }
  28332. this._engine.wipeCaches(true);
  28333. this._isDisposed = true;
  28334. };
  28335. Object.defineProperty(Scene.prototype, "isDisposed", {
  28336. /**
  28337. * Gets if the scene is already disposed
  28338. */
  28339. get: function () {
  28340. return this._isDisposed;
  28341. },
  28342. enumerable: true,
  28343. configurable: true
  28344. });
  28345. /**
  28346. * Call this function to reduce memory footprint of the scene.
  28347. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28348. */
  28349. Scene.prototype.clearCachedVertexData = function () {
  28350. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28351. var mesh = this.meshes[meshIndex];
  28352. var geometry = mesh.geometry;
  28353. if (geometry) {
  28354. geometry._indices = [];
  28355. for (var vbName in geometry._vertexBuffers) {
  28356. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28357. continue;
  28358. }
  28359. geometry._vertexBuffers[vbName]._buffer._data = null;
  28360. }
  28361. }
  28362. }
  28363. };
  28364. /**
  28365. * This function will remove the local cached buffer data from texture.
  28366. * It will save memory but will prevent the texture from being rebuilt
  28367. */
  28368. Scene.prototype.cleanCachedTextureBuffer = function () {
  28369. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28370. var baseTexture = _a[_i];
  28371. var buffer = baseTexture._buffer;
  28372. if (buffer) {
  28373. baseTexture._buffer = null;
  28374. }
  28375. }
  28376. };
  28377. /**
  28378. * Get the world extend vectors with an optional filter
  28379. *
  28380. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28381. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28382. */
  28383. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28384. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28385. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28386. filterPredicate = filterPredicate || (function () { return true; });
  28387. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28388. mesh.computeWorldMatrix(true);
  28389. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28390. return;
  28391. }
  28392. var boundingInfo = mesh.getBoundingInfo();
  28393. var minBox = boundingInfo.boundingBox.minimumWorld;
  28394. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28395. BABYLON.Tools.CheckExtends(minBox, min, max);
  28396. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28397. });
  28398. return {
  28399. min: min,
  28400. max: max
  28401. };
  28402. };
  28403. // Picking
  28404. /**
  28405. * Creates a ray that can be used to pick in the scene
  28406. * @param x defines the x coordinate of the origin (on-screen)
  28407. * @param y defines the y coordinate of the origin (on-screen)
  28408. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28409. * @param camera defines the camera to use for the picking
  28410. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28411. * @returns a Ray
  28412. */
  28413. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28414. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28415. var result = BABYLON.Ray.Zero();
  28416. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28417. return result;
  28418. };
  28419. /**
  28420. * Creates a ray that can be used to pick in the scene
  28421. * @param x defines the x coordinate of the origin (on-screen)
  28422. * @param y defines the y coordinate of the origin (on-screen)
  28423. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28424. * @param result defines the ray where to store the picking ray
  28425. * @param camera defines the camera to use for the picking
  28426. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28427. * @returns the current scene
  28428. */
  28429. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28430. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28431. var engine = this._engine;
  28432. if (!camera) {
  28433. if (!this.activeCamera)
  28434. throw new Error("Active camera not set");
  28435. camera = this.activeCamera;
  28436. }
  28437. var cameraViewport = camera.viewport;
  28438. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28439. // Moving coordinates to local viewport world
  28440. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28441. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28442. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28443. return this;
  28444. };
  28445. /**
  28446. * Creates a ray that can be used to pick in the scene
  28447. * @param x defines the x coordinate of the origin (on-screen)
  28448. * @param y defines the y coordinate of the origin (on-screen)
  28449. * @param camera defines the camera to use for the picking
  28450. * @returns a Ray
  28451. */
  28452. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28453. var result = BABYLON.Ray.Zero();
  28454. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28455. return result;
  28456. };
  28457. /**
  28458. * Creates a ray that can be used to pick in the scene
  28459. * @param x defines the x coordinate of the origin (on-screen)
  28460. * @param y defines the y coordinate of the origin (on-screen)
  28461. * @param result defines the ray where to store the picking ray
  28462. * @param camera defines the camera to use for the picking
  28463. * @returns the current scene
  28464. */
  28465. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28466. if (!BABYLON.PickingInfo) {
  28467. return this;
  28468. }
  28469. var engine = this._engine;
  28470. if (!camera) {
  28471. if (!this.activeCamera)
  28472. throw new Error("Active camera not set");
  28473. camera = this.activeCamera;
  28474. }
  28475. var cameraViewport = camera.viewport;
  28476. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28477. var identity = BABYLON.Matrix.Identity();
  28478. // Moving coordinates to local viewport world
  28479. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28480. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28481. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28482. return this;
  28483. };
  28484. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28485. if (!BABYLON.PickingInfo) {
  28486. return null;
  28487. }
  28488. var pickingInfo = null;
  28489. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28490. var mesh = this.meshes[meshIndex];
  28491. if (predicate) {
  28492. if (!predicate(mesh)) {
  28493. continue;
  28494. }
  28495. }
  28496. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28497. continue;
  28498. }
  28499. var world = mesh.getWorldMatrix();
  28500. var ray = rayFunction(world);
  28501. var result = mesh.intersects(ray, fastCheck);
  28502. if (!result || !result.hit)
  28503. continue;
  28504. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28505. continue;
  28506. pickingInfo = result;
  28507. if (fastCheck) {
  28508. break;
  28509. }
  28510. }
  28511. return pickingInfo || new BABYLON.PickingInfo();
  28512. };
  28513. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28514. if (!BABYLON.PickingInfo) {
  28515. return null;
  28516. }
  28517. var pickingInfos = new Array();
  28518. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28519. var mesh = this.meshes[meshIndex];
  28520. if (predicate) {
  28521. if (!predicate(mesh)) {
  28522. continue;
  28523. }
  28524. }
  28525. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28526. continue;
  28527. }
  28528. var world = mesh.getWorldMatrix();
  28529. var ray = rayFunction(world);
  28530. var result = mesh.intersects(ray, false);
  28531. if (!result || !result.hit)
  28532. continue;
  28533. pickingInfos.push(result);
  28534. }
  28535. return pickingInfos;
  28536. };
  28537. /** Launch a ray to try to pick a mesh in the scene
  28538. * @param x position on screen
  28539. * @param y position on screen
  28540. * @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
  28541. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28542. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28543. * @returns a PickingInfo
  28544. */
  28545. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28546. var _this = this;
  28547. if (!BABYLON.PickingInfo) {
  28548. return null;
  28549. }
  28550. var result = this._internalPick(function (world) {
  28551. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28552. return _this._tempPickingRay;
  28553. }, predicate, fastCheck);
  28554. if (result) {
  28555. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28556. }
  28557. return result;
  28558. };
  28559. /** Use the given ray to pick a mesh in the scene
  28560. * @param ray The ray to use to pick meshes
  28561. * @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
  28562. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28563. * @returns a PickingInfo
  28564. */
  28565. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28566. var _this = this;
  28567. var result = this._internalPick(function (world) {
  28568. if (!_this._pickWithRayInverseMatrix) {
  28569. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28570. }
  28571. world.invertToRef(_this._pickWithRayInverseMatrix);
  28572. if (!_this._cachedRayForTransform) {
  28573. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28574. }
  28575. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28576. return _this._cachedRayForTransform;
  28577. }, predicate, fastCheck);
  28578. if (result) {
  28579. result.ray = ray;
  28580. }
  28581. return result;
  28582. };
  28583. /**
  28584. * Launch a ray to try to pick a mesh in the scene
  28585. * @param x X position on screen
  28586. * @param y Y position on screen
  28587. * @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
  28588. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28589. * @returns an array of PickingInfo
  28590. */
  28591. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28592. var _this = this;
  28593. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28594. };
  28595. /**
  28596. * Launch a ray to try to pick a mesh in the scene
  28597. * @param ray Ray to use
  28598. * @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
  28599. * @returns an array of PickingInfo
  28600. */
  28601. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28602. var _this = this;
  28603. return this._internalMultiPick(function (world) {
  28604. if (!_this._pickWithRayInverseMatrix) {
  28605. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28606. }
  28607. world.invertToRef(_this._pickWithRayInverseMatrix);
  28608. if (!_this._cachedRayForTransform) {
  28609. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28610. }
  28611. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28612. return _this._cachedRayForTransform;
  28613. }, predicate);
  28614. };
  28615. /**
  28616. * Force the value of meshUnderPointer
  28617. * @param mesh defines the mesh to use
  28618. */
  28619. Scene.prototype.setPointerOverMesh = function (mesh) {
  28620. if (this._pointerOverMesh === mesh) {
  28621. return;
  28622. }
  28623. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28624. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28625. }
  28626. this._pointerOverMesh = mesh;
  28627. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28628. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28629. }
  28630. };
  28631. /**
  28632. * Gets the mesh under the pointer
  28633. * @returns a Mesh or null if no mesh is under the pointer
  28634. */
  28635. Scene.prototype.getPointerOverMesh = function () {
  28636. return this._pointerOverMesh;
  28637. };
  28638. // Misc.
  28639. /** @hidden */
  28640. Scene.prototype._rebuildGeometries = function () {
  28641. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28642. var geometry = _a[_i];
  28643. geometry._rebuild();
  28644. }
  28645. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28646. var mesh = _c[_b];
  28647. mesh._rebuild();
  28648. }
  28649. if (this.postProcessManager) {
  28650. this.postProcessManager._rebuild();
  28651. }
  28652. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28653. var component = _e[_d];
  28654. component.rebuild();
  28655. }
  28656. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28657. var system = _g[_f];
  28658. system.rebuild();
  28659. }
  28660. };
  28661. /** @hidden */
  28662. Scene.prototype._rebuildTextures = function () {
  28663. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28664. var texture = _a[_i];
  28665. texture._rebuild();
  28666. }
  28667. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28668. };
  28669. // Tags
  28670. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28671. if (tagsQuery === undefined) {
  28672. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28673. return list;
  28674. }
  28675. var listByTags = [];
  28676. forEach = forEach || (function (item) { return; });
  28677. for (var i in list) {
  28678. var item = list[i];
  28679. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28680. listByTags.push(item);
  28681. forEach(item);
  28682. }
  28683. }
  28684. return listByTags;
  28685. };
  28686. /**
  28687. * Get a list of meshes by tags
  28688. * @param tagsQuery defines the tags query to use
  28689. * @param forEach defines a predicate used to filter results
  28690. * @returns an array of Mesh
  28691. */
  28692. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28693. return this._getByTags(this.meshes, tagsQuery, forEach);
  28694. };
  28695. /**
  28696. * Get a list of cameras by tags
  28697. * @param tagsQuery defines the tags query to use
  28698. * @param forEach defines a predicate used to filter results
  28699. * @returns an array of Camera
  28700. */
  28701. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28702. return this._getByTags(this.cameras, tagsQuery, forEach);
  28703. };
  28704. /**
  28705. * Get a list of lights by tags
  28706. * @param tagsQuery defines the tags query to use
  28707. * @param forEach defines a predicate used to filter results
  28708. * @returns an array of Light
  28709. */
  28710. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28711. return this._getByTags(this.lights, tagsQuery, forEach);
  28712. };
  28713. /**
  28714. * Get a list of materials by tags
  28715. * @param tagsQuery defines the tags query to use
  28716. * @param forEach defines a predicate used to filter results
  28717. * @returns an array of Material
  28718. */
  28719. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28720. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28721. };
  28722. /**
  28723. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28724. * This allowed control for front to back rendering or reversly depending of the special needs.
  28725. *
  28726. * @param renderingGroupId The rendering group id corresponding to its index
  28727. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28728. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28729. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28730. */
  28731. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28732. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28733. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28734. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28735. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28736. };
  28737. /**
  28738. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28739. *
  28740. * @param renderingGroupId The rendering group id corresponding to its index
  28741. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28742. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28743. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28744. */
  28745. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28746. if (depth === void 0) { depth = true; }
  28747. if (stencil === void 0) { stencil = true; }
  28748. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28749. };
  28750. /**
  28751. * Gets the current auto clear configuration for one rendering group of the rendering
  28752. * manager.
  28753. * @param index the rendering group index to get the information for
  28754. * @returns The auto clear setup for the requested rendering group
  28755. */
  28756. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28757. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28758. };
  28759. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  28760. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  28761. get: function () {
  28762. return this._blockMaterialDirtyMechanism;
  28763. },
  28764. set: function (value) {
  28765. if (this._blockMaterialDirtyMechanism === value) {
  28766. return;
  28767. }
  28768. this._blockMaterialDirtyMechanism = value;
  28769. if (!value) { // Do a complete update
  28770. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  28771. }
  28772. },
  28773. enumerable: true,
  28774. configurable: true
  28775. });
  28776. /**
  28777. * Will flag all materials as dirty to trigger new shader compilation
  28778. * @param flag defines the flag used to specify which material part must be marked as dirty
  28779. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28780. */
  28781. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28782. if (this._blockMaterialDirtyMechanism) {
  28783. return;
  28784. }
  28785. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28786. var material = _a[_i];
  28787. if (predicate && !predicate(material)) {
  28788. continue;
  28789. }
  28790. material.markAsDirty(flag);
  28791. }
  28792. };
  28793. /** @hidden */
  28794. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28795. var _this = this;
  28796. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28797. this._activeRequests.push(request);
  28798. request.onCompleteObservable.add(function (request) {
  28799. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28800. });
  28801. return request;
  28802. };
  28803. /** @hidden */
  28804. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28805. var _this = this;
  28806. return new Promise(function (resolve, reject) {
  28807. _this._loadFile(url, function (data) {
  28808. resolve(data);
  28809. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28810. reject(exception);
  28811. });
  28812. });
  28813. };
  28814. // Statics
  28815. Scene._uniqueIdCounter = 0;
  28816. /** The fog is deactivated */
  28817. Scene.FOGMODE_NONE = 0;
  28818. /** The fog density is following an exponential function */
  28819. Scene.FOGMODE_EXP = 1;
  28820. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28821. Scene.FOGMODE_EXP2 = 2;
  28822. /** The fog density is following a linear function. */
  28823. Scene.FOGMODE_LINEAR = 3;
  28824. /**
  28825. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28826. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28827. */
  28828. Scene.MinDeltaTime = 1.0;
  28829. /**
  28830. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28831. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28832. */
  28833. Scene.MaxDeltaTime = 1000.0;
  28834. /** The distance in pixel that you have to move to prevent some events */
  28835. Scene.DragMovementThreshold = 10; // in pixels
  28836. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28837. Scene.LongPressDelay = 500; // in milliseconds
  28838. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28839. Scene.DoubleClickDelay = 300; // in milliseconds
  28840. /** If you need to check double click without raising a single click at first click, enable this flag */
  28841. Scene.ExclusiveDoubleClickMode = false;
  28842. return Scene;
  28843. }(BABYLON.AbstractScene));
  28844. BABYLON.Scene = Scene;
  28845. })(BABYLON || (BABYLON = {}));
  28846. //# sourceMappingURL=babylon.scene.js.map
  28847. var BABYLON;
  28848. (function (BABYLON) {
  28849. /**
  28850. * Set of assets to keep when moving a scene into an asset container.
  28851. */
  28852. var KeepAssets = /** @class */ (function (_super) {
  28853. __extends(KeepAssets, _super);
  28854. function KeepAssets() {
  28855. return _super !== null && _super.apply(this, arguments) || this;
  28856. }
  28857. return KeepAssets;
  28858. }(BABYLON.AbstractScene));
  28859. BABYLON.KeepAssets = KeepAssets;
  28860. /**
  28861. * Container with a set of assets that can be added or removed from a scene.
  28862. */
  28863. var AssetContainer = /** @class */ (function (_super) {
  28864. __extends(AssetContainer, _super);
  28865. /**
  28866. * Instantiates an AssetContainer.
  28867. * @param scene The scene the AssetContainer belongs to.
  28868. */
  28869. function AssetContainer(scene) {
  28870. var _this = _super.call(this) || this;
  28871. _this.scene = scene;
  28872. return _this;
  28873. }
  28874. /**
  28875. * Adds all the assets from the container to the scene.
  28876. */
  28877. AssetContainer.prototype.addAllToScene = function () {
  28878. var _this = this;
  28879. this.cameras.forEach(function (o) {
  28880. _this.scene.addCamera(o);
  28881. });
  28882. this.lights.forEach(function (o) {
  28883. _this.scene.addLight(o);
  28884. });
  28885. this.meshes.forEach(function (o) {
  28886. _this.scene.addMesh(o);
  28887. });
  28888. this.skeletons.forEach(function (o) {
  28889. _this.scene.addSkeleton(o);
  28890. });
  28891. this.animations.forEach(function (o) {
  28892. _this.scene.addAnimation(o);
  28893. });
  28894. this.animationGroups.forEach(function (o) {
  28895. _this.scene.addAnimationGroup(o);
  28896. });
  28897. this.multiMaterials.forEach(function (o) {
  28898. _this.scene.addMultiMaterial(o);
  28899. });
  28900. this.materials.forEach(function (o) {
  28901. _this.scene.addMaterial(o);
  28902. });
  28903. this.morphTargetManagers.forEach(function (o) {
  28904. _this.scene.addMorphTargetManager(o);
  28905. });
  28906. this.geometries.forEach(function (o) {
  28907. _this.scene.addGeometry(o);
  28908. });
  28909. this.transformNodes.forEach(function (o) {
  28910. _this.scene.addTransformNode(o);
  28911. });
  28912. this.actionManagers.forEach(function (o) {
  28913. _this.scene.addActionManager(o);
  28914. });
  28915. this.textures.forEach(function (o) {
  28916. _this.scene.addTexture(o);
  28917. });
  28918. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28919. var component = _a[_i];
  28920. component.addFromContainer(this.scene);
  28921. }
  28922. };
  28923. /**
  28924. * Removes all the assets in the container from the scene
  28925. */
  28926. AssetContainer.prototype.removeAllFromScene = function () {
  28927. var _this = this;
  28928. this.cameras.forEach(function (o) {
  28929. _this.scene.removeCamera(o);
  28930. });
  28931. this.lights.forEach(function (o) {
  28932. _this.scene.removeLight(o);
  28933. });
  28934. this.meshes.forEach(function (o) {
  28935. _this.scene.removeMesh(o);
  28936. });
  28937. this.skeletons.forEach(function (o) {
  28938. _this.scene.removeSkeleton(o);
  28939. });
  28940. this.animations.forEach(function (o) {
  28941. _this.scene.removeAnimation(o);
  28942. });
  28943. this.animationGroups.forEach(function (o) {
  28944. _this.scene.removeAnimationGroup(o);
  28945. });
  28946. this.multiMaterials.forEach(function (o) {
  28947. _this.scene.removeMultiMaterial(o);
  28948. });
  28949. this.materials.forEach(function (o) {
  28950. _this.scene.removeMaterial(o);
  28951. });
  28952. this.morphTargetManagers.forEach(function (o) {
  28953. _this.scene.removeMorphTargetManager(o);
  28954. });
  28955. this.geometries.forEach(function (o) {
  28956. _this.scene.removeGeometry(o);
  28957. });
  28958. this.transformNodes.forEach(function (o) {
  28959. _this.scene.removeTransformNode(o);
  28960. });
  28961. this.actionManagers.forEach(function (o) {
  28962. _this.scene.removeActionManager(o);
  28963. });
  28964. this.textures.forEach(function (o) {
  28965. _this.scene.removeTexture(o);
  28966. });
  28967. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28968. var component = _a[_i];
  28969. component.removeFromContainer(this.scene);
  28970. }
  28971. };
  28972. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28973. if (!sourceAssets) {
  28974. return;
  28975. }
  28976. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28977. var asset = sourceAssets_1[_i];
  28978. var move = true;
  28979. if (keepAssets) {
  28980. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28981. var keepAsset = keepAssets_1[_a];
  28982. if (asset === keepAsset) {
  28983. move = false;
  28984. break;
  28985. }
  28986. }
  28987. }
  28988. if (move) {
  28989. targetAssets.push(asset);
  28990. }
  28991. }
  28992. };
  28993. /**
  28994. * Removes all the assets contained in the scene and adds them to the container.
  28995. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28996. */
  28997. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28998. if (keepAssets === undefined) {
  28999. keepAssets = new KeepAssets();
  29000. }
  29001. for (var key in this) {
  29002. if (this.hasOwnProperty(key)) {
  29003. this[key] = this[key] || [];
  29004. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29005. }
  29006. }
  29007. this.removeAllFromScene();
  29008. };
  29009. /**
  29010. * 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.
  29011. * @returns the root mesh
  29012. */
  29013. AssetContainer.prototype.createRootMesh = function () {
  29014. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29015. this.meshes.forEach(function (m) {
  29016. if (!m.parent) {
  29017. rootMesh.addChild(m);
  29018. }
  29019. });
  29020. this.meshes.unshift(rootMesh);
  29021. return rootMesh;
  29022. };
  29023. return AssetContainer;
  29024. }(BABYLON.AbstractScene));
  29025. BABYLON.AssetContainer = AssetContainer;
  29026. })(BABYLON || (BABYLON = {}));
  29027. //# sourceMappingURL=babylon.assetContainer.js.map
  29028. var BABYLON;
  29029. (function (BABYLON) {
  29030. var Buffer = /** @class */ (function () {
  29031. /**
  29032. * Constructor
  29033. * @param engine the engine
  29034. * @param data the data to use for this buffer
  29035. * @param updatable whether the data is updatable
  29036. * @param stride the stride (optional)
  29037. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29038. * @param instanced whether the buffer is instanced (optional)
  29039. * @param useBytes set to true if the stride in in bytes (optional)
  29040. */
  29041. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29042. if (stride === void 0) { stride = 0; }
  29043. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29044. if (instanced === void 0) { instanced = false; }
  29045. if (useBytes === void 0) { useBytes = false; }
  29046. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29047. this._engine = engine.getScene().getEngine();
  29048. }
  29049. else {
  29050. this._engine = engine;
  29051. }
  29052. this._updatable = updatable;
  29053. this._instanced = instanced;
  29054. this._data = data;
  29055. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29056. if (!postponeInternalCreation) { // by default
  29057. this.create();
  29058. }
  29059. }
  29060. /**
  29061. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29062. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29063. * @param offset defines offset in the buffer (0 by default)
  29064. * @param size defines the size in floats of attributes (position is 3 for instance)
  29065. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29066. * @param instanced defines if the vertex buffer contains indexed data
  29067. * @param useBytes defines if the offset and stride are in bytes
  29068. * @returns the new vertex buffer
  29069. */
  29070. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29071. if (useBytes === void 0) { useBytes = false; }
  29072. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29073. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29074. // a lot of these parameters are ignored as they are overriden by the buffer
  29075. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29076. };
  29077. // Properties
  29078. Buffer.prototype.isUpdatable = function () {
  29079. return this._updatable;
  29080. };
  29081. Buffer.prototype.getData = function () {
  29082. return this._data;
  29083. };
  29084. Buffer.prototype.getBuffer = function () {
  29085. return this._buffer;
  29086. };
  29087. /**
  29088. * Gets the stride in float32 units (i.e. byte stride / 4).
  29089. * May not be an integer if the byte stride is not divisible by 4.
  29090. * DEPRECATED. Use byteStride instead.
  29091. * @returns the stride in float32 units
  29092. */
  29093. Buffer.prototype.getStrideSize = function () {
  29094. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29095. };
  29096. // Methods
  29097. Buffer.prototype.create = function (data) {
  29098. if (data === void 0) { data = null; }
  29099. if (!data && this._buffer) {
  29100. return; // nothing to do
  29101. }
  29102. data = data || this._data;
  29103. if (!data) {
  29104. return;
  29105. }
  29106. if (!this._buffer) { // create buffer
  29107. if (this._updatable) {
  29108. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29109. this._data = data;
  29110. }
  29111. else {
  29112. this._buffer = this._engine.createVertexBuffer(data);
  29113. }
  29114. }
  29115. else if (this._updatable) { // update buffer
  29116. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29117. this._data = data;
  29118. }
  29119. };
  29120. /** @hidden */
  29121. Buffer.prototype._rebuild = function () {
  29122. this._buffer = null;
  29123. this.create(this._data);
  29124. };
  29125. Buffer.prototype.update = function (data) {
  29126. this.create(data);
  29127. };
  29128. /**
  29129. * Updates the data directly.
  29130. * @param data the new data
  29131. * @param offset the new offset
  29132. * @param vertexCount the vertex count (optional)
  29133. * @param useBytes set to true if the offset is in bytes
  29134. */
  29135. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29136. if (useBytes === void 0) { useBytes = false; }
  29137. if (!this._buffer) {
  29138. return;
  29139. }
  29140. if (this._updatable) { // update buffer
  29141. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29142. this._data = null;
  29143. }
  29144. };
  29145. Buffer.prototype.dispose = function () {
  29146. if (!this._buffer) {
  29147. return;
  29148. }
  29149. if (this._engine._releaseBuffer(this._buffer)) {
  29150. this._buffer = null;
  29151. }
  29152. };
  29153. return Buffer;
  29154. }());
  29155. BABYLON.Buffer = Buffer;
  29156. })(BABYLON || (BABYLON = {}));
  29157. //# sourceMappingURL=babylon.buffer.js.map
  29158. var BABYLON;
  29159. (function (BABYLON) {
  29160. var VertexBuffer = /** @class */ (function () {
  29161. /**
  29162. * Constructor
  29163. * @param engine the engine
  29164. * @param data the data to use for this vertex buffer
  29165. * @param kind the vertex buffer kind
  29166. * @param updatable whether the data is updatable
  29167. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29168. * @param stride the stride (optional)
  29169. * @param instanced whether the buffer is instanced (optional)
  29170. * @param offset the offset of the data (optional)
  29171. * @param size the number of components (optional)
  29172. * @param type the type of the component (optional)
  29173. * @param normalized whether the data contains normalized data (optional)
  29174. * @param useBytes set to true if stride and offset are in bytes (optional)
  29175. */
  29176. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29177. if (normalized === void 0) { normalized = false; }
  29178. if (useBytes === void 0) { useBytes = false; }
  29179. if (data instanceof BABYLON.Buffer) {
  29180. this._buffer = data;
  29181. this._ownsBuffer = false;
  29182. }
  29183. else {
  29184. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29185. this._ownsBuffer = true;
  29186. }
  29187. this._kind = kind;
  29188. if (type == undefined) {
  29189. var data_1 = this.getData();
  29190. this.type = VertexBuffer.FLOAT;
  29191. if (data_1 instanceof Int8Array)
  29192. this.type = VertexBuffer.BYTE;
  29193. else if (data_1 instanceof Uint8Array)
  29194. this.type = VertexBuffer.UNSIGNED_BYTE;
  29195. else if (data_1 instanceof Int16Array)
  29196. this.type = VertexBuffer.SHORT;
  29197. else if (data_1 instanceof Uint16Array)
  29198. this.type = VertexBuffer.UNSIGNED_SHORT;
  29199. else if (data_1 instanceof Int32Array)
  29200. this.type = VertexBuffer.INT;
  29201. else if (data_1 instanceof Uint32Array)
  29202. this.type = VertexBuffer.UNSIGNED_INT;
  29203. }
  29204. else {
  29205. this.type = type;
  29206. }
  29207. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29208. if (useBytes) {
  29209. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29210. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29211. this.byteOffset = offset || 0;
  29212. }
  29213. else {
  29214. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29215. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29216. this.byteOffset = (offset || 0) * typeByteLength;
  29217. }
  29218. this.normalized = normalized;
  29219. this._instanced = instanced !== undefined ? instanced : false;
  29220. this._instanceDivisor = instanced ? 1 : 0;
  29221. }
  29222. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29223. /**
  29224. * Gets or sets the instance divisor when in instanced mode
  29225. */
  29226. get: function () {
  29227. return this._instanceDivisor;
  29228. },
  29229. set: function (value) {
  29230. this._instanceDivisor = value;
  29231. if (value == 0) {
  29232. this._instanced = false;
  29233. }
  29234. else {
  29235. this._instanced = true;
  29236. }
  29237. },
  29238. enumerable: true,
  29239. configurable: true
  29240. });
  29241. /** @hidden */
  29242. VertexBuffer.prototype._rebuild = function () {
  29243. if (!this._buffer) {
  29244. return;
  29245. }
  29246. this._buffer._rebuild();
  29247. };
  29248. /**
  29249. * Returns the kind of the VertexBuffer (string).
  29250. */
  29251. VertexBuffer.prototype.getKind = function () {
  29252. return this._kind;
  29253. };
  29254. // Properties
  29255. /**
  29256. * Boolean : is the VertexBuffer updatable ?
  29257. */
  29258. VertexBuffer.prototype.isUpdatable = function () {
  29259. return this._buffer.isUpdatable();
  29260. };
  29261. /**
  29262. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29263. */
  29264. VertexBuffer.prototype.getData = function () {
  29265. return this._buffer.getData();
  29266. };
  29267. /**
  29268. * Returns the WebGLBuffer associated to the VertexBuffer.
  29269. */
  29270. VertexBuffer.prototype.getBuffer = function () {
  29271. return this._buffer.getBuffer();
  29272. };
  29273. /**
  29274. * Returns the stride as a multiple of the type byte length.
  29275. * DEPRECATED. Use byteStride instead.
  29276. */
  29277. VertexBuffer.prototype.getStrideSize = function () {
  29278. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29279. };
  29280. /**
  29281. * Returns the offset as a multiple of the type byte length.
  29282. * DEPRECATED. Use byteOffset instead.
  29283. */
  29284. VertexBuffer.prototype.getOffset = function () {
  29285. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29286. };
  29287. /**
  29288. * Returns the number of components per vertex attribute (integer).
  29289. */
  29290. VertexBuffer.prototype.getSize = function () {
  29291. return this._size;
  29292. };
  29293. /**
  29294. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29295. */
  29296. VertexBuffer.prototype.getIsInstanced = function () {
  29297. return this._instanced;
  29298. };
  29299. /**
  29300. * Returns the instancing divisor, zero for non-instanced (integer).
  29301. */
  29302. VertexBuffer.prototype.getInstanceDivisor = function () {
  29303. return this._instanceDivisor;
  29304. };
  29305. // Methods
  29306. /**
  29307. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29308. * Returns the created WebGLBuffer.
  29309. */
  29310. VertexBuffer.prototype.create = function (data) {
  29311. return this._buffer.create(data);
  29312. };
  29313. /**
  29314. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29315. * This function will create a new buffer if the current one is not updatable
  29316. * Returns the updated WebGLBuffer.
  29317. */
  29318. VertexBuffer.prototype.update = function (data) {
  29319. return this._buffer.update(data);
  29320. };
  29321. /**
  29322. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29323. * Returns the directly updated WebGLBuffer.
  29324. * @param data the new data
  29325. * @param offset the new offset
  29326. * @param useBytes set to true if the offset is in bytes
  29327. */
  29328. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29329. if (useBytes === void 0) { useBytes = false; }
  29330. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29331. };
  29332. /**
  29333. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29334. */
  29335. VertexBuffer.prototype.dispose = function () {
  29336. if (this._ownsBuffer) {
  29337. this._buffer.dispose();
  29338. }
  29339. };
  29340. /**
  29341. * Enumerates each value of this vertex buffer as numbers.
  29342. * @param count the number of values to enumerate
  29343. * @param callback the callback function called for each value
  29344. */
  29345. VertexBuffer.prototype.forEach = function (count, callback) {
  29346. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29347. };
  29348. Object.defineProperty(VertexBuffer, "PositionKind", {
  29349. get: function () {
  29350. return VertexBuffer._PositionKind;
  29351. },
  29352. enumerable: true,
  29353. configurable: true
  29354. });
  29355. Object.defineProperty(VertexBuffer, "NormalKind", {
  29356. get: function () {
  29357. return VertexBuffer._NormalKind;
  29358. },
  29359. enumerable: true,
  29360. configurable: true
  29361. });
  29362. Object.defineProperty(VertexBuffer, "TangentKind", {
  29363. get: function () {
  29364. return VertexBuffer._TangentKind;
  29365. },
  29366. enumerable: true,
  29367. configurable: true
  29368. });
  29369. Object.defineProperty(VertexBuffer, "UVKind", {
  29370. get: function () {
  29371. return VertexBuffer._UVKind;
  29372. },
  29373. enumerable: true,
  29374. configurable: true
  29375. });
  29376. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29377. get: function () {
  29378. return VertexBuffer._UV2Kind;
  29379. },
  29380. enumerable: true,
  29381. configurable: true
  29382. });
  29383. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29384. get: function () {
  29385. return VertexBuffer._UV3Kind;
  29386. },
  29387. enumerable: true,
  29388. configurable: true
  29389. });
  29390. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29391. get: function () {
  29392. return VertexBuffer._UV4Kind;
  29393. },
  29394. enumerable: true,
  29395. configurable: true
  29396. });
  29397. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29398. get: function () {
  29399. return VertexBuffer._UV5Kind;
  29400. },
  29401. enumerable: true,
  29402. configurable: true
  29403. });
  29404. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29405. get: function () {
  29406. return VertexBuffer._UV6Kind;
  29407. },
  29408. enumerable: true,
  29409. configurable: true
  29410. });
  29411. Object.defineProperty(VertexBuffer, "ColorKind", {
  29412. get: function () {
  29413. return VertexBuffer._ColorKind;
  29414. },
  29415. enumerable: true,
  29416. configurable: true
  29417. });
  29418. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29419. get: function () {
  29420. return VertexBuffer._MatricesIndicesKind;
  29421. },
  29422. enumerable: true,
  29423. configurable: true
  29424. });
  29425. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29426. get: function () {
  29427. return VertexBuffer._MatricesWeightsKind;
  29428. },
  29429. enumerable: true,
  29430. configurable: true
  29431. });
  29432. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29433. get: function () {
  29434. return VertexBuffer._MatricesIndicesExtraKind;
  29435. },
  29436. enumerable: true,
  29437. configurable: true
  29438. });
  29439. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29440. get: function () {
  29441. return VertexBuffer._MatricesWeightsExtraKind;
  29442. },
  29443. enumerable: true,
  29444. configurable: true
  29445. });
  29446. /**
  29447. * Deduces the stride given a kind.
  29448. * @param kind The kind string to deduce
  29449. * @returns The deduced stride
  29450. */
  29451. VertexBuffer.DeduceStride = function (kind) {
  29452. switch (kind) {
  29453. case VertexBuffer.UVKind:
  29454. case VertexBuffer.UV2Kind:
  29455. case VertexBuffer.UV3Kind:
  29456. case VertexBuffer.UV4Kind:
  29457. case VertexBuffer.UV5Kind:
  29458. case VertexBuffer.UV6Kind:
  29459. return 2;
  29460. case VertexBuffer.NormalKind:
  29461. case VertexBuffer.PositionKind:
  29462. return 3;
  29463. case VertexBuffer.ColorKind:
  29464. case VertexBuffer.MatricesIndicesKind:
  29465. case VertexBuffer.MatricesIndicesExtraKind:
  29466. case VertexBuffer.MatricesWeightsKind:
  29467. case VertexBuffer.MatricesWeightsExtraKind:
  29468. case VertexBuffer.TangentKind:
  29469. return 4;
  29470. default:
  29471. throw new Error("Invalid kind '" + kind + "'");
  29472. }
  29473. };
  29474. /**
  29475. * Gets the byte length of the given type.
  29476. * @param type the type
  29477. * @returns the number of bytes
  29478. */
  29479. VertexBuffer.GetTypeByteLength = function (type) {
  29480. switch (type) {
  29481. case VertexBuffer.BYTE:
  29482. case VertexBuffer.UNSIGNED_BYTE:
  29483. return 1;
  29484. case VertexBuffer.SHORT:
  29485. case VertexBuffer.UNSIGNED_SHORT:
  29486. return 2;
  29487. case VertexBuffer.INT:
  29488. case VertexBuffer.FLOAT:
  29489. return 4;
  29490. default:
  29491. throw new Error("Invalid type '" + type + "'");
  29492. }
  29493. };
  29494. /**
  29495. * Enumerates each value of the given parameters as numbers.
  29496. * @param data the data to enumerate
  29497. * @param byteOffset the byte offset of the data
  29498. * @param byteStride the byte stride of the data
  29499. * @param componentCount the number of components per element
  29500. * @param componentType the type of the component
  29501. * @param count the total number of components
  29502. * @param normalized whether the data is normalized
  29503. * @param callback the callback function called for each value
  29504. */
  29505. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29506. if (data instanceof Array) {
  29507. var offset = byteOffset / 4;
  29508. var stride = byteStride / 4;
  29509. for (var index = 0; index < count; index += componentCount) {
  29510. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29511. callback(data[offset + componentIndex], index + componentIndex);
  29512. }
  29513. offset += stride;
  29514. }
  29515. }
  29516. else {
  29517. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29518. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29519. for (var index = 0; index < count; index += componentCount) {
  29520. var componentByteOffset = byteOffset;
  29521. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29522. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29523. callback(value, index + componentIndex);
  29524. componentByteOffset += componentByteLength;
  29525. }
  29526. byteOffset += byteStride;
  29527. }
  29528. }
  29529. };
  29530. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29531. switch (type) {
  29532. case VertexBuffer.BYTE: {
  29533. var value = dataView.getInt8(byteOffset);
  29534. if (normalized) {
  29535. value = Math.max(value / 127, -1);
  29536. }
  29537. return value;
  29538. }
  29539. case VertexBuffer.UNSIGNED_BYTE: {
  29540. var value = dataView.getUint8(byteOffset);
  29541. if (normalized) {
  29542. value = value / 255;
  29543. }
  29544. return value;
  29545. }
  29546. case VertexBuffer.SHORT: {
  29547. var value = dataView.getInt16(byteOffset, true);
  29548. if (normalized) {
  29549. value = Math.max(value / 16383, -1);
  29550. }
  29551. return value;
  29552. }
  29553. case VertexBuffer.UNSIGNED_SHORT: {
  29554. var value = dataView.getUint16(byteOffset, true);
  29555. if (normalized) {
  29556. value = value / 65535;
  29557. }
  29558. return value;
  29559. }
  29560. case VertexBuffer.FLOAT: {
  29561. return dataView.getFloat32(byteOffset, true);
  29562. }
  29563. default: {
  29564. throw new Error("Invalid component type " + type);
  29565. }
  29566. }
  29567. };
  29568. /**
  29569. * The byte type.
  29570. */
  29571. VertexBuffer.BYTE = 5120;
  29572. /**
  29573. * The unsigned byte type.
  29574. */
  29575. VertexBuffer.UNSIGNED_BYTE = 5121;
  29576. /**
  29577. * The short type.
  29578. */
  29579. VertexBuffer.SHORT = 5122;
  29580. /**
  29581. * The unsigned short type.
  29582. */
  29583. VertexBuffer.UNSIGNED_SHORT = 5123;
  29584. /**
  29585. * The integer type.
  29586. */
  29587. VertexBuffer.INT = 5124;
  29588. /**
  29589. * The unsigned integer type.
  29590. */
  29591. VertexBuffer.UNSIGNED_INT = 5125;
  29592. /**
  29593. * The float type.
  29594. */
  29595. VertexBuffer.FLOAT = 5126;
  29596. // Enums
  29597. VertexBuffer._PositionKind = "position";
  29598. VertexBuffer._NormalKind = "normal";
  29599. VertexBuffer._TangentKind = "tangent";
  29600. VertexBuffer._UVKind = "uv";
  29601. VertexBuffer._UV2Kind = "uv2";
  29602. VertexBuffer._UV3Kind = "uv3";
  29603. VertexBuffer._UV4Kind = "uv4";
  29604. VertexBuffer._UV5Kind = "uv5";
  29605. VertexBuffer._UV6Kind = "uv6";
  29606. VertexBuffer._ColorKind = "color";
  29607. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29608. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29609. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29610. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29611. return VertexBuffer;
  29612. }());
  29613. BABYLON.VertexBuffer = VertexBuffer;
  29614. })(BABYLON || (BABYLON = {}));
  29615. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29616. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29617. var BABYLON;
  29618. (function (BABYLON) {
  29619. /**
  29620. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29621. */
  29622. var DummyInternalTextureTracker = /** @class */ (function () {
  29623. function DummyInternalTextureTracker() {
  29624. /**
  29625. * Gets or set the previous tracker in the list
  29626. */
  29627. this.previous = null;
  29628. /**
  29629. * Gets or set the next tracker in the list
  29630. */
  29631. this.next = null;
  29632. }
  29633. return DummyInternalTextureTracker;
  29634. }());
  29635. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29636. })(BABYLON || (BABYLON = {}));
  29637. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29638. var BABYLON;
  29639. (function (BABYLON) {
  29640. /**
  29641. * Class used to store data associated with WebGL texture data for the engine
  29642. * This class should not be used directly
  29643. */
  29644. var InternalTexture = /** @class */ (function () {
  29645. /**
  29646. * Creates a new InternalTexture
  29647. * @param engine defines the engine to use
  29648. * @param dataSource defines the type of data that will be used
  29649. */
  29650. function InternalTexture(engine, dataSource) {
  29651. /**
  29652. * Observable called when the texture is loaded
  29653. */
  29654. this.onLoadedObservable = new BABYLON.Observable();
  29655. /**
  29656. * Gets or set the previous tracker in the list
  29657. */
  29658. this.previous = null;
  29659. /**
  29660. * Gets or set the next tracker in the list
  29661. */
  29662. this.next = null;
  29663. // Private
  29664. /** @hidden */
  29665. this._initialSlot = -1;
  29666. /** @hidden */
  29667. this._designatedSlot = -1;
  29668. /** @hidden */
  29669. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29670. /** @hidden */
  29671. this._comparisonFunction = 0;
  29672. /** @hidden */
  29673. this._sphericalPolynomial = null;
  29674. /** @hidden */
  29675. this._lodGenerationScale = 0;
  29676. /** @hidden */
  29677. this._lodGenerationOffset = 0;
  29678. /** @hidden */
  29679. this._isRGBD = false;
  29680. /** @hidden */
  29681. this._references = 1;
  29682. this._engine = engine;
  29683. this._dataSource = dataSource;
  29684. this._webGLTexture = engine._createTexture();
  29685. }
  29686. /**
  29687. * Gets the Engine the texture belongs to.
  29688. * @returns The babylon engine
  29689. */
  29690. InternalTexture.prototype.getEngine = function () {
  29691. return this._engine;
  29692. };
  29693. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29694. /**
  29695. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29696. */
  29697. get: function () {
  29698. return this._dataSource;
  29699. },
  29700. enumerable: true,
  29701. configurable: true
  29702. });
  29703. /**
  29704. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29705. */
  29706. InternalTexture.prototype.incrementReferences = function () {
  29707. this._references++;
  29708. };
  29709. /**
  29710. * Change the size of the texture (not the size of the content)
  29711. * @param width defines the new width
  29712. * @param height defines the new height
  29713. * @param depth defines the new depth (1 by default)
  29714. */
  29715. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29716. if (depth === void 0) { depth = 1; }
  29717. this.width = width;
  29718. this.height = height;
  29719. this.depth = depth;
  29720. this.baseWidth = width;
  29721. this.baseHeight = height;
  29722. this.baseDepth = depth;
  29723. this._size = width * height * depth;
  29724. };
  29725. /** @hidden */
  29726. InternalTexture.prototype._rebuild = function () {
  29727. var _this = this;
  29728. var proxy;
  29729. this.isReady = false;
  29730. this._cachedCoordinatesMode = null;
  29731. this._cachedWrapU = null;
  29732. this._cachedWrapV = null;
  29733. this._cachedAnisotropicFilteringLevel = null;
  29734. switch (this._dataSource) {
  29735. case InternalTexture.DATASOURCE_TEMP:
  29736. return;
  29737. case InternalTexture.DATASOURCE_URL:
  29738. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29739. _this.isReady = true;
  29740. }, null, this._buffer, undefined, this.format);
  29741. proxy._swapAndDie(this);
  29742. return;
  29743. case InternalTexture.DATASOURCE_RAW:
  29744. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29745. proxy._swapAndDie(this);
  29746. this.isReady = true;
  29747. return;
  29748. case InternalTexture.DATASOURCE_RAW3D:
  29749. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29750. proxy._swapAndDie(this);
  29751. this.isReady = true;
  29752. return;
  29753. case InternalTexture.DATASOURCE_DYNAMIC:
  29754. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29755. proxy._swapAndDie(this);
  29756. // The engine will make sure to update content so no need to flag it as isReady = true
  29757. return;
  29758. case InternalTexture.DATASOURCE_RENDERTARGET:
  29759. var options = new BABYLON.RenderTargetCreationOptions();
  29760. options.generateDepthBuffer = this._generateDepthBuffer;
  29761. options.generateMipMaps = this.generateMipMaps;
  29762. options.generateStencilBuffer = this._generateStencilBuffer;
  29763. options.samplingMode = this.samplingMode;
  29764. options.type = this.type;
  29765. if (this.isCube) {
  29766. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29767. }
  29768. else {
  29769. var size = {
  29770. width: this.width,
  29771. height: this.height
  29772. };
  29773. proxy = this._engine.createRenderTargetTexture(size, options);
  29774. }
  29775. proxy._swapAndDie(this);
  29776. this.isReady = true;
  29777. return;
  29778. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29779. var depthTextureOptions = {
  29780. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29781. comparisonFunction: this._comparisonFunction,
  29782. generateStencil: this._generateStencilBuffer,
  29783. isCube: this.isCube
  29784. };
  29785. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29786. proxy._swapAndDie(this);
  29787. this.isReady = true;
  29788. return;
  29789. case InternalTexture.DATASOURCE_CUBE:
  29790. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29791. _this.isReady = true;
  29792. }, null, this.format, this._extension);
  29793. proxy._swapAndDie(this);
  29794. return;
  29795. case InternalTexture.DATASOURCE_CUBERAW:
  29796. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29797. proxy._swapAndDie(this);
  29798. this.isReady = true;
  29799. return;
  29800. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29801. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29802. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29803. _this.isReady = true;
  29804. });
  29805. proxy._swapAndDie(this);
  29806. return;
  29807. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29808. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29809. if (proxy) {
  29810. proxy._swapAndDie(_this);
  29811. }
  29812. _this.isReady = true;
  29813. }, null, this.format, this._extension);
  29814. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29815. return;
  29816. }
  29817. };
  29818. /** @hidden */
  29819. InternalTexture.prototype._swapAndDie = function (target) {
  29820. target._webGLTexture = this._webGLTexture;
  29821. if (this._framebuffer) {
  29822. target._framebuffer = this._framebuffer;
  29823. }
  29824. if (this._depthStencilBuffer) {
  29825. target._depthStencilBuffer = this._depthStencilBuffer;
  29826. }
  29827. if (this._lodTextureHigh) {
  29828. if (target._lodTextureHigh) {
  29829. target._lodTextureHigh.dispose();
  29830. }
  29831. target._lodTextureHigh = this._lodTextureHigh;
  29832. }
  29833. if (this._lodTextureMid) {
  29834. if (target._lodTextureMid) {
  29835. target._lodTextureMid.dispose();
  29836. }
  29837. target._lodTextureMid = this._lodTextureMid;
  29838. }
  29839. if (this._lodTextureLow) {
  29840. if (target._lodTextureLow) {
  29841. target._lodTextureLow.dispose();
  29842. }
  29843. target._lodTextureLow = this._lodTextureLow;
  29844. }
  29845. var cache = this._engine.getLoadedTexturesCache();
  29846. var index = cache.indexOf(this);
  29847. if (index !== -1) {
  29848. cache.splice(index, 1);
  29849. }
  29850. };
  29851. /**
  29852. * Dispose the current allocated resources
  29853. */
  29854. InternalTexture.prototype.dispose = function () {
  29855. if (!this._webGLTexture) {
  29856. return;
  29857. }
  29858. this._references--;
  29859. if (this._references === 0) {
  29860. this._engine._releaseTexture(this);
  29861. this._webGLTexture = null;
  29862. this.previous = null;
  29863. this.next = null;
  29864. }
  29865. };
  29866. /**
  29867. * The source of the texture data is unknown
  29868. */
  29869. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29870. /**
  29871. * Texture data comes from an URL
  29872. */
  29873. InternalTexture.DATASOURCE_URL = 1;
  29874. /**
  29875. * Texture data is only used for temporary storage
  29876. */
  29877. InternalTexture.DATASOURCE_TEMP = 2;
  29878. /**
  29879. * Texture data comes from raw data (ArrayBuffer)
  29880. */
  29881. InternalTexture.DATASOURCE_RAW = 3;
  29882. /**
  29883. * Texture content is dynamic (video or dynamic texture)
  29884. */
  29885. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29886. /**
  29887. * Texture content is generated by rendering to it
  29888. */
  29889. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29890. /**
  29891. * Texture content is part of a multi render target process
  29892. */
  29893. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29894. /**
  29895. * Texture data comes from a cube data file
  29896. */
  29897. InternalTexture.DATASOURCE_CUBE = 7;
  29898. /**
  29899. * Texture data comes from a raw cube data
  29900. */
  29901. InternalTexture.DATASOURCE_CUBERAW = 8;
  29902. /**
  29903. * Texture data come from a prefiltered cube data file
  29904. */
  29905. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29906. /**
  29907. * Texture content is raw 3D data
  29908. */
  29909. InternalTexture.DATASOURCE_RAW3D = 10;
  29910. /**
  29911. * Texture content is a depth texture
  29912. */
  29913. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29914. /**
  29915. * Texture data comes from a raw cube data encoded with RGBD
  29916. */
  29917. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29918. return InternalTexture;
  29919. }());
  29920. BABYLON.InternalTexture = InternalTexture;
  29921. })(BABYLON || (BABYLON = {}));
  29922. //# sourceMappingURL=babylon.internalTexture.js.map
  29923. var BABYLON;
  29924. (function (BABYLON) {
  29925. var BaseTexture = /** @class */ (function () {
  29926. function BaseTexture(scene) {
  29927. this._hasAlpha = false;
  29928. this.getAlphaFromRGB = false;
  29929. this.level = 1;
  29930. this.coordinatesIndex = 0;
  29931. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29932. /**
  29933. * | Value | Type | Description |
  29934. * | ----- | ------------------ | ----------- |
  29935. * | 0 | CLAMP_ADDRESSMODE | |
  29936. * | 1 | WRAP_ADDRESSMODE | |
  29937. * | 2 | MIRROR_ADDRESSMODE | |
  29938. */
  29939. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29940. /**
  29941. * | Value | Type | Description |
  29942. * | ----- | ------------------ | ----------- |
  29943. * | 0 | CLAMP_ADDRESSMODE | |
  29944. * | 1 | WRAP_ADDRESSMODE | |
  29945. * | 2 | MIRROR_ADDRESSMODE | |
  29946. */
  29947. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29948. /**
  29949. * | Value | Type | Description |
  29950. * | ----- | ------------------ | ----------- |
  29951. * | 0 | CLAMP_ADDRESSMODE | |
  29952. * | 1 | WRAP_ADDRESSMODE | |
  29953. * | 2 | MIRROR_ADDRESSMODE | |
  29954. */
  29955. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29956. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29957. this.isCube = false;
  29958. this.is3D = false;
  29959. this.gammaSpace = true;
  29960. this.invertZ = false;
  29961. this.lodLevelInAlpha = false;
  29962. this.isRenderTarget = false;
  29963. this.animations = new Array();
  29964. /**
  29965. * An event triggered when the texture is disposed.
  29966. */
  29967. this.onDisposeObservable = new BABYLON.Observable();
  29968. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29969. this._cachedSize = BABYLON.Size.Zero();
  29970. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29971. if (this._scene) {
  29972. this._scene.textures.push(this);
  29973. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  29974. }
  29975. this._uid = null;
  29976. }
  29977. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29978. get: function () {
  29979. return this._hasAlpha;
  29980. },
  29981. set: function (value) {
  29982. if (this._hasAlpha === value) {
  29983. return;
  29984. }
  29985. this._hasAlpha = value;
  29986. if (this._scene) {
  29987. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29988. }
  29989. },
  29990. enumerable: true,
  29991. configurable: true
  29992. });
  29993. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29994. get: function () {
  29995. return this._coordinatesMode;
  29996. },
  29997. /**
  29998. * How a texture is mapped.
  29999. *
  30000. * | Value | Type | Description |
  30001. * | ----- | ----------------------------------- | ----------- |
  30002. * | 0 | EXPLICIT_MODE | |
  30003. * | 1 | SPHERICAL_MODE | |
  30004. * | 2 | PLANAR_MODE | |
  30005. * | 3 | CUBIC_MODE | |
  30006. * | 4 | PROJECTION_MODE | |
  30007. * | 5 | SKYBOX_MODE | |
  30008. * | 6 | INVCUBIC_MODE | |
  30009. * | 7 | EQUIRECTANGULAR_MODE | |
  30010. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30011. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30012. */
  30013. set: function (value) {
  30014. if (this._coordinatesMode === value) {
  30015. return;
  30016. }
  30017. this._coordinatesMode = value;
  30018. if (this._scene) {
  30019. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30020. }
  30021. },
  30022. enumerable: true,
  30023. configurable: true
  30024. });
  30025. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30026. /**
  30027. * Gets whether or not the texture contains RGBD data.
  30028. */
  30029. get: function () {
  30030. return this._texture != null && this._texture._isRGBD;
  30031. },
  30032. enumerable: true,
  30033. configurable: true
  30034. });
  30035. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30036. get: function () {
  30037. if (this._texture)
  30038. return this._texture._lodGenerationOffset;
  30039. return 0.0;
  30040. },
  30041. set: function (value) {
  30042. if (this._texture)
  30043. this._texture._lodGenerationOffset = value;
  30044. },
  30045. enumerable: true,
  30046. configurable: true
  30047. });
  30048. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30049. get: function () {
  30050. if (this._texture)
  30051. return this._texture._lodGenerationScale;
  30052. return 0.0;
  30053. },
  30054. set: function (value) {
  30055. if (this._texture)
  30056. this._texture._lodGenerationScale = value;
  30057. },
  30058. enumerable: true,
  30059. configurable: true
  30060. });
  30061. Object.defineProperty(BaseTexture.prototype, "uid", {
  30062. get: function () {
  30063. if (!this._uid) {
  30064. this._uid = BABYLON.Tools.RandomId();
  30065. }
  30066. return this._uid;
  30067. },
  30068. enumerable: true,
  30069. configurable: true
  30070. });
  30071. BaseTexture.prototype.toString = function () {
  30072. return this.name;
  30073. };
  30074. BaseTexture.prototype.getClassName = function () {
  30075. return "BaseTexture";
  30076. };
  30077. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30078. set: function (callback) {
  30079. if (this._onDisposeObserver) {
  30080. this.onDisposeObservable.remove(this._onDisposeObserver);
  30081. }
  30082. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30083. },
  30084. enumerable: true,
  30085. configurable: true
  30086. });
  30087. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30088. get: function () {
  30089. return true;
  30090. },
  30091. enumerable: true,
  30092. configurable: true
  30093. });
  30094. BaseTexture.prototype.getScene = function () {
  30095. return this._scene;
  30096. };
  30097. BaseTexture.prototype.getTextureMatrix = function () {
  30098. return BABYLON.Matrix.IdentityReadOnly;
  30099. };
  30100. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30101. return BABYLON.Matrix.IdentityReadOnly;
  30102. };
  30103. BaseTexture.prototype.getInternalTexture = function () {
  30104. return this._texture;
  30105. };
  30106. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30107. return !this.isBlocking || this.isReady();
  30108. };
  30109. BaseTexture.prototype.isReady = function () {
  30110. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30111. this.delayLoad();
  30112. return false;
  30113. }
  30114. if (this._texture) {
  30115. return this._texture.isReady;
  30116. }
  30117. return false;
  30118. };
  30119. BaseTexture.prototype.getSize = function () {
  30120. if (this._texture) {
  30121. if (this._texture.width) {
  30122. this._cachedSize.width = this._texture.width;
  30123. this._cachedSize.height = this._texture.height;
  30124. return this._cachedSize;
  30125. }
  30126. if (this._texture._size) {
  30127. this._cachedSize.width = this._texture._size;
  30128. this._cachedSize.height = this._texture._size;
  30129. return this._cachedSize;
  30130. }
  30131. }
  30132. return this._cachedSize;
  30133. };
  30134. BaseTexture.prototype.getBaseSize = function () {
  30135. if (!this.isReady() || !this._texture)
  30136. return BABYLON.Size.Zero();
  30137. if (this._texture._size) {
  30138. return new BABYLON.Size(this._texture._size, this._texture._size);
  30139. }
  30140. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30141. };
  30142. BaseTexture.prototype.scale = function (ratio) {
  30143. };
  30144. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30145. get: function () {
  30146. return false;
  30147. },
  30148. enumerable: true,
  30149. configurable: true
  30150. });
  30151. /** @hidden */
  30152. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30153. if (!this._scene) {
  30154. return null;
  30155. }
  30156. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30157. for (var index = 0; index < texturesCache.length; index++) {
  30158. var texturesCacheEntry = texturesCache[index];
  30159. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30160. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30161. texturesCacheEntry.incrementReferences();
  30162. return texturesCacheEntry;
  30163. }
  30164. }
  30165. }
  30166. return null;
  30167. };
  30168. /** @hidden */
  30169. BaseTexture.prototype._rebuild = function () {
  30170. };
  30171. BaseTexture.prototype.delayLoad = function () {
  30172. };
  30173. BaseTexture.prototype.clone = function () {
  30174. return null;
  30175. };
  30176. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30177. get: function () {
  30178. if (!this._texture) {
  30179. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30180. }
  30181. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30182. },
  30183. enumerable: true,
  30184. configurable: true
  30185. });
  30186. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30187. get: function () {
  30188. if (!this._texture) {
  30189. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30190. }
  30191. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30192. },
  30193. enumerable: true,
  30194. configurable: true
  30195. });
  30196. /**
  30197. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30198. * This will returns an RGBA array buffer containing either in values (0-255) or
  30199. * float values (0-1) depending of the underlying buffer type.
  30200. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30201. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30202. * @param buffer defines a user defined buffer to fill with data (can be null)
  30203. * @returns The Array buffer containing the pixels data.
  30204. */
  30205. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30206. if (faceIndex === void 0) { faceIndex = 0; }
  30207. if (level === void 0) { level = 0; }
  30208. if (buffer === void 0) { buffer = null; }
  30209. if (!this._texture) {
  30210. return null;
  30211. }
  30212. var size = this.getSize();
  30213. var width = size.width;
  30214. var height = size.height;
  30215. var scene = this.getScene();
  30216. if (!scene) {
  30217. return null;
  30218. }
  30219. var engine = scene.getEngine();
  30220. if (level != 0) {
  30221. width = width / Math.pow(2, level);
  30222. height = height / Math.pow(2, level);
  30223. width = Math.round(width);
  30224. height = Math.round(height);
  30225. }
  30226. if (this._texture.isCube) {
  30227. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30228. }
  30229. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30230. };
  30231. BaseTexture.prototype.releaseInternalTexture = function () {
  30232. if (this._texture) {
  30233. this._texture.dispose();
  30234. this._texture = null;
  30235. }
  30236. };
  30237. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30238. get: function () {
  30239. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30240. return null;
  30241. }
  30242. if (!this._texture._sphericalPolynomial) {
  30243. this._texture._sphericalPolynomial =
  30244. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30245. }
  30246. return this._texture._sphericalPolynomial;
  30247. },
  30248. set: function (value) {
  30249. if (this._texture) {
  30250. this._texture._sphericalPolynomial = value;
  30251. }
  30252. },
  30253. enumerable: true,
  30254. configurable: true
  30255. });
  30256. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30257. get: function () {
  30258. if (this._texture) {
  30259. return this._texture._lodTextureHigh;
  30260. }
  30261. return null;
  30262. },
  30263. enumerable: true,
  30264. configurable: true
  30265. });
  30266. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30267. get: function () {
  30268. if (this._texture) {
  30269. return this._texture._lodTextureMid;
  30270. }
  30271. return null;
  30272. },
  30273. enumerable: true,
  30274. configurable: true
  30275. });
  30276. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30277. get: function () {
  30278. if (this._texture) {
  30279. return this._texture._lodTextureLow;
  30280. }
  30281. return null;
  30282. },
  30283. enumerable: true,
  30284. configurable: true
  30285. });
  30286. BaseTexture.prototype.dispose = function () {
  30287. if (!this._scene) {
  30288. return;
  30289. }
  30290. // Animations
  30291. this._scene.stopAnimation(this);
  30292. // Remove from scene
  30293. this._scene._removePendingData(this);
  30294. var index = this._scene.textures.indexOf(this);
  30295. if (index >= 0) {
  30296. this._scene.textures.splice(index, 1);
  30297. }
  30298. this._scene.onTextureRemovedObservable.notifyObservers(this);
  30299. if (this._texture === undefined) {
  30300. return;
  30301. }
  30302. // Release
  30303. this.releaseInternalTexture();
  30304. // Callback
  30305. this.onDisposeObservable.notifyObservers(this);
  30306. this.onDisposeObservable.clear();
  30307. };
  30308. BaseTexture.prototype.serialize = function () {
  30309. if (!this.name) {
  30310. return null;
  30311. }
  30312. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30313. // Animations
  30314. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30315. return serializationObject;
  30316. };
  30317. BaseTexture.WhenAllReady = function (textures, callback) {
  30318. var numRemaining = textures.length;
  30319. if (numRemaining === 0) {
  30320. callback();
  30321. return;
  30322. }
  30323. var _loop_1 = function () {
  30324. texture = textures[i];
  30325. if (texture.isReady()) {
  30326. if (--numRemaining === 0) {
  30327. callback();
  30328. }
  30329. }
  30330. else {
  30331. onLoadObservable = texture.onLoadObservable;
  30332. var onLoadCallback_1 = function () {
  30333. onLoadObservable.removeCallback(onLoadCallback_1);
  30334. if (--numRemaining === 0) {
  30335. callback();
  30336. }
  30337. };
  30338. onLoadObservable.add(onLoadCallback_1);
  30339. }
  30340. };
  30341. var texture, onLoadObservable;
  30342. for (var i = 0; i < textures.length; i++) {
  30343. _loop_1();
  30344. }
  30345. };
  30346. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30347. __decorate([
  30348. BABYLON.serialize()
  30349. ], BaseTexture.prototype, "name", void 0);
  30350. __decorate([
  30351. BABYLON.serialize("hasAlpha")
  30352. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30353. __decorate([
  30354. BABYLON.serialize()
  30355. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30356. __decorate([
  30357. BABYLON.serialize()
  30358. ], BaseTexture.prototype, "level", void 0);
  30359. __decorate([
  30360. BABYLON.serialize()
  30361. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30362. __decorate([
  30363. BABYLON.serialize("coordinatesMode")
  30364. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30365. __decorate([
  30366. BABYLON.serialize()
  30367. ], BaseTexture.prototype, "wrapU", void 0);
  30368. __decorate([
  30369. BABYLON.serialize()
  30370. ], BaseTexture.prototype, "wrapV", void 0);
  30371. __decorate([
  30372. BABYLON.serialize()
  30373. ], BaseTexture.prototype, "wrapR", void 0);
  30374. __decorate([
  30375. BABYLON.serialize()
  30376. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30377. __decorate([
  30378. BABYLON.serialize()
  30379. ], BaseTexture.prototype, "isCube", void 0);
  30380. __decorate([
  30381. BABYLON.serialize()
  30382. ], BaseTexture.prototype, "is3D", void 0);
  30383. __decorate([
  30384. BABYLON.serialize()
  30385. ], BaseTexture.prototype, "gammaSpace", void 0);
  30386. __decorate([
  30387. BABYLON.serialize()
  30388. ], BaseTexture.prototype, "invertZ", void 0);
  30389. __decorate([
  30390. BABYLON.serialize()
  30391. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30392. __decorate([
  30393. BABYLON.serialize()
  30394. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30395. __decorate([
  30396. BABYLON.serialize()
  30397. ], BaseTexture.prototype, "lodGenerationScale", null);
  30398. __decorate([
  30399. BABYLON.serialize()
  30400. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30401. return BaseTexture;
  30402. }());
  30403. BABYLON.BaseTexture = BaseTexture;
  30404. })(BABYLON || (BABYLON = {}));
  30405. //# sourceMappingURL=babylon.baseTexture.js.map
  30406. var BABYLON;
  30407. (function (BABYLON) {
  30408. var Texture = /** @class */ (function (_super) {
  30409. __extends(Texture, _super);
  30410. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30411. if (noMipmap === void 0) { noMipmap = false; }
  30412. if (invertY === void 0) { invertY = true; }
  30413. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30414. if (onLoad === void 0) { onLoad = null; }
  30415. if (onError === void 0) { onError = null; }
  30416. if (buffer === void 0) { buffer = null; }
  30417. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30418. var _this = _super.call(this, scene) || this;
  30419. _this.uOffset = 0;
  30420. _this.vOffset = 0;
  30421. _this.uScale = 1.0;
  30422. _this.vScale = 1.0;
  30423. _this.uAng = 0;
  30424. _this.vAng = 0;
  30425. _this.wAng = 0;
  30426. /**
  30427. * Defines the center of rotation (U)
  30428. */
  30429. _this.uRotationCenter = 0.5;
  30430. /**
  30431. * Defines the center of rotation (V)
  30432. */
  30433. _this.vRotationCenter = 0.5;
  30434. /**
  30435. * Defines the center of rotation (W)
  30436. */
  30437. _this.wRotationCenter = 0.5;
  30438. _this._isBlocking = true;
  30439. _this.name = url || "";
  30440. _this.url = url;
  30441. _this._noMipmap = noMipmap;
  30442. _this._invertY = invertY;
  30443. _this._samplingMode = samplingMode;
  30444. _this._buffer = buffer;
  30445. _this._deleteBuffer = deleteBuffer;
  30446. if (format) {
  30447. _this._format = format;
  30448. }
  30449. scene = _this.getScene();
  30450. if (!scene) {
  30451. return _this;
  30452. }
  30453. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30454. var load = function () {
  30455. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30456. _this.onLoadObservable.notifyObservers(_this);
  30457. }
  30458. if (onLoad) {
  30459. onLoad();
  30460. }
  30461. if (!_this.isBlocking && scene) {
  30462. scene.resetCachedMaterial();
  30463. }
  30464. };
  30465. if (!_this.url) {
  30466. _this._delayedOnLoad = load;
  30467. _this._delayedOnError = onError;
  30468. return _this;
  30469. }
  30470. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30471. if (!_this._texture) {
  30472. if (!scene.useDelayedTextureLoading) {
  30473. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30474. if (deleteBuffer) {
  30475. delete _this._buffer;
  30476. }
  30477. }
  30478. else {
  30479. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30480. _this._delayedOnLoad = load;
  30481. _this._delayedOnError = onError;
  30482. }
  30483. }
  30484. else {
  30485. if (_this._texture.isReady) {
  30486. BABYLON.Tools.SetImmediate(function () { return load(); });
  30487. }
  30488. else {
  30489. _this._texture.onLoadedObservable.add(load);
  30490. }
  30491. }
  30492. return _this;
  30493. }
  30494. Object.defineProperty(Texture.prototype, "noMipmap", {
  30495. get: function () {
  30496. return this._noMipmap;
  30497. },
  30498. enumerable: true,
  30499. configurable: true
  30500. });
  30501. Object.defineProperty(Texture.prototype, "isBlocking", {
  30502. get: function () {
  30503. return this._isBlocking;
  30504. },
  30505. set: function (value) {
  30506. this._isBlocking = value;
  30507. },
  30508. enumerable: true,
  30509. configurable: true
  30510. });
  30511. Object.defineProperty(Texture.prototype, "samplingMode", {
  30512. get: function () {
  30513. return this._samplingMode;
  30514. },
  30515. enumerable: true,
  30516. configurable: true
  30517. });
  30518. /**
  30519. * Update the url (and optional buffer) of this texture if url was null during construction.
  30520. * @param url the url of the texture
  30521. * @param buffer the buffer of the texture (defaults to null)
  30522. */
  30523. Texture.prototype.updateURL = function (url, buffer) {
  30524. if (buffer === void 0) { buffer = null; }
  30525. if (this.url) {
  30526. throw new Error("URL is already set");
  30527. }
  30528. this.url = url;
  30529. this._buffer = buffer;
  30530. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30531. this.delayLoad();
  30532. };
  30533. Texture.prototype.delayLoad = function () {
  30534. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30535. return;
  30536. }
  30537. var scene = this.getScene();
  30538. if (!scene) {
  30539. return;
  30540. }
  30541. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30542. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30543. if (!this._texture) {
  30544. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30545. if (this._deleteBuffer) {
  30546. delete this._buffer;
  30547. }
  30548. }
  30549. else {
  30550. if (this._delayedOnLoad) {
  30551. if (this._texture.isReady) {
  30552. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30553. }
  30554. else {
  30555. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30556. }
  30557. }
  30558. }
  30559. this._delayedOnLoad = null;
  30560. this._delayedOnError = null;
  30561. };
  30562. /**
  30563. * Default is Trilinear mode.
  30564. *
  30565. * | Value | Type | Description |
  30566. * | ----- | ------------------ | ----------- |
  30567. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30568. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30569. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30570. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30571. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30572. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30573. * | 7 | NEAREST_LINEAR | |
  30574. * | 8 | NEAREST_NEAREST | |
  30575. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30576. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30577. * | 11 | LINEAR_LINEAR | |
  30578. * | 12 | LINEAR_NEAREST | |
  30579. *
  30580. * > _mag_: magnification filter (close to the viewer)
  30581. * > _min_: minification filter (far from the viewer)
  30582. * > _mip_: filter used between mip map levels
  30583. *
  30584. */
  30585. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30586. if (!this._texture) {
  30587. return;
  30588. }
  30589. var scene = this.getScene();
  30590. if (!scene) {
  30591. return;
  30592. }
  30593. this._samplingMode = samplingMode;
  30594. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30595. };
  30596. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30597. x *= this.uScale;
  30598. y *= this.vScale;
  30599. x -= this.uRotationCenter * this.uScale;
  30600. y -= this.vRotationCenter * this.vScale;
  30601. z -= this.wRotationCenter;
  30602. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30603. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30604. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30605. t.z += this.wRotationCenter;
  30606. };
  30607. Texture.prototype.getTextureMatrix = function () {
  30608. var _this = this;
  30609. if (this.uOffset === this._cachedUOffset &&
  30610. this.vOffset === this._cachedVOffset &&
  30611. this.uScale === this._cachedUScale &&
  30612. this.vScale === this._cachedVScale &&
  30613. this.uAng === this._cachedUAng &&
  30614. this.vAng === this._cachedVAng &&
  30615. this.wAng === this._cachedWAng) {
  30616. return this._cachedTextureMatrix;
  30617. }
  30618. this._cachedUOffset = this.uOffset;
  30619. this._cachedVOffset = this.vOffset;
  30620. this._cachedUScale = this.uScale;
  30621. this._cachedVScale = this.vScale;
  30622. this._cachedUAng = this.uAng;
  30623. this._cachedVAng = this.vAng;
  30624. this._cachedWAng = this.wAng;
  30625. if (!this._cachedTextureMatrix) {
  30626. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30627. this._rowGenerationMatrix = new BABYLON.Matrix();
  30628. this._t0 = BABYLON.Vector3.Zero();
  30629. this._t1 = BABYLON.Vector3.Zero();
  30630. this._t2 = BABYLON.Vector3.Zero();
  30631. }
  30632. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30633. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30634. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30635. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30636. this._t1.subtractInPlace(this._t0);
  30637. this._t2.subtractInPlace(this._t0);
  30638. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30639. this._cachedTextureMatrix.m[0] = this._t1.x;
  30640. this._cachedTextureMatrix.m[1] = this._t1.y;
  30641. this._cachedTextureMatrix.m[2] = this._t1.z;
  30642. this._cachedTextureMatrix.m[4] = this._t2.x;
  30643. this._cachedTextureMatrix.m[5] = this._t2.y;
  30644. this._cachedTextureMatrix.m[6] = this._t2.z;
  30645. this._cachedTextureMatrix.m[8] = this._t0.x;
  30646. this._cachedTextureMatrix.m[9] = this._t0.y;
  30647. this._cachedTextureMatrix.m[10] = this._t0.z;
  30648. var scene = this.getScene();
  30649. if (!scene) {
  30650. return this._cachedTextureMatrix;
  30651. }
  30652. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30653. return mat.hasTexture(_this);
  30654. });
  30655. return this._cachedTextureMatrix;
  30656. };
  30657. Texture.prototype.getReflectionTextureMatrix = function () {
  30658. var _this = this;
  30659. var scene = this.getScene();
  30660. if (!scene) {
  30661. return this._cachedTextureMatrix;
  30662. }
  30663. if (this.uOffset === this._cachedUOffset &&
  30664. this.vOffset === this._cachedVOffset &&
  30665. this.uScale === this._cachedUScale &&
  30666. this.vScale === this._cachedVScale &&
  30667. this.coordinatesMode === this._cachedCoordinatesMode) {
  30668. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30669. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30670. return this._cachedTextureMatrix;
  30671. }
  30672. }
  30673. else {
  30674. return this._cachedTextureMatrix;
  30675. }
  30676. }
  30677. if (!this._cachedTextureMatrix) {
  30678. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30679. }
  30680. if (!this._projectionModeMatrix) {
  30681. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30682. }
  30683. this._cachedUOffset = this.uOffset;
  30684. this._cachedVOffset = this.vOffset;
  30685. this._cachedUScale = this.uScale;
  30686. this._cachedVScale = this.vScale;
  30687. this._cachedCoordinatesMode = this.coordinatesMode;
  30688. switch (this.coordinatesMode) {
  30689. case Texture.PLANAR_MODE:
  30690. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30691. this._cachedTextureMatrix[0] = this.uScale;
  30692. this._cachedTextureMatrix[5] = this.vScale;
  30693. this._cachedTextureMatrix[12] = this.uOffset;
  30694. this._cachedTextureMatrix[13] = this.vOffset;
  30695. break;
  30696. case Texture.PROJECTION_MODE:
  30697. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30698. this._projectionModeMatrix.m[0] = 0.5;
  30699. this._projectionModeMatrix.m[5] = -0.5;
  30700. this._projectionModeMatrix.m[10] = 0.0;
  30701. this._projectionModeMatrix.m[12] = 0.5;
  30702. this._projectionModeMatrix.m[13] = 0.5;
  30703. this._projectionModeMatrix.m[14] = 1.0;
  30704. this._projectionModeMatrix.m[15] = 1.0;
  30705. var projectionMatrix = scene.getProjectionMatrix();
  30706. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30707. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30708. break;
  30709. default:
  30710. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30711. break;
  30712. }
  30713. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30714. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30715. });
  30716. return this._cachedTextureMatrix;
  30717. };
  30718. Texture.prototype.clone = function () {
  30719. var _this = this;
  30720. return BABYLON.SerializationHelper.Clone(function () {
  30721. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30722. }, this);
  30723. };
  30724. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30725. get: function () {
  30726. if (!this._onLoadObservable) {
  30727. this._onLoadObservable = new BABYLON.Observable();
  30728. }
  30729. return this._onLoadObservable;
  30730. },
  30731. enumerable: true,
  30732. configurable: true
  30733. });
  30734. Texture.prototype.serialize = function () {
  30735. var serializationObject = _super.prototype.serialize.call(this);
  30736. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30737. serializationObject.base64String = this._buffer;
  30738. serializationObject.name = serializationObject.name.replace("data:", "");
  30739. }
  30740. serializationObject.invertY = this._invertY;
  30741. serializationObject.samplingMode = this.samplingMode;
  30742. return serializationObject;
  30743. };
  30744. Texture.prototype.getClassName = function () {
  30745. return "Texture";
  30746. };
  30747. Texture.prototype.dispose = function () {
  30748. _super.prototype.dispose.call(this);
  30749. if (this._onLoadObservable) {
  30750. this._onLoadObservable.clear();
  30751. this._onLoadObservable = null;
  30752. }
  30753. this._delayedOnLoad = null;
  30754. this._delayedOnError = null;
  30755. };
  30756. // Statics
  30757. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30758. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30759. if (onLoad === void 0) { onLoad = null; }
  30760. if (onError === void 0) { onError = null; }
  30761. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30762. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30763. };
  30764. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30765. if (parsedTexture.customType) {
  30766. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30767. // Update Sampling Mode
  30768. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30769. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30770. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30771. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30772. }
  30773. }
  30774. return parsedCustomTexture;
  30775. }
  30776. if (parsedTexture.isCube) {
  30777. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30778. }
  30779. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30780. return null;
  30781. }
  30782. var texture = BABYLON.SerializationHelper.Parse(function () {
  30783. var generateMipMaps = true;
  30784. if (parsedTexture.noMipmap) {
  30785. generateMipMaps = false;
  30786. }
  30787. if (parsedTexture.mirrorPlane) {
  30788. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30789. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30790. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30791. return mirrorTexture;
  30792. }
  30793. else if (parsedTexture.isRenderTarget) {
  30794. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30795. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30796. return renderTargetTexture;
  30797. }
  30798. else {
  30799. var texture;
  30800. if (parsedTexture.base64String) {
  30801. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30802. }
  30803. else {
  30804. var url = rootUrl + parsedTexture.name;
  30805. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30806. url = parsedTexture.url;
  30807. }
  30808. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30809. }
  30810. return texture;
  30811. }
  30812. }, parsedTexture, scene);
  30813. // Update Sampling Mode
  30814. if (parsedTexture.samplingMode) {
  30815. var sampling = parsedTexture.samplingMode;
  30816. if (texture._samplingMode !== sampling) {
  30817. texture.updateSamplingMode(sampling);
  30818. }
  30819. }
  30820. // Animations
  30821. if (parsedTexture.animations) {
  30822. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30823. var parsedAnimation = parsedTexture.animations[animationIndex];
  30824. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30825. }
  30826. }
  30827. return texture;
  30828. };
  30829. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30830. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30831. if (noMipmap === void 0) { noMipmap = false; }
  30832. if (invertY === void 0) { invertY = true; }
  30833. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30834. if (onLoad === void 0) { onLoad = null; }
  30835. if (onError === void 0) { onError = null; }
  30836. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30837. if (name.substr(0, 5) !== "data:") {
  30838. name = "data:" + name;
  30839. }
  30840. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30841. };
  30842. // Constants
  30843. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30844. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30845. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30846. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30847. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30848. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30849. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30850. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30851. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30852. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30853. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30854. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30855. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30856. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30857. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30858. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30859. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30860. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30861. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30862. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30863. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30864. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30865. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30866. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30867. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30868. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30869. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30870. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30871. /**
  30872. * 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
  30873. */
  30874. Texture.UseSerializedUrlIfAny = false;
  30875. __decorate([
  30876. BABYLON.serialize()
  30877. ], Texture.prototype, "url", void 0);
  30878. __decorate([
  30879. BABYLON.serialize()
  30880. ], Texture.prototype, "uOffset", void 0);
  30881. __decorate([
  30882. BABYLON.serialize()
  30883. ], Texture.prototype, "vOffset", void 0);
  30884. __decorate([
  30885. BABYLON.serialize()
  30886. ], Texture.prototype, "uScale", void 0);
  30887. __decorate([
  30888. BABYLON.serialize()
  30889. ], Texture.prototype, "vScale", void 0);
  30890. __decorate([
  30891. BABYLON.serialize()
  30892. ], Texture.prototype, "uAng", void 0);
  30893. __decorate([
  30894. BABYLON.serialize()
  30895. ], Texture.prototype, "vAng", void 0);
  30896. __decorate([
  30897. BABYLON.serialize()
  30898. ], Texture.prototype, "wAng", void 0);
  30899. __decorate([
  30900. BABYLON.serialize()
  30901. ], Texture.prototype, "uRotationCenter", void 0);
  30902. __decorate([
  30903. BABYLON.serialize()
  30904. ], Texture.prototype, "vRotationCenter", void 0);
  30905. __decorate([
  30906. BABYLON.serialize()
  30907. ], Texture.prototype, "wRotationCenter", void 0);
  30908. __decorate([
  30909. BABYLON.serialize()
  30910. ], Texture.prototype, "isBlocking", null);
  30911. return Texture;
  30912. }(BABYLON.BaseTexture));
  30913. BABYLON.Texture = Texture;
  30914. })(BABYLON || (BABYLON = {}));
  30915. //# sourceMappingURL=babylon.texture.js.map
  30916. var BABYLON;
  30917. (function (BABYLON) {
  30918. /**
  30919. * @hidden
  30920. **/
  30921. var _InstancesBatch = /** @class */ (function () {
  30922. function _InstancesBatch() {
  30923. this.mustReturn = false;
  30924. this.visibleInstances = new Array();
  30925. this.renderSelf = new Array();
  30926. }
  30927. return _InstancesBatch;
  30928. }());
  30929. BABYLON._InstancesBatch = _InstancesBatch;
  30930. /**
  30931. * Class used to represent renderable models
  30932. */
  30933. var Mesh = /** @class */ (function (_super) {
  30934. __extends(Mesh, _super);
  30935. /**
  30936. * @constructor
  30937. * @param name The value used by scene.getMeshByName() to do a lookup.
  30938. * @param scene The scene to add this mesh to.
  30939. * @param parent The parent of this mesh, if it has one
  30940. * @param source An optional Mesh from which geometry is shared, cloned.
  30941. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30942. * When false, achieved by calling a clone(), also passing False.
  30943. * This will make creation of children, recursive.
  30944. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30945. */
  30946. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30947. if (scene === void 0) { scene = null; }
  30948. if (parent === void 0) { parent = null; }
  30949. if (source === void 0) { source = null; }
  30950. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30951. var _this = _super.call(this, name, scene) || this;
  30952. // Members
  30953. /**
  30954. * Gets the delay loading state of the mesh (when delay loading is turned on)
  30955. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  30956. */
  30957. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30958. /**
  30959. * Gets the list of instances created from this mesh
  30960. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  30961. */
  30962. _this.instances = new Array();
  30963. _this._LODLevels = new Array();
  30964. /** @hidden */
  30965. _this._visibleInstances = {};
  30966. _this._renderIdForInstances = new Array();
  30967. _this._batchCache = new _InstancesBatch();
  30968. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30969. // Use by builder only to know what orientation were the mesh build in.
  30970. /** @hidden */
  30971. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  30972. /**
  30973. * Use this property to change the original side orientation defined at construction time
  30974. */
  30975. _this.overrideMaterialSideOrientation = null;
  30976. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30977. // Will be used to save a source mesh reference, If any
  30978. _this._source = null;
  30979. scene = _this.getScene();
  30980. if (source) {
  30981. // Geometry
  30982. if (source._geometry) {
  30983. source._geometry.applyToMesh(_this);
  30984. }
  30985. // Deep copy
  30986. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30987. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30988. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30989. ], ["_poseMatrix"]);
  30990. // Source mesh
  30991. _this._source = source;
  30992. // Construction Params
  30993. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30994. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30995. var myAnyThis = _this;
  30996. var myAnySource = source;
  30997. myAnyThis._closePath = myAnySource._closePath;
  30998. myAnyThis._idx = myAnySource._idx;
  30999. myAnyThis.dashSize = myAnySource.dashSize;
  31000. myAnyThis.gapSize = myAnySource.gapSize;
  31001. myAnyThis.path3D = myAnySource.path3D;
  31002. myAnyThis.pathArray = myAnySource.pathArray;
  31003. myAnyThis.arc = myAnySource.arc;
  31004. myAnyThis.radius = myAnySource.radius;
  31005. // Animation ranges
  31006. if (_this._source._ranges) {
  31007. var ranges = _this._source._ranges;
  31008. for (var name in ranges) {
  31009. if (!ranges.hasOwnProperty(name)) {
  31010. continue;
  31011. }
  31012. if (!ranges[name]) {
  31013. continue;
  31014. }
  31015. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31016. }
  31017. }
  31018. // Metadata
  31019. if (source.metadata && source.metadata.clone) {
  31020. _this.metadata = source.metadata.clone();
  31021. }
  31022. else {
  31023. _this.metadata = source.metadata;
  31024. }
  31025. // Tags
  31026. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31027. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31028. }
  31029. // Parent
  31030. _this.parent = source.parent;
  31031. // Pivot
  31032. _this.setPivotMatrix(source.getPivotMatrix());
  31033. _this.id = name + "." + source.id;
  31034. // Material
  31035. _this.material = source.material;
  31036. var index;
  31037. if (!doNotCloneChildren) {
  31038. // Children
  31039. var directDescendants = source.getDescendants(true);
  31040. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31041. var child = directDescendants[index_1];
  31042. if (child.clone) {
  31043. child.clone(name + "." + child.name, _this);
  31044. }
  31045. }
  31046. }
  31047. // Physics clone
  31048. var physicsEngine = _this.getScene().getPhysicsEngine();
  31049. if (clonePhysicsImpostor && physicsEngine) {
  31050. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31051. if (impostor) {
  31052. _this.physicsImpostor = impostor.clone(_this);
  31053. }
  31054. }
  31055. // Particles
  31056. for (index = 0; index < scene.particleSystems.length; index++) {
  31057. var system = scene.particleSystems[index];
  31058. if (system.emitter === source) {
  31059. system.clone(system.name, _this);
  31060. }
  31061. }
  31062. _this.refreshBoundingInfo();
  31063. _this.computeWorldMatrix(true);
  31064. }
  31065. // Parent
  31066. if (parent !== null) {
  31067. _this.parent = parent;
  31068. }
  31069. return _this;
  31070. }
  31071. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31072. /**
  31073. * An event triggered before rendering the mesh
  31074. */
  31075. get: function () {
  31076. if (!this._onBeforeRenderObservable) {
  31077. this._onBeforeRenderObservable = new BABYLON.Observable();
  31078. }
  31079. return this._onBeforeRenderObservable;
  31080. },
  31081. enumerable: true,
  31082. configurable: true
  31083. });
  31084. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31085. /**
  31086. * An event triggered after rendering the mesh
  31087. */
  31088. get: function () {
  31089. if (!this._onAfterRenderObservable) {
  31090. this._onAfterRenderObservable = new BABYLON.Observable();
  31091. }
  31092. return this._onAfterRenderObservable;
  31093. },
  31094. enumerable: true,
  31095. configurable: true
  31096. });
  31097. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31098. /**
  31099. * An event triggered before drawing the mesh
  31100. */
  31101. get: function () {
  31102. if (!this._onBeforeDrawObservable) {
  31103. this._onBeforeDrawObservable = new BABYLON.Observable();
  31104. }
  31105. return this._onBeforeDrawObservable;
  31106. },
  31107. enumerable: true,
  31108. configurable: true
  31109. });
  31110. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31111. /**
  31112. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  31113. */
  31114. set: function (callback) {
  31115. if (this._onBeforeDrawObserver) {
  31116. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31117. }
  31118. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31119. },
  31120. enumerable: true,
  31121. configurable: true
  31122. });
  31123. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31124. /**
  31125. * Gets or sets the morph target manager
  31126. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31127. */
  31128. get: function () {
  31129. return this._morphTargetManager;
  31130. },
  31131. set: function (value) {
  31132. if (this._morphTargetManager === value) {
  31133. return;
  31134. }
  31135. this._morphTargetManager = value;
  31136. this._syncGeometryWithMorphTargetManager();
  31137. },
  31138. enumerable: true,
  31139. configurable: true
  31140. });
  31141. Object.defineProperty(Mesh.prototype, "source", {
  31142. /**
  31143. * Gets the source mesh (the one used to clone this one from)
  31144. */
  31145. get: function () {
  31146. return this._source;
  31147. },
  31148. enumerable: true,
  31149. configurable: true
  31150. });
  31151. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31152. /**
  31153. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31154. */
  31155. get: function () {
  31156. return this._unIndexed;
  31157. },
  31158. set: function (value) {
  31159. if (this._unIndexed !== value) {
  31160. this._unIndexed = value;
  31161. this._markSubMeshesAsAttributesDirty();
  31162. }
  31163. },
  31164. enumerable: true,
  31165. configurable: true
  31166. });
  31167. // Methods
  31168. /**
  31169. * Gets the class name
  31170. * @returns the string "Mesh".
  31171. */
  31172. Mesh.prototype.getClassName = function () {
  31173. return "Mesh";
  31174. };
  31175. /**
  31176. * Returns a description of this mesh
  31177. * @param fullDetails define if full details about this mesh must be used
  31178. * @returns a descriptive string representing this mesh
  31179. */
  31180. Mesh.prototype.toString = function (fullDetails) {
  31181. var ret = _super.prototype.toString.call(this, fullDetails);
  31182. ret += ", n vertices: " + this.getTotalVertices();
  31183. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31184. if (this.animations) {
  31185. for (var i = 0; i < this.animations.length; i++) {
  31186. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31187. }
  31188. }
  31189. if (fullDetails) {
  31190. if (this._geometry) {
  31191. var ib = this.getIndices();
  31192. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31193. if (vb && ib) {
  31194. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31195. }
  31196. }
  31197. else {
  31198. ret += ", flat shading: UNKNOWN";
  31199. }
  31200. }
  31201. return ret;
  31202. };
  31203. /** @hidden */
  31204. Mesh.prototype._unBindEffect = function () {
  31205. _super.prototype._unBindEffect.call(this);
  31206. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31207. var instance = _a[_i];
  31208. instance._unBindEffect();
  31209. }
  31210. };
  31211. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31212. /**
  31213. * Gets a boolean indicating if this mesh has LOD
  31214. */
  31215. get: function () {
  31216. return this._LODLevels.length > 0;
  31217. },
  31218. enumerable: true,
  31219. configurable: true
  31220. });
  31221. /**
  31222. * Gets the list of MeshLODLevel associated with the current mesh
  31223. * @returns an array of MeshLODLevel
  31224. */
  31225. Mesh.prototype.getLODLevels = function () {
  31226. return this._LODLevels;
  31227. };
  31228. Mesh.prototype._sortLODLevels = function () {
  31229. this._LODLevels.sort(function (a, b) {
  31230. if (a.distance < b.distance) {
  31231. return 1;
  31232. }
  31233. if (a.distance > b.distance) {
  31234. return -1;
  31235. }
  31236. return 0;
  31237. });
  31238. };
  31239. /**
  31240. * Add a mesh as LOD level triggered at the given distance.
  31241. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31242. * @param distance The distance from the center of the object to show this level
  31243. * @param mesh The mesh to be added as LOD level (can be null)
  31244. * @return This mesh (for chaining)
  31245. */
  31246. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31247. if (mesh && mesh._masterMesh) {
  31248. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31249. return this;
  31250. }
  31251. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31252. this._LODLevels.push(level);
  31253. if (mesh) {
  31254. mesh._masterMesh = this;
  31255. }
  31256. this._sortLODLevels();
  31257. return this;
  31258. };
  31259. /**
  31260. * Returns the LOD level mesh at the passed distance or null if not found.
  31261. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31262. * @param distance The distance from the center of the object to show this level
  31263. * @returns a Mesh or `null`
  31264. */
  31265. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31266. for (var index = 0; index < this._LODLevels.length; index++) {
  31267. var level = this._LODLevels[index];
  31268. if (level.distance === distance) {
  31269. return level.mesh;
  31270. }
  31271. }
  31272. return null;
  31273. };
  31274. /**
  31275. * Remove a mesh from the LOD array
  31276. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31277. * @param mesh defines the mesh to be removed
  31278. * @return This mesh (for chaining)
  31279. */
  31280. Mesh.prototype.removeLODLevel = function (mesh) {
  31281. for (var index = 0; index < this._LODLevels.length; index++) {
  31282. if (this._LODLevels[index].mesh === mesh) {
  31283. this._LODLevels.splice(index, 1);
  31284. if (mesh) {
  31285. mesh._masterMesh = null;
  31286. }
  31287. }
  31288. }
  31289. this._sortLODLevels();
  31290. return this;
  31291. };
  31292. /**
  31293. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31294. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31295. * @param camera defines the camera to use to compute distance
  31296. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  31297. * @return This mesh (for chaining)
  31298. */
  31299. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31300. if (!this._LODLevels || this._LODLevels.length === 0) {
  31301. return this;
  31302. }
  31303. var bSphere;
  31304. if (boundingSphere) {
  31305. bSphere = boundingSphere;
  31306. }
  31307. else {
  31308. var boundingInfo = this.getBoundingInfo();
  31309. bSphere = boundingInfo.boundingSphere;
  31310. }
  31311. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31312. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31313. if (this.onLODLevelSelection) {
  31314. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31315. }
  31316. return this;
  31317. }
  31318. for (var index = 0; index < this._LODLevels.length; index++) {
  31319. var level = this._LODLevels[index];
  31320. if (level.distance < distanceToCamera) {
  31321. if (level.mesh) {
  31322. level.mesh._preActivate();
  31323. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31324. }
  31325. if (this.onLODLevelSelection) {
  31326. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31327. }
  31328. return level.mesh;
  31329. }
  31330. }
  31331. if (this.onLODLevelSelection) {
  31332. this.onLODLevelSelection(distanceToCamera, this, this);
  31333. }
  31334. return this;
  31335. };
  31336. Object.defineProperty(Mesh.prototype, "geometry", {
  31337. /**
  31338. * Gets the mesh internal Geometry object
  31339. */
  31340. get: function () {
  31341. return this._geometry;
  31342. },
  31343. enumerable: true,
  31344. configurable: true
  31345. });
  31346. /**
  31347. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31348. * @returns the total number of vertices
  31349. */
  31350. Mesh.prototype.getTotalVertices = function () {
  31351. if (this._geometry === null || this._geometry === undefined) {
  31352. return 0;
  31353. }
  31354. return this._geometry.getTotalVertices();
  31355. };
  31356. /**
  31357. * Returns the content of an associated vertex buffer
  31358. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31359. * - BABYLON.VertexBuffer.PositionKind
  31360. * - BABYLON.VertexBuffer.UVKind
  31361. * - BABYLON.VertexBuffer.UV2Kind
  31362. * - BABYLON.VertexBuffer.UV3Kind
  31363. * - BABYLON.VertexBuffer.UV4Kind
  31364. * - BABYLON.VertexBuffer.UV5Kind
  31365. * - BABYLON.VertexBuffer.UV6Kind
  31366. * - BABYLON.VertexBuffer.ColorKind
  31367. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31368. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31369. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31370. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31371. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  31372. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  31373. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  31374. */
  31375. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31376. if (!this._geometry) {
  31377. return null;
  31378. }
  31379. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31380. };
  31381. /**
  31382. * Returns the mesh VertexBuffer object from the requested `kind`
  31383. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31384. * - BABYLON.VertexBuffer.PositionKind
  31385. * - BABYLON.VertexBuffer.UVKind
  31386. * - BABYLON.VertexBuffer.UV2Kind
  31387. * - BABYLON.VertexBuffer.UV3Kind
  31388. * - BABYLON.VertexBuffer.UV4Kind
  31389. * - BABYLON.VertexBuffer.UV5Kind
  31390. * - BABYLON.VertexBuffer.UV6Kind
  31391. * - BABYLON.VertexBuffer.ColorKind
  31392. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31393. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31394. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31395. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31396. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  31397. */
  31398. Mesh.prototype.getVertexBuffer = function (kind) {
  31399. if (!this._geometry) {
  31400. return null;
  31401. }
  31402. return this._geometry.getVertexBuffer(kind);
  31403. };
  31404. /**
  31405. * Tests if a specific vertex buffer is associated with this mesh
  31406. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31407. * - BABYLON.VertexBuffer.PositionKind
  31408. * - BABYLON.VertexBuffer.UVKind
  31409. * - BABYLON.VertexBuffer.UV2Kind
  31410. * - BABYLON.VertexBuffer.UV3Kind
  31411. * - BABYLON.VertexBuffer.UV4Kind
  31412. * - BABYLON.VertexBuffer.UV5Kind
  31413. * - BABYLON.VertexBuffer.UV6Kind
  31414. * - BABYLON.VertexBuffer.ColorKind
  31415. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31416. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31417. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31418. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31419. * @returns a boolean
  31420. */
  31421. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31422. if (!this._geometry) {
  31423. if (this._delayInfo) {
  31424. return this._delayInfo.indexOf(kind) !== -1;
  31425. }
  31426. return false;
  31427. }
  31428. return this._geometry.isVerticesDataPresent(kind);
  31429. };
  31430. /**
  31431. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31432. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31433. * - BABYLON.VertexBuffer.PositionKind
  31434. * - BABYLON.VertexBuffer.UVKind
  31435. * - BABYLON.VertexBuffer.UV2Kind
  31436. * - BABYLON.VertexBuffer.UV3Kind
  31437. * - BABYLON.VertexBuffer.UV4Kind
  31438. * - BABYLON.VertexBuffer.UV5Kind
  31439. * - BABYLON.VertexBuffer.UV6Kind
  31440. * - BABYLON.VertexBuffer.ColorKind
  31441. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31442. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31443. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31444. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31445. * @returns a boolean
  31446. */
  31447. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31448. if (!this._geometry) {
  31449. if (this._delayInfo) {
  31450. return this._delayInfo.indexOf(kind) !== -1;
  31451. }
  31452. return false;
  31453. }
  31454. return this._geometry.isVertexBufferUpdatable(kind);
  31455. };
  31456. /**
  31457. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  31458. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31459. * - BABYLON.VertexBuffer.PositionKind
  31460. * - BABYLON.VertexBuffer.UVKind
  31461. * - BABYLON.VertexBuffer.UV2Kind
  31462. * - BABYLON.VertexBuffer.UV3Kind
  31463. * - BABYLON.VertexBuffer.UV4Kind
  31464. * - BABYLON.VertexBuffer.UV5Kind
  31465. * - BABYLON.VertexBuffer.UV6Kind
  31466. * - BABYLON.VertexBuffer.ColorKind
  31467. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31468. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31469. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31470. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31471. * @returns an array of strings
  31472. */
  31473. Mesh.prototype.getVerticesDataKinds = function () {
  31474. if (!this._geometry) {
  31475. var result = new Array();
  31476. if (this._delayInfo) {
  31477. this._delayInfo.forEach(function (kind, index, array) {
  31478. result.push(kind);
  31479. });
  31480. }
  31481. return result;
  31482. }
  31483. return this._geometry.getVerticesDataKinds();
  31484. };
  31485. /**
  31486. * Returns a positive integer : the total number of indices in this mesh geometry.
  31487. * @returns the numner of indices or zero if the mesh has no geometry.
  31488. */
  31489. Mesh.prototype.getTotalIndices = function () {
  31490. if (!this._geometry) {
  31491. return 0;
  31492. }
  31493. return this._geometry.getTotalIndices();
  31494. };
  31495. /**
  31496. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31497. * @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.
  31498. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31499. * @returns the indices array or an empty array if the mesh has no geometry
  31500. */
  31501. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31502. if (!this._geometry) {
  31503. return [];
  31504. }
  31505. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31506. };
  31507. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31508. get: function () {
  31509. return this._masterMesh !== null && this._masterMesh !== undefined;
  31510. },
  31511. enumerable: true,
  31512. configurable: true
  31513. });
  31514. /**
  31515. * Determine if the current mesh is ready to be rendered
  31516. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31517. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31518. * @returns true if all associated assets are ready (material, textures, shaders)
  31519. */
  31520. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31521. if (completeCheck === void 0) { completeCheck = false; }
  31522. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31523. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31524. return false;
  31525. }
  31526. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31527. return false;
  31528. }
  31529. if (!this.subMeshes || this.subMeshes.length === 0) {
  31530. return true;
  31531. }
  31532. if (!completeCheck) {
  31533. return true;
  31534. }
  31535. var engine = this.getEngine();
  31536. var scene = this.getScene();
  31537. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31538. this.computeWorldMatrix();
  31539. var mat = this.material || scene.defaultMaterial;
  31540. if (mat) {
  31541. if (mat.storeEffectOnSubMeshes) {
  31542. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31543. var subMesh = _a[_i];
  31544. var effectiveMaterial = subMesh.getMaterial();
  31545. if (effectiveMaterial) {
  31546. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31547. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31548. return false;
  31549. }
  31550. }
  31551. else {
  31552. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31553. return false;
  31554. }
  31555. }
  31556. }
  31557. }
  31558. }
  31559. else {
  31560. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31561. return false;
  31562. }
  31563. }
  31564. }
  31565. // Shadows
  31566. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31567. var light = _c[_b];
  31568. var generator = light.getShadowGenerator();
  31569. if (generator) {
  31570. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31571. var subMesh = _e[_d];
  31572. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31573. return false;
  31574. }
  31575. }
  31576. }
  31577. }
  31578. // LOD
  31579. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31580. var lod = _g[_f];
  31581. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31582. return false;
  31583. }
  31584. }
  31585. return true;
  31586. };
  31587. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31588. /**
  31589. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  31590. */
  31591. get: function () {
  31592. return this._areNormalsFrozen;
  31593. },
  31594. enumerable: true,
  31595. configurable: true
  31596. });
  31597. /**
  31598. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  31599. * @returns the current mesh
  31600. */
  31601. Mesh.prototype.freezeNormals = function () {
  31602. this._areNormalsFrozen = true;
  31603. return this;
  31604. };
  31605. /**
  31606. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  31607. * @returns the current mesh
  31608. */
  31609. Mesh.prototype.unfreezeNormals = function () {
  31610. this._areNormalsFrozen = false;
  31611. return this;
  31612. };
  31613. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31614. /**
  31615. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31616. */
  31617. set: function (count) {
  31618. this._overridenInstanceCount = count;
  31619. },
  31620. enumerable: true,
  31621. configurable: true
  31622. });
  31623. // Methods
  31624. /** @hidden */
  31625. Mesh.prototype._preActivate = function () {
  31626. var sceneRenderId = this.getScene().getRenderId();
  31627. if (this._preActivateId === sceneRenderId) {
  31628. return this;
  31629. }
  31630. this._preActivateId = sceneRenderId;
  31631. this._visibleInstances = null;
  31632. return this;
  31633. };
  31634. /** @hidden */
  31635. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31636. if (this._visibleInstances) {
  31637. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31638. }
  31639. return this;
  31640. };
  31641. /** @hidden */
  31642. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31643. if (!this._visibleInstances) {
  31644. this._visibleInstances = {};
  31645. this._visibleInstances.defaultRenderId = renderId;
  31646. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31647. }
  31648. if (!this._visibleInstances[renderId]) {
  31649. this._visibleInstances[renderId] = new Array();
  31650. }
  31651. this._visibleInstances[renderId].push(instance);
  31652. return this;
  31653. };
  31654. /**
  31655. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31656. * This means the mesh underlying bounding box and sphere are recomputed.
  31657. * @returns the current mesh
  31658. */
  31659. Mesh.prototype.refreshBoundingInfo = function () {
  31660. return this._refreshBoundingInfo(false);
  31661. };
  31662. /** @hidden */
  31663. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31664. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31665. return this;
  31666. }
  31667. var data = this._getPositionData(applySkeleton);
  31668. if (data) {
  31669. var bias = this.geometry ? this.geometry.boundingBias : null;
  31670. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31671. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31672. }
  31673. if (this.subMeshes) {
  31674. for (var index = 0; index < this.subMeshes.length; index++) {
  31675. this.subMeshes[index].refreshBoundingInfo();
  31676. }
  31677. }
  31678. this._updateBoundingInfo();
  31679. return this;
  31680. };
  31681. Mesh.prototype._getPositionData = function (applySkeleton) {
  31682. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31683. if (data && applySkeleton && this.skeleton) {
  31684. data = BABYLON.Tools.Slice(data);
  31685. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31686. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31687. if (matricesWeightsData && matricesIndicesData) {
  31688. var needExtras = this.numBoneInfluencers > 4;
  31689. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31690. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31691. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31692. var tempVector = BABYLON.Tmp.Vector3[0];
  31693. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31694. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31695. var matWeightIdx = 0;
  31696. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31697. finalMatrix.reset();
  31698. var inf;
  31699. var weight;
  31700. for (inf = 0; inf < 4; inf++) {
  31701. weight = matricesWeightsData[matWeightIdx + inf];
  31702. if (weight > 0) {
  31703. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31704. finalMatrix.addToSelf(tempMatrix);
  31705. }
  31706. }
  31707. if (needExtras) {
  31708. for (inf = 0; inf < 4; inf++) {
  31709. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31710. if (weight > 0) {
  31711. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31712. finalMatrix.addToSelf(tempMatrix);
  31713. }
  31714. }
  31715. }
  31716. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31717. tempVector.toArray(data, index);
  31718. }
  31719. }
  31720. }
  31721. return data;
  31722. };
  31723. /** @hidden */
  31724. Mesh.prototype._createGlobalSubMesh = function (force) {
  31725. var totalVertices = this.getTotalVertices();
  31726. if (!totalVertices || !this.getIndices()) {
  31727. return null;
  31728. }
  31729. // Check if we need to recreate the submeshes
  31730. if (this.subMeshes && this.subMeshes.length > 0) {
  31731. var ib = this.getIndices();
  31732. if (!ib) {
  31733. return null;
  31734. }
  31735. var totalIndices = ib.length;
  31736. var needToRecreate = false;
  31737. if (force) {
  31738. needToRecreate = true;
  31739. }
  31740. else {
  31741. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31742. var submesh = _a[_i];
  31743. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31744. needToRecreate = true;
  31745. break;
  31746. }
  31747. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31748. needToRecreate = true;
  31749. break;
  31750. }
  31751. }
  31752. }
  31753. if (!needToRecreate) {
  31754. return this.subMeshes[0];
  31755. }
  31756. }
  31757. this.releaseSubMeshes();
  31758. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31759. };
  31760. /**
  31761. * This function will subdivide the mesh into multiple submeshes
  31762. * @param count defines the expected number of submeshes
  31763. */
  31764. Mesh.prototype.subdivide = function (count) {
  31765. if (count < 1) {
  31766. return;
  31767. }
  31768. var totalIndices = this.getTotalIndices();
  31769. var subdivisionSize = (totalIndices / count) | 0;
  31770. var offset = 0;
  31771. // Ensure that subdivisionSize is a multiple of 3
  31772. while (subdivisionSize % 3 !== 0) {
  31773. subdivisionSize++;
  31774. }
  31775. this.releaseSubMeshes();
  31776. for (var index = 0; index < count; index++) {
  31777. if (offset >= totalIndices) {
  31778. break;
  31779. }
  31780. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31781. offset += subdivisionSize;
  31782. }
  31783. this.synchronizeInstances();
  31784. };
  31785. /**
  31786. * Copy a FloatArray into a specific associated vertex buffer
  31787. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31788. * - BABYLON.VertexBuffer.PositionKind
  31789. * - BABYLON.VertexBuffer.UVKind
  31790. * - BABYLON.VertexBuffer.UV2Kind
  31791. * - BABYLON.VertexBuffer.UV3Kind
  31792. * - BABYLON.VertexBuffer.UV4Kind
  31793. * - BABYLON.VertexBuffer.UV5Kind
  31794. * - BABYLON.VertexBuffer.UV6Kind
  31795. * - BABYLON.VertexBuffer.ColorKind
  31796. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31797. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31798. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31799. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31800. * @param data defines the data source
  31801. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31802. * @param stride defines the data stride size (can be null)
  31803. * @returns the current mesh
  31804. */
  31805. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31806. if (updatable === void 0) { updatable = false; }
  31807. if (!this._geometry) {
  31808. var vertexData = new BABYLON.VertexData();
  31809. vertexData.set(data, kind);
  31810. var scene = this.getScene();
  31811. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31812. }
  31813. else {
  31814. this._geometry.setVerticesData(kind, data, updatable, stride);
  31815. }
  31816. return this;
  31817. };
  31818. /**
  31819. * Flags an associated vertex buffer as updatable
  31820. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  31821. * - BABYLON.VertexBuffer.PositionKind
  31822. * - BABYLON.VertexBuffer.UVKind
  31823. * - BABYLON.VertexBuffer.UV2Kind
  31824. * - BABYLON.VertexBuffer.UV3Kind
  31825. * - BABYLON.VertexBuffer.UV4Kind
  31826. * - BABYLON.VertexBuffer.UV5Kind
  31827. * - BABYLON.VertexBuffer.UV6Kind
  31828. * - BABYLON.VertexBuffer.ColorKind
  31829. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31830. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31831. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31832. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31833. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31834. */
  31835. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31836. if (updatable === void 0) { updatable = true; }
  31837. var vb = this.getVertexBuffer(kind);
  31838. if (!vb || vb.isUpdatable() === updatable) {
  31839. return;
  31840. }
  31841. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31842. };
  31843. /**
  31844. * Sets the mesh global Vertex Buffer
  31845. * @param buffer defines the buffer to use
  31846. * @returns the current mesh
  31847. */
  31848. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31849. if (!this._geometry) {
  31850. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31851. }
  31852. this._geometry.setVerticesBuffer(buffer);
  31853. return this;
  31854. };
  31855. /**
  31856. * Update a specific associated vertex buffer
  31857. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31858. * - BABYLON.VertexBuffer.PositionKind
  31859. * - BABYLON.VertexBuffer.UVKind
  31860. * - BABYLON.VertexBuffer.UV2Kind
  31861. * - BABYLON.VertexBuffer.UV3Kind
  31862. * - BABYLON.VertexBuffer.UV4Kind
  31863. * - BABYLON.VertexBuffer.UV5Kind
  31864. * - BABYLON.VertexBuffer.UV6Kind
  31865. * - BABYLON.VertexBuffer.ColorKind
  31866. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31867. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31868. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31869. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31870. * @param data defines the data source
  31871. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  31872. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  31873. * @returns the current mesh
  31874. */
  31875. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31876. if (!this._geometry) {
  31877. return this;
  31878. }
  31879. if (!makeItUnique) {
  31880. this._geometry.updateVerticesData(kind, data, updateExtends);
  31881. }
  31882. else {
  31883. this.makeGeometryUnique();
  31884. this.updateVerticesData(kind, data, updateExtends, false);
  31885. }
  31886. return this;
  31887. };
  31888. /**
  31889. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31890. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31891. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  31892. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  31893. * @returns the current mesh
  31894. */
  31895. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31896. if (computeNormals === void 0) { computeNormals = true; }
  31897. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31898. if (!positions) {
  31899. return this;
  31900. }
  31901. positionFunction(positions);
  31902. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31903. if (computeNormals) {
  31904. var indices = this.getIndices();
  31905. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31906. if (!normals) {
  31907. return this;
  31908. }
  31909. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31910. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31911. }
  31912. return this;
  31913. };
  31914. /**
  31915. * Creates a un-shared specific occurence of the geometry for the mesh.
  31916. * @returns the current mesh
  31917. */
  31918. Mesh.prototype.makeGeometryUnique = function () {
  31919. if (!this._geometry) {
  31920. return this;
  31921. }
  31922. var oldGeometry = this._geometry;
  31923. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31924. oldGeometry.releaseForMesh(this, true);
  31925. geometry.applyToMesh(this);
  31926. return this;
  31927. };
  31928. /**
  31929. * Set the index buffer of this mesh
  31930. * @param indices defines the source data
  31931. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  31932. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  31933. * @returns the current mesh
  31934. */
  31935. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31936. if (totalVertices === void 0) { totalVertices = null; }
  31937. if (updatable === void 0) { updatable = false; }
  31938. if (!this._geometry) {
  31939. var vertexData = new BABYLON.VertexData();
  31940. vertexData.indices = indices;
  31941. var scene = this.getScene();
  31942. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31943. }
  31944. else {
  31945. this._geometry.setIndices(indices, totalVertices, updatable);
  31946. }
  31947. return this;
  31948. };
  31949. /**
  31950. * Update the current index buffer
  31951. * @param indices defines the source data
  31952. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  31953. * @returns the current mesh
  31954. */
  31955. Mesh.prototype.updateIndices = function (indices, offset) {
  31956. if (!this._geometry) {
  31957. return this;
  31958. }
  31959. this._geometry.updateIndices(indices, offset);
  31960. return this;
  31961. };
  31962. /**
  31963. * Invert the geometry to move from a right handed system to a left handed one.
  31964. * @returns the current mesh
  31965. */
  31966. Mesh.prototype.toLeftHanded = function () {
  31967. if (!this._geometry) {
  31968. return this;
  31969. }
  31970. this._geometry.toLeftHanded();
  31971. return this;
  31972. };
  31973. /** @hidden */
  31974. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31975. if (!this._geometry) {
  31976. return this;
  31977. }
  31978. var engine = this.getScene().getEngine();
  31979. // Wireframe
  31980. var indexToBind;
  31981. if (this._unIndexed) {
  31982. indexToBind = null;
  31983. }
  31984. else {
  31985. switch (fillMode) {
  31986. case BABYLON.Material.PointFillMode:
  31987. indexToBind = null;
  31988. break;
  31989. case BABYLON.Material.WireFrameFillMode:
  31990. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31991. break;
  31992. default:
  31993. case BABYLON.Material.TriangleFillMode:
  31994. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31995. break;
  31996. }
  31997. }
  31998. // VBOs
  31999. this._geometry._bind(effect, indexToBind);
  32000. return this;
  32001. };
  32002. /** @hidden */
  32003. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32004. if (alternate === void 0) { alternate = false; }
  32005. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32006. return this;
  32007. }
  32008. if (this._onBeforeDrawObservable) {
  32009. this._onBeforeDrawObservable.notifyObservers(this);
  32010. }
  32011. var scene = this.getScene();
  32012. var engine = scene.getEngine();
  32013. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32014. // or triangles as points
  32015. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32016. }
  32017. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32018. // Triangles as wireframe
  32019. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32020. }
  32021. else {
  32022. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32023. }
  32024. if (scene._isAlternateRenderingEnabled && !alternate) {
  32025. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32026. if (!effect || !scene.activeCamera) {
  32027. return this;
  32028. }
  32029. scene._switchToAlternateCameraConfiguration(true);
  32030. this._effectiveMaterial.bindView(effect);
  32031. this._effectiveMaterial.bindViewProjection(effect);
  32032. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32033. this._draw(subMesh, fillMode, instancesCount, true);
  32034. engine.setViewport(scene.activeCamera.viewport);
  32035. scene._switchToAlternateCameraConfiguration(false);
  32036. this._effectiveMaterial.bindView(effect);
  32037. this._effectiveMaterial.bindViewProjection(effect);
  32038. }
  32039. return this;
  32040. };
  32041. /**
  32042. * Registers for this mesh a javascript function called just before the rendering process
  32043. * @param func defines the function to call before rendering this mesh
  32044. * @returns the current mesh
  32045. */
  32046. Mesh.prototype.registerBeforeRender = function (func) {
  32047. this.onBeforeRenderObservable.add(func);
  32048. return this;
  32049. };
  32050. /**
  32051. * Disposes a previously registered javascript function called before the rendering
  32052. * @param func defines the function to remove
  32053. * @returns the current mesh
  32054. */
  32055. Mesh.prototype.unregisterBeforeRender = function (func) {
  32056. this.onBeforeRenderObservable.removeCallback(func);
  32057. return this;
  32058. };
  32059. /**
  32060. * Registers for this mesh a javascript function called just after the rendering is complete
  32061. * @param func defines the function to call after rendering this mesh
  32062. * @returns the current mesh
  32063. */
  32064. Mesh.prototype.registerAfterRender = function (func) {
  32065. this.onAfterRenderObservable.add(func);
  32066. return this;
  32067. };
  32068. /**
  32069. * Disposes a previously registered javascript function called after the rendering.
  32070. * @param func defines the function to remove
  32071. * @returns the current mesh
  32072. */
  32073. Mesh.prototype.unregisterAfterRender = function (func) {
  32074. this.onAfterRenderObservable.removeCallback(func);
  32075. return this;
  32076. };
  32077. /** @hidden */
  32078. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32079. var scene = this.getScene();
  32080. this._batchCache.mustReturn = false;
  32081. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32082. this._batchCache.visibleInstances[subMeshId] = null;
  32083. if (this._visibleInstances) {
  32084. var currentRenderId = scene.getRenderId();
  32085. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32086. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32087. var selfRenderId = this._renderId;
  32088. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32089. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32090. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32091. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32092. }
  32093. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32094. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32095. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32096. this._batchCache.mustReturn = true;
  32097. return this._batchCache;
  32098. }
  32099. if (currentRenderId !== selfRenderId) {
  32100. this._batchCache.renderSelf[subMeshId] = false;
  32101. }
  32102. }
  32103. this._renderIdForInstances[subMeshId] = currentRenderId;
  32104. }
  32105. return this._batchCache;
  32106. };
  32107. /** @hidden */
  32108. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32109. var visibleInstances = batch.visibleInstances[subMesh._id];
  32110. if (!visibleInstances) {
  32111. return this;
  32112. }
  32113. var matricesCount = visibleInstances.length + 1;
  32114. var bufferSize = matricesCount * 16 * 4;
  32115. var currentInstancesBufferSize = this._instancesBufferSize;
  32116. var instancesBuffer = this._instancesBuffer;
  32117. while (this._instancesBufferSize < bufferSize) {
  32118. this._instancesBufferSize *= 2;
  32119. }
  32120. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32121. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32122. }
  32123. var offset = 0;
  32124. var instancesCount = 0;
  32125. var world = this.getWorldMatrix();
  32126. if (batch.renderSelf[subMesh._id]) {
  32127. world.copyToArray(this._instancesData, offset);
  32128. offset += 16;
  32129. instancesCount++;
  32130. }
  32131. if (visibleInstances) {
  32132. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32133. var instance = visibleInstances[instanceIndex];
  32134. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32135. offset += 16;
  32136. instancesCount++;
  32137. }
  32138. }
  32139. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32140. if (instancesBuffer) {
  32141. instancesBuffer.dispose();
  32142. }
  32143. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32144. this._instancesBuffer = instancesBuffer;
  32145. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32146. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32147. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32148. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32149. }
  32150. else {
  32151. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32152. }
  32153. this._bind(subMesh, effect, fillMode);
  32154. this._draw(subMesh, fillMode, instancesCount);
  32155. engine.unbindInstanceAttributes();
  32156. return this;
  32157. };
  32158. /** @hidden */
  32159. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32160. var scene = this.getScene();
  32161. var engine = scene.getEngine();
  32162. if (hardwareInstancedRendering) {
  32163. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32164. }
  32165. else {
  32166. if (batch.renderSelf[subMesh._id]) {
  32167. // Draw
  32168. if (onBeforeDraw) {
  32169. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32170. }
  32171. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32172. }
  32173. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32174. if (visibleInstancesForSubMesh) {
  32175. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32176. var instance = visibleInstancesForSubMesh[instanceIndex];
  32177. // World
  32178. var world = instance.getWorldMatrix();
  32179. if (onBeforeDraw) {
  32180. onBeforeDraw(true, world, effectiveMaterial);
  32181. }
  32182. // Draw
  32183. this._draw(subMesh, fillMode);
  32184. }
  32185. }
  32186. }
  32187. return this;
  32188. };
  32189. /**
  32190. * 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
  32191. * @param subMesh defines the subMesh to render
  32192. * @param enableAlphaMode defines if alpha mode can be changed
  32193. * @returns the current mesh
  32194. */
  32195. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32196. this._checkOcclusionQuery();
  32197. if (this._isOccluded) {
  32198. return this;
  32199. }
  32200. var scene = this.getScene();
  32201. // Managing instances
  32202. var batch = this._getInstancesRenderList(subMesh._id);
  32203. if (batch.mustReturn) {
  32204. return this;
  32205. }
  32206. // Checking geometry state
  32207. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32208. return this;
  32209. }
  32210. if (this._onBeforeRenderObservable) {
  32211. this._onBeforeRenderObservable.notifyObservers(this);
  32212. }
  32213. var engine = scene.getEngine();
  32214. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32215. // Material
  32216. var material = subMesh.getMaterial();
  32217. if (!material) {
  32218. return this;
  32219. }
  32220. this._effectiveMaterial = material;
  32221. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32222. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32223. return this;
  32224. }
  32225. }
  32226. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32227. return this;
  32228. }
  32229. // Alpha mode
  32230. if (enableAlphaMode) {
  32231. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32232. }
  32233. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32234. var step = _a[_i];
  32235. step.action(this, subMesh, batch);
  32236. }
  32237. var effect;
  32238. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32239. effect = subMesh.effect;
  32240. }
  32241. else {
  32242. effect = this._effectiveMaterial.getEffect();
  32243. }
  32244. if (!effect) {
  32245. return this;
  32246. }
  32247. var sideOrientation = this.overrideMaterialSideOrientation;
  32248. if (sideOrientation == null) {
  32249. sideOrientation = this._effectiveMaterial.sideOrientation;
  32250. if (this._getWorldMatrixDeterminant() < 0) {
  32251. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32252. }
  32253. }
  32254. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32255. if (this._effectiveMaterial.forceDepthWrite) {
  32256. engine.setDepthWrite(true);
  32257. }
  32258. // Bind
  32259. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32260. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32261. this._bind(subMesh, effect, fillMode);
  32262. }
  32263. var world = this.getWorldMatrix();
  32264. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32265. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32266. }
  32267. else {
  32268. this._effectiveMaterial.bind(world, this);
  32269. }
  32270. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32271. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32272. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32273. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32274. }
  32275. // Draw
  32276. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32277. // Unbind
  32278. this._effectiveMaterial.unbind();
  32279. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32280. var step = _c[_b];
  32281. step.action(this, subMesh, batch);
  32282. }
  32283. if (this._onAfterRenderObservable) {
  32284. this._onAfterRenderObservable.notifyObservers(this);
  32285. }
  32286. return this;
  32287. };
  32288. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32289. if (isInstance && effectiveMaterial) {
  32290. effectiveMaterial.bindOnlyWorldMatrix(world);
  32291. }
  32292. };
  32293. /**
  32294. * Normalize matrix weights so that all vertices have a total weight set to 1
  32295. */
  32296. Mesh.prototype.cleanMatrixWeights = function () {
  32297. var epsilon = 1e-3;
  32298. var noInfluenceBoneIndex = 0.0;
  32299. if (this.skeleton) {
  32300. noInfluenceBoneIndex = this.skeleton.bones.length;
  32301. }
  32302. else {
  32303. return;
  32304. }
  32305. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32306. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32307. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32308. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32309. var influencers = this.numBoneInfluencers;
  32310. var size = matricesWeights.length;
  32311. for (var i = 0; i < size; i += 4) {
  32312. var weight = 0.0;
  32313. var firstZeroWeight = -1;
  32314. for (var j = 0; j < 4; j++) {
  32315. var w = matricesWeights[i + j];
  32316. weight += w;
  32317. if (w < epsilon && firstZeroWeight < 0) {
  32318. firstZeroWeight = j;
  32319. }
  32320. }
  32321. if (matricesWeightsExtra) {
  32322. for (var j = 0; j < 4; j++) {
  32323. var w = matricesWeightsExtra[i + j];
  32324. weight += w;
  32325. if (w < epsilon && firstZeroWeight < 0) {
  32326. firstZeroWeight = j + 4;
  32327. }
  32328. }
  32329. }
  32330. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32331. firstZeroWeight = influencers - 1;
  32332. }
  32333. if (weight > epsilon) {
  32334. var mweight = 1.0 / weight;
  32335. for (var j = 0; j < 4; j++) {
  32336. matricesWeights[i + j] *= mweight;
  32337. }
  32338. if (matricesWeightsExtra) {
  32339. for (var j = 0; j < 4; j++) {
  32340. matricesWeightsExtra[i + j] *= mweight;
  32341. }
  32342. }
  32343. }
  32344. else {
  32345. if (firstZeroWeight >= 4) {
  32346. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32347. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32348. }
  32349. else {
  32350. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32351. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32352. }
  32353. }
  32354. }
  32355. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32356. if (matricesIndicesExtra) {
  32357. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32358. }
  32359. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32360. if (matricesWeightsExtra) {
  32361. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32362. }
  32363. };
  32364. /** @hidden */
  32365. Mesh.prototype._checkDelayState = function () {
  32366. var scene = this.getScene();
  32367. if (this._geometry) {
  32368. this._geometry.load(scene);
  32369. }
  32370. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32371. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32372. this._queueLoad(scene);
  32373. }
  32374. return this;
  32375. };
  32376. Mesh.prototype._queueLoad = function (scene) {
  32377. var _this = this;
  32378. scene._addPendingData(this);
  32379. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32380. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32381. if (data instanceof ArrayBuffer) {
  32382. _this._delayLoadingFunction(data, _this);
  32383. }
  32384. else {
  32385. _this._delayLoadingFunction(JSON.parse(data), _this);
  32386. }
  32387. _this.instances.forEach(function (instance) {
  32388. instance._syncSubMeshes();
  32389. });
  32390. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32391. scene._removePendingData(_this);
  32392. }, function () { }, scene.database, getBinaryData);
  32393. return this;
  32394. };
  32395. /**
  32396. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32397. * A mesh is in the frustum if its bounding box intersects the frustum
  32398. * @param frustumPlanes defines the frustum to test
  32399. * @returns true if the mesh is in the frustum planes
  32400. */
  32401. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32402. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32403. return false;
  32404. }
  32405. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32406. return false;
  32407. }
  32408. this._checkDelayState();
  32409. return true;
  32410. };
  32411. /**
  32412. * Sets the mesh material by the material or multiMaterial `id` property
  32413. * @param id is a string identifying the material or the multiMaterial
  32414. * @returns the current mesh
  32415. */
  32416. Mesh.prototype.setMaterialByID = function (id) {
  32417. var materials = this.getScene().materials;
  32418. var index;
  32419. for (index = materials.length - 1; index > -1; index--) {
  32420. if (materials[index].id === id) {
  32421. this.material = materials[index];
  32422. return this;
  32423. }
  32424. }
  32425. // Multi
  32426. var multiMaterials = this.getScene().multiMaterials;
  32427. for (index = multiMaterials.length - 1; index > -1; index--) {
  32428. if (multiMaterials[index].id === id) {
  32429. this.material = multiMaterials[index];
  32430. return this;
  32431. }
  32432. }
  32433. return this;
  32434. };
  32435. /**
  32436. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32437. * @returns an array of IAnimatable
  32438. */
  32439. Mesh.prototype.getAnimatables = function () {
  32440. var results = new Array();
  32441. if (this.material) {
  32442. results.push(this.material);
  32443. }
  32444. if (this.skeleton) {
  32445. results.push(this.skeleton);
  32446. }
  32447. return results;
  32448. };
  32449. /**
  32450. * Modifies the mesh geometry according to the passed transformation matrix.
  32451. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32452. * The mesh normals are modified using the same transformation.
  32453. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32454. * @param transform defines the transform matrix to use
  32455. * @see http://doc.babylonjs.com/resources/baking_transformations
  32456. * @returns the current mesh
  32457. */
  32458. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32459. // Position
  32460. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32461. return this;
  32462. }
  32463. var submeshes = this.subMeshes.splice(0);
  32464. this._resetPointsArrayCache();
  32465. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32466. var temp = new Array();
  32467. var index;
  32468. for (index = 0; index < data.length; index += 3) {
  32469. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32470. }
  32471. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32472. // Normals
  32473. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32474. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32475. temp = [];
  32476. for (index = 0; index < data.length; index += 3) {
  32477. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32478. }
  32479. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32480. }
  32481. // flip faces?
  32482. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32483. this.flipFaces();
  32484. }
  32485. // Restore submeshes
  32486. this.releaseSubMeshes();
  32487. this.subMeshes = submeshes;
  32488. return this;
  32489. };
  32490. /**
  32491. * Modifies the mesh geometry according to its own current World Matrix.
  32492. * The mesh World Matrix is then reset.
  32493. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32494. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32495. * @see http://doc.babylonjs.com/resources/baking_transformations
  32496. * @returns the current mesh
  32497. */
  32498. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32499. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32500. this.scaling.copyFromFloats(1, 1, 1);
  32501. this.position.copyFromFloats(0, 0, 0);
  32502. this.rotation.copyFromFloats(0, 0, 0);
  32503. //only if quaternion is already set
  32504. if (this.rotationQuaternion) {
  32505. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32506. }
  32507. this._worldMatrix = BABYLON.Matrix.Identity();
  32508. return this;
  32509. };
  32510. Object.defineProperty(Mesh.prototype, "_positions", {
  32511. // Cache
  32512. /** @hidden */
  32513. get: function () {
  32514. if (this._geometry) {
  32515. return this._geometry._positions;
  32516. }
  32517. return null;
  32518. },
  32519. enumerable: true,
  32520. configurable: true
  32521. });
  32522. /** @hidden */
  32523. Mesh.prototype._resetPointsArrayCache = function () {
  32524. if (this._geometry) {
  32525. this._geometry._resetPointsArrayCache();
  32526. }
  32527. return this;
  32528. };
  32529. /** @hidden */
  32530. Mesh.prototype._generatePointsArray = function () {
  32531. if (this._geometry) {
  32532. return this._geometry._generatePointsArray();
  32533. }
  32534. return false;
  32535. };
  32536. /**
  32537. * Returns a new Mesh object generated from the current mesh properties.
  32538. * This method must not get confused with createInstance()
  32539. * @param name is a string, the name given to the new mesh
  32540. * @param newParent can be any Node object (default `null`)
  32541. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  32542. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  32543. * @returns a new mesh
  32544. */
  32545. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32546. if (name === void 0) { name = ""; }
  32547. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32548. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32549. };
  32550. /**
  32551. * Releases resources associated with this mesh.
  32552. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32553. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32554. */
  32555. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32556. var _this = this;
  32557. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32558. this.morphTargetManager = null;
  32559. if (this._geometry) {
  32560. this._geometry.releaseForMesh(this, true);
  32561. }
  32562. if (this._onBeforeDrawObservable) {
  32563. this._onBeforeDrawObservable.clear();
  32564. }
  32565. if (this._onBeforeRenderObservable) {
  32566. this._onBeforeRenderObservable.clear();
  32567. }
  32568. if (this._onAfterRenderObservable) {
  32569. this._onAfterRenderObservable.clear();
  32570. }
  32571. // Sources
  32572. var meshes = this.getScene().meshes;
  32573. meshes.forEach(function (abstractMesh) {
  32574. var mesh = abstractMesh;
  32575. if (mesh._source && mesh._source === _this) {
  32576. mesh._source = null;
  32577. }
  32578. });
  32579. this._source = null;
  32580. // Instances
  32581. if (this._instancesBuffer) {
  32582. this._instancesBuffer.dispose();
  32583. this._instancesBuffer = null;
  32584. }
  32585. while (this.instances.length) {
  32586. this.instances[0].dispose();
  32587. }
  32588. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32589. };
  32590. /**
  32591. * Modifies the mesh geometry according to a displacement map.
  32592. * 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.
  32593. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32594. * @param url is a string, the URL from the image file is to be downloaded.
  32595. * @param minHeight is the lower limit of the displacement.
  32596. * @param maxHeight is the upper limit of the displacement.
  32597. * @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.
  32598. * @param uvOffset is an optional vector2 used to offset UV.
  32599. * @param uvScale is an optional vector2 used to scale UV.
  32600. * @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.
  32601. * @returns the Mesh.
  32602. */
  32603. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32604. var _this = this;
  32605. if (forceUpdate === void 0) { forceUpdate = false; }
  32606. var scene = this.getScene();
  32607. var onload = function (img) {
  32608. // Getting height map data
  32609. var canvas = document.createElement("canvas");
  32610. var context = canvas.getContext("2d");
  32611. var heightMapWidth = img.width;
  32612. var heightMapHeight = img.height;
  32613. canvas.width = heightMapWidth;
  32614. canvas.height = heightMapHeight;
  32615. context.drawImage(img, 0, 0);
  32616. // Create VertexData from map data
  32617. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32618. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32619. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32620. //execute success callback, if set
  32621. if (onSuccess) {
  32622. onSuccess(_this);
  32623. }
  32624. };
  32625. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32626. return this;
  32627. };
  32628. /**
  32629. * Modifies the mesh geometry according to a displacementMap buffer.
  32630. * 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.
  32631. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32632. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32633. * @param heightMapWidth is the width of the buffer image.
  32634. * @param heightMapHeight is the height of the buffer image.
  32635. * @param minHeight is the lower limit of the displacement.
  32636. * @param maxHeight is the upper limit of the displacement.
  32637. * @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.
  32638. * @param uvOffset is an optional vector2 used to offset UV.
  32639. * @param uvScale is an optional vector2 used to scale UV.
  32640. * @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.
  32641. * @returns the Mesh.
  32642. */
  32643. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32644. if (forceUpdate === void 0) { forceUpdate = false; }
  32645. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32646. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32647. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32648. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32649. return this;
  32650. }
  32651. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32652. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32653. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32654. var position = BABYLON.Vector3.Zero();
  32655. var normal = BABYLON.Vector3.Zero();
  32656. var uv = BABYLON.Vector2.Zero();
  32657. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32658. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32659. for (var index = 0; index < positions.length; index += 3) {
  32660. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32661. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32662. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32663. // Compute height
  32664. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32665. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32666. var pos = (u + v * heightMapWidth) * 4;
  32667. var r = buffer[pos] / 255.0;
  32668. var g = buffer[pos + 1] / 255.0;
  32669. var b = buffer[pos + 2] / 255.0;
  32670. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32671. normal.normalize();
  32672. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32673. position = position.add(normal);
  32674. position.toArray(positions, index);
  32675. }
  32676. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32677. if (forceUpdate) {
  32678. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32679. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32680. }
  32681. else {
  32682. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32683. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32684. }
  32685. return this;
  32686. };
  32687. /**
  32688. * Modify the mesh to get a flat shading rendering.
  32689. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32690. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32691. * @returns current mesh
  32692. */
  32693. Mesh.prototype.convertToFlatShadedMesh = function () {
  32694. var kinds = this.getVerticesDataKinds();
  32695. var vbs = {};
  32696. var data = {};
  32697. var newdata = {};
  32698. var updatableNormals = false;
  32699. var kindIndex;
  32700. var kind;
  32701. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32702. kind = kinds[kindIndex];
  32703. var vertexBuffer = this.getVertexBuffer(kind);
  32704. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32705. updatableNormals = vertexBuffer.isUpdatable();
  32706. kinds.splice(kindIndex, 1);
  32707. kindIndex--;
  32708. continue;
  32709. }
  32710. vbs[kind] = vertexBuffer;
  32711. data[kind] = vbs[kind].getData();
  32712. newdata[kind] = [];
  32713. }
  32714. // Save previous submeshes
  32715. var previousSubmeshes = this.subMeshes.slice(0);
  32716. var indices = this.getIndices();
  32717. var totalIndices = this.getTotalIndices();
  32718. // Generating unique vertices per face
  32719. var index;
  32720. for (index = 0; index < totalIndices; index++) {
  32721. var vertexIndex = indices[index];
  32722. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32723. kind = kinds[kindIndex];
  32724. var stride = vbs[kind].getStrideSize();
  32725. for (var offset = 0; offset < stride; offset++) {
  32726. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32727. }
  32728. }
  32729. }
  32730. // Updating faces & normal
  32731. var normals = [];
  32732. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32733. for (index = 0; index < totalIndices; index += 3) {
  32734. indices[index] = index;
  32735. indices[index + 1] = index + 1;
  32736. indices[index + 2] = index + 2;
  32737. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32738. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32739. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32740. var p1p2 = p1.subtract(p2);
  32741. var p3p2 = p3.subtract(p2);
  32742. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32743. // Store same normals for every vertex
  32744. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32745. normals.push(normal.x);
  32746. normals.push(normal.y);
  32747. normals.push(normal.z);
  32748. }
  32749. }
  32750. this.setIndices(indices);
  32751. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32752. // Updating vertex buffers
  32753. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32754. kind = kinds[kindIndex];
  32755. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32756. }
  32757. // Updating submeshes
  32758. this.releaseSubMeshes();
  32759. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32760. var previousOne = previousSubmeshes[submeshIndex];
  32761. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32762. }
  32763. this.synchronizeInstances();
  32764. return this;
  32765. };
  32766. /**
  32767. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32768. * In other words, more vertices, no more indices and a single bigger VBO.
  32769. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32770. * @returns current mesh
  32771. */
  32772. Mesh.prototype.convertToUnIndexedMesh = function () {
  32773. var kinds = this.getVerticesDataKinds();
  32774. var vbs = {};
  32775. var data = {};
  32776. var newdata = {};
  32777. var kindIndex;
  32778. var kind;
  32779. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32780. kind = kinds[kindIndex];
  32781. var vertexBuffer = this.getVertexBuffer(kind);
  32782. vbs[kind] = vertexBuffer;
  32783. data[kind] = vbs[kind].getData();
  32784. newdata[kind] = [];
  32785. }
  32786. // Save previous submeshes
  32787. var previousSubmeshes = this.subMeshes.slice(0);
  32788. var indices = this.getIndices();
  32789. var totalIndices = this.getTotalIndices();
  32790. // Generating unique vertices per face
  32791. var index;
  32792. for (index = 0; index < totalIndices; index++) {
  32793. var vertexIndex = indices[index];
  32794. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32795. kind = kinds[kindIndex];
  32796. var stride = vbs[kind].getStrideSize();
  32797. for (var offset = 0; offset < stride; offset++) {
  32798. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32799. }
  32800. }
  32801. }
  32802. // Updating indices
  32803. for (index = 0; index < totalIndices; index += 3) {
  32804. indices[index] = index;
  32805. indices[index + 1] = index + 1;
  32806. indices[index + 2] = index + 2;
  32807. }
  32808. this.setIndices(indices);
  32809. // Updating vertex buffers
  32810. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32811. kind = kinds[kindIndex];
  32812. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32813. }
  32814. // Updating submeshes
  32815. this.releaseSubMeshes();
  32816. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32817. var previousOne = previousSubmeshes[submeshIndex];
  32818. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32819. }
  32820. this._unIndexed = true;
  32821. this.synchronizeInstances();
  32822. return this;
  32823. };
  32824. /**
  32825. * Inverses facet orientations.
  32826. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32827. * @param flipNormals will also inverts the normals
  32828. * @returns current mesh
  32829. */
  32830. Mesh.prototype.flipFaces = function (flipNormals) {
  32831. if (flipNormals === void 0) { flipNormals = false; }
  32832. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32833. var i;
  32834. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32835. for (i = 0; i < vertex_data.normals.length; i++) {
  32836. vertex_data.normals[i] *= -1;
  32837. }
  32838. }
  32839. if (vertex_data.indices) {
  32840. var temp;
  32841. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32842. // reassign indices
  32843. temp = vertex_data.indices[i + 1];
  32844. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32845. vertex_data.indices[i + 2] = temp;
  32846. }
  32847. }
  32848. vertex_data.applyToMesh(this);
  32849. return this;
  32850. };
  32851. // Instances
  32852. /**
  32853. * Creates a new InstancedMesh object from the mesh model.
  32854. * Warning : this method is not supported for Line mesh and LineSystem
  32855. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32856. * @param name defines the name of the new instance
  32857. * @returns a new InstancedMesh
  32858. */
  32859. Mesh.prototype.createInstance = function (name) {
  32860. return new BABYLON.InstancedMesh(name, this);
  32861. };
  32862. /**
  32863. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32864. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32865. * @returns the current mesh
  32866. */
  32867. Mesh.prototype.synchronizeInstances = function () {
  32868. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32869. var instance = this.instances[instanceIndex];
  32870. instance._syncSubMeshes();
  32871. }
  32872. return this;
  32873. };
  32874. /**
  32875. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32876. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32877. * This should be used together with the simplification to avoid disappearing triangles.
  32878. * @param successCallback an optional success callback to be called after the optimization finished.
  32879. * @returns the current mesh
  32880. */
  32881. Mesh.prototype.optimizeIndices = function (successCallback) {
  32882. var _this = this;
  32883. var indices = this.getIndices();
  32884. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32885. if (!positions || !indices) {
  32886. return this;
  32887. }
  32888. var vectorPositions = new Array();
  32889. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32890. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32891. }
  32892. var dupes = new Array();
  32893. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32894. var realPos = vectorPositions.length - 1 - iteration;
  32895. var testedPosition = vectorPositions[realPos];
  32896. for (var j = 0; j < realPos; ++j) {
  32897. var againstPosition = vectorPositions[j];
  32898. if (testedPosition.equals(againstPosition)) {
  32899. dupes[realPos] = j;
  32900. break;
  32901. }
  32902. }
  32903. }, function () {
  32904. for (var i = 0; i < indices.length; ++i) {
  32905. indices[i] = dupes[indices[i]] || indices[i];
  32906. }
  32907. //indices are now reordered
  32908. var originalSubMeshes = _this.subMeshes.slice(0);
  32909. _this.setIndices(indices);
  32910. _this.subMeshes = originalSubMeshes;
  32911. if (successCallback) {
  32912. successCallback(_this);
  32913. }
  32914. });
  32915. return this;
  32916. };
  32917. /**
  32918. * Serialize current mesh
  32919. * @param serializationObject defines the object which will receive the serialization data
  32920. */
  32921. Mesh.prototype.serialize = function (serializationObject) {
  32922. serializationObject.name = this.name;
  32923. serializationObject.id = this.id;
  32924. serializationObject.type = this.getClassName();
  32925. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32926. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32927. }
  32928. serializationObject.position = this.position.asArray();
  32929. if (this.rotationQuaternion) {
  32930. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32931. }
  32932. else if (this.rotation) {
  32933. serializationObject.rotation = this.rotation.asArray();
  32934. }
  32935. serializationObject.scaling = this.scaling.asArray();
  32936. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32937. serializationObject.isEnabled = this.isEnabled(false);
  32938. serializationObject.isVisible = this.isVisible;
  32939. serializationObject.infiniteDistance = this.infiniteDistance;
  32940. serializationObject.pickable = this.isPickable;
  32941. serializationObject.receiveShadows = this.receiveShadows;
  32942. serializationObject.billboardMode = this.billboardMode;
  32943. serializationObject.visibility = this.visibility;
  32944. serializationObject.checkCollisions = this.checkCollisions;
  32945. serializationObject.isBlocker = this.isBlocker;
  32946. // Parent
  32947. if (this.parent) {
  32948. serializationObject.parentId = this.parent.id;
  32949. }
  32950. // Geometry
  32951. serializationObject.isUnIndexed = this.isUnIndexed;
  32952. var geometry = this._geometry;
  32953. if (geometry) {
  32954. var geometryId = geometry.id;
  32955. serializationObject.geometryId = geometryId;
  32956. // SubMeshes
  32957. serializationObject.subMeshes = [];
  32958. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32959. var subMesh = this.subMeshes[subIndex];
  32960. serializationObject.subMeshes.push({
  32961. materialIndex: subMesh.materialIndex,
  32962. verticesStart: subMesh.verticesStart,
  32963. verticesCount: subMesh.verticesCount,
  32964. indexStart: subMesh.indexStart,
  32965. indexCount: subMesh.indexCount
  32966. });
  32967. }
  32968. }
  32969. // Material
  32970. if (this.material) {
  32971. serializationObject.materialId = this.material.id;
  32972. }
  32973. else {
  32974. this.material = null;
  32975. }
  32976. // Morph targets
  32977. if (this.morphTargetManager) {
  32978. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32979. }
  32980. // Skeleton
  32981. if (this.skeleton) {
  32982. serializationObject.skeletonId = this.skeleton.id;
  32983. }
  32984. // Physics
  32985. //TODO implement correct serialization for physics impostors.
  32986. var impostor = this.getPhysicsImpostor();
  32987. if (impostor) {
  32988. serializationObject.physicsMass = impostor.getParam("mass");
  32989. serializationObject.physicsFriction = impostor.getParam("friction");
  32990. serializationObject.physicsRestitution = impostor.getParam("mass");
  32991. serializationObject.physicsImpostor = impostor.type;
  32992. }
  32993. // Metadata
  32994. if (this.metadata) {
  32995. serializationObject.metadata = this.metadata;
  32996. }
  32997. // Instances
  32998. serializationObject.instances = [];
  32999. for (var index = 0; index < this.instances.length; index++) {
  33000. var instance = this.instances[index];
  33001. if (instance.doNotSerialize) {
  33002. continue;
  33003. }
  33004. var serializationInstance = {
  33005. name: instance.name,
  33006. id: instance.id,
  33007. position: instance.position.asArray(),
  33008. scaling: instance.scaling.asArray()
  33009. };
  33010. if (instance.parent) {
  33011. serializationInstance.parentId = instance.parent.id;
  33012. }
  33013. if (instance.rotationQuaternion) {
  33014. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33015. }
  33016. else if (instance.rotation) {
  33017. serializationInstance.rotation = instance.rotation.asArray();
  33018. }
  33019. serializationObject.instances.push(serializationInstance);
  33020. // Animations
  33021. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33022. serializationInstance.ranges = instance.serializeAnimationRanges();
  33023. }
  33024. //
  33025. // Animations
  33026. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33027. serializationObject.ranges = this.serializeAnimationRanges();
  33028. // Layer mask
  33029. serializationObject.layerMask = this.layerMask;
  33030. // Alpha
  33031. serializationObject.alphaIndex = this.alphaIndex;
  33032. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33033. // Overlay
  33034. serializationObject.overlayAlpha = this.overlayAlpha;
  33035. serializationObject.overlayColor = this.overlayColor.asArray();
  33036. serializationObject.renderOverlay = this.renderOverlay;
  33037. // Fog
  33038. serializationObject.applyFog = this.applyFog;
  33039. // Action Manager
  33040. if (this.actionManager) {
  33041. serializationObject.actions = this.actionManager.serialize(this.name);
  33042. }
  33043. };
  33044. /** @hidden */
  33045. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33046. if (!this.geometry) {
  33047. return;
  33048. }
  33049. this._markSubMeshesAsAttributesDirty();
  33050. var morphTargetManager = this._morphTargetManager;
  33051. if (morphTargetManager && morphTargetManager.vertexCount) {
  33052. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33053. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33054. this.morphTargetManager = null;
  33055. return;
  33056. }
  33057. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33058. var morphTarget = morphTargetManager.getActiveTarget(index);
  33059. var positions = morphTarget.getPositions();
  33060. if (!positions) {
  33061. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33062. return;
  33063. }
  33064. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33065. var normals = morphTarget.getNormals();
  33066. if (normals) {
  33067. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33068. }
  33069. var tangents = morphTarget.getTangents();
  33070. if (tangents) {
  33071. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33072. }
  33073. }
  33074. }
  33075. else {
  33076. var index = 0;
  33077. // Positions
  33078. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33079. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33080. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33081. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33082. }
  33083. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33084. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33085. }
  33086. index++;
  33087. }
  33088. }
  33089. };
  33090. // Statics
  33091. /**
  33092. * Returns a new Mesh object parsed from the source provided.
  33093. * @param parsedMesh is the source
  33094. * @param scene defines the hosting scene
  33095. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  33096. * @returns a new Mesh
  33097. */
  33098. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33099. var mesh;
  33100. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33101. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33102. }
  33103. else {
  33104. mesh = new Mesh(parsedMesh.name, scene);
  33105. }
  33106. mesh.id = parsedMesh.id;
  33107. if (BABYLON.Tags) {
  33108. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33109. }
  33110. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33111. if (parsedMesh.metadata !== undefined) {
  33112. mesh.metadata = parsedMesh.metadata;
  33113. }
  33114. if (parsedMesh.rotationQuaternion) {
  33115. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33116. }
  33117. else if (parsedMesh.rotation) {
  33118. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33119. }
  33120. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33121. if (parsedMesh.localMatrix) {
  33122. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33123. }
  33124. else if (parsedMesh.pivotMatrix) {
  33125. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33126. }
  33127. mesh.setEnabled(parsedMesh.isEnabled);
  33128. mesh.isVisible = parsedMesh.isVisible;
  33129. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33130. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33131. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33132. if (parsedMesh.applyFog !== undefined) {
  33133. mesh.applyFog = parsedMesh.applyFog;
  33134. }
  33135. if (parsedMesh.pickable !== undefined) {
  33136. mesh.isPickable = parsedMesh.pickable;
  33137. }
  33138. if (parsedMesh.alphaIndex !== undefined) {
  33139. mesh.alphaIndex = parsedMesh.alphaIndex;
  33140. }
  33141. mesh.receiveShadows = parsedMesh.receiveShadows;
  33142. mesh.billboardMode = parsedMesh.billboardMode;
  33143. if (parsedMesh.visibility !== undefined) {
  33144. mesh.visibility = parsedMesh.visibility;
  33145. }
  33146. mesh.checkCollisions = parsedMesh.checkCollisions;
  33147. if (parsedMesh.isBlocker !== undefined) {
  33148. mesh.isBlocker = parsedMesh.isBlocker;
  33149. }
  33150. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33151. // freezeWorldMatrix
  33152. if (parsedMesh.freezeWorldMatrix) {
  33153. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33154. }
  33155. // Parent
  33156. if (parsedMesh.parentId) {
  33157. mesh._waitingParentId = parsedMesh.parentId;
  33158. }
  33159. // Actions
  33160. if (parsedMesh.actions !== undefined) {
  33161. mesh._waitingActions = parsedMesh.actions;
  33162. }
  33163. // Overlay
  33164. if (parsedMesh.overlayAlpha !== undefined) {
  33165. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33166. }
  33167. if (parsedMesh.overlayColor !== undefined) {
  33168. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33169. }
  33170. if (parsedMesh.renderOverlay !== undefined) {
  33171. mesh.renderOverlay = parsedMesh.renderOverlay;
  33172. }
  33173. // Geometry
  33174. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33175. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33176. if (parsedMesh.delayLoadingFile) {
  33177. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33178. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33179. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33180. if (parsedMesh._binaryInfo) {
  33181. mesh._binaryInfo = parsedMesh._binaryInfo;
  33182. }
  33183. mesh._delayInfo = [];
  33184. if (parsedMesh.hasUVs) {
  33185. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33186. }
  33187. if (parsedMesh.hasUVs2) {
  33188. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33189. }
  33190. if (parsedMesh.hasUVs3) {
  33191. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33192. }
  33193. if (parsedMesh.hasUVs4) {
  33194. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33195. }
  33196. if (parsedMesh.hasUVs5) {
  33197. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33198. }
  33199. if (parsedMesh.hasUVs6) {
  33200. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33201. }
  33202. if (parsedMesh.hasColors) {
  33203. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33204. }
  33205. if (parsedMesh.hasMatricesIndices) {
  33206. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33207. }
  33208. if (parsedMesh.hasMatricesWeights) {
  33209. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33210. }
  33211. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33212. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33213. mesh._checkDelayState();
  33214. }
  33215. }
  33216. else {
  33217. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33218. }
  33219. // Material
  33220. if (parsedMesh.materialId) {
  33221. mesh.setMaterialByID(parsedMesh.materialId);
  33222. }
  33223. else {
  33224. mesh.material = null;
  33225. }
  33226. // Morph targets
  33227. if (parsedMesh.morphTargetManagerId > -1) {
  33228. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33229. }
  33230. // Skeleton
  33231. if (parsedMesh.skeletonId > -1) {
  33232. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33233. if (parsedMesh.numBoneInfluencers) {
  33234. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33235. }
  33236. }
  33237. // Animations
  33238. if (parsedMesh.animations) {
  33239. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33240. var parsedAnimation = parsedMesh.animations[animationIndex];
  33241. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33242. }
  33243. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33244. }
  33245. if (parsedMesh.autoAnimate) {
  33246. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33247. }
  33248. // Layer Mask
  33249. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33250. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33251. }
  33252. else {
  33253. mesh.layerMask = 0x0FFFFFFF;
  33254. }
  33255. // Physics
  33256. if (parsedMesh.physicsImpostor) {
  33257. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33258. mass: parsedMesh.physicsMass,
  33259. friction: parsedMesh.physicsFriction,
  33260. restitution: parsedMesh.physicsRestitution
  33261. }, scene);
  33262. }
  33263. // Instances
  33264. if (parsedMesh.instances) {
  33265. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33266. var parsedInstance = parsedMesh.instances[index];
  33267. var instance = mesh.createInstance(parsedInstance.name);
  33268. if (parsedInstance.id) {
  33269. instance.id = parsedInstance.id;
  33270. }
  33271. if (BABYLON.Tags) {
  33272. if (parsedInstance.tags) {
  33273. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33274. }
  33275. else {
  33276. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33277. }
  33278. }
  33279. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33280. if (parsedInstance.parentId) {
  33281. instance._waitingParentId = parsedInstance.parentId;
  33282. }
  33283. if (parsedInstance.rotationQuaternion) {
  33284. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33285. }
  33286. else if (parsedInstance.rotation) {
  33287. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33288. }
  33289. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33290. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  33291. instance.checkCollisions = parsedInstance.checkCollisions;
  33292. }
  33293. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  33294. instance.isPickable = parsedInstance.pickable;
  33295. }
  33296. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  33297. instance.showBoundingBox = parsedInstance.showBoundingBox;
  33298. }
  33299. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33300. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  33301. }
  33302. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33303. instance.alphaIndex = parsedInstance.alphaIndex;
  33304. }
  33305. // Physics
  33306. if (parsedInstance.physicsImpostor) {
  33307. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  33308. mass: parsedInstance.physicsMass,
  33309. friction: parsedInstance.physicsFriction,
  33310. restitution: parsedInstance.physicsRestitution
  33311. }, scene);
  33312. }
  33313. // Animation
  33314. if (parsedInstance.animations) {
  33315. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  33316. parsedAnimation = parsedInstance.animations[animationIndex];
  33317. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33318. }
  33319. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  33320. if (parsedInstance.autoAnimate) {
  33321. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  33322. }
  33323. }
  33324. }
  33325. }
  33326. return mesh;
  33327. };
  33328. /**
  33329. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  33330. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33331. * @param name defines the name of the mesh to create
  33332. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33333. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  33334. * @param closePath creates a seam between the first and the last points of each path of the path array
  33335. * @param offset is taken in account only if the `pathArray` is containing a single path
  33336. * @param scene defines the hosting scene
  33337. * @param updatable defines if the mesh must be flagged as updatable
  33338. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33339. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  33340. * @returns a new Mesh
  33341. */
  33342. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33343. if (closeArray === void 0) { closeArray = false; }
  33344. if (updatable === void 0) { updatable = false; }
  33345. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33346. pathArray: pathArray,
  33347. closeArray: closeArray,
  33348. closePath: closePath,
  33349. offset: offset,
  33350. updatable: updatable,
  33351. sideOrientation: sideOrientation,
  33352. instance: instance
  33353. }, scene);
  33354. };
  33355. /**
  33356. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  33357. * @param name defines the name of the mesh to create
  33358. * @param radius sets the radius size (float) of the polygon (default 0.5)
  33359. * @param tessellation sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
  33360. * @param scene defines the hosting scene
  33361. * @param updatable defines if the mesh must be flagged as updatable
  33362. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33363. * @returns a new Mesh
  33364. */
  33365. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33366. if (scene === void 0) { scene = null; }
  33367. var options = {
  33368. radius: radius,
  33369. tessellation: tessellation,
  33370. sideOrientation: sideOrientation,
  33371. updatable: updatable
  33372. };
  33373. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33374. };
  33375. /**
  33376. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  33377. * @param name defines the name of the mesh to create
  33378. * @param size sets the size (float) of each box side (default 1)
  33379. * @param scene defines the hosting scene
  33380. * @param updatable defines if the mesh must be flagged as updatable
  33381. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33382. * @returns a new Mesh
  33383. */
  33384. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33385. if (scene === void 0) { scene = null; }
  33386. var options = {
  33387. size: size,
  33388. sideOrientation: sideOrientation,
  33389. updatable: updatable
  33390. };
  33391. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33392. };
  33393. /**
  33394. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  33395. * @param name defines the name of the mesh to create
  33396. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  33397. * @param diameter sets the diameter size (float) of the sphere (default 1)
  33398. * @param scene defines the hosting scene
  33399. * @param updatable defines if the mesh must be flagged as updatable
  33400. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33401. * @returns a new Mesh
  33402. */
  33403. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33404. var options = {
  33405. segments: segments,
  33406. diameterX: diameter,
  33407. diameterY: diameter,
  33408. diameterZ: diameter,
  33409. sideOrientation: sideOrientation,
  33410. updatable: updatable
  33411. };
  33412. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33413. };
  33414. /**
  33415. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  33416. * @param name defines the name of the mesh to create
  33417. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  33418. * @param diameterTop set the top cap diameter (floats, default 1)
  33419. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  33420. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  33421. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  33422. * @param scene defines the hosting scene
  33423. * @param updatable defines if the mesh must be flagged as updatable
  33424. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33425. * @returns a new Mesh
  33426. */
  33427. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33428. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33429. if (scene !== undefined) {
  33430. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33431. updatable = scene;
  33432. }
  33433. scene = subdivisions;
  33434. subdivisions = 1;
  33435. }
  33436. var options = {
  33437. height: height,
  33438. diameterTop: diameterTop,
  33439. diameterBottom: diameterBottom,
  33440. tessellation: tessellation,
  33441. subdivisions: subdivisions,
  33442. sideOrientation: sideOrientation,
  33443. updatable: updatable
  33444. };
  33445. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33446. };
  33447. // Torus (Code from SharpDX.org)
  33448. /**
  33449. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  33450. * @param name defines the name of the mesh to create
  33451. * @param diameter sets the diameter size (float) of the torus (default 1)
  33452. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  33453. * @param tessellation sets the number of torus sides (postive integer, default 16)
  33454. * @param scene defines the hosting scene
  33455. * @param updatable defines if the mesh must be flagged as updatable
  33456. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33457. * @returns a new Mesh
  33458. */
  33459. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33460. var options = {
  33461. diameter: diameter,
  33462. thickness: thickness,
  33463. tessellation: tessellation,
  33464. sideOrientation: sideOrientation,
  33465. updatable: updatable
  33466. };
  33467. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33468. };
  33469. /**
  33470. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  33471. * @param name defines the name of the mesh to create
  33472. * @param radius sets the global radius size (float) of the torus knot (default 2)
  33473. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  33474. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  33475. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  33476. * @param p the number of windings on X axis (positive integers, default 2)
  33477. * @param q the number of windings on Y axis (positive integers, default 3)
  33478. * @param scene defines the hosting scene
  33479. * @param updatable defines if the mesh must be flagged as updatable
  33480. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33481. * @returns a new Mesh
  33482. */
  33483. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33484. var options = {
  33485. radius: radius,
  33486. tube: tube,
  33487. radialSegments: radialSegments,
  33488. tubularSegments: tubularSegments,
  33489. p: p,
  33490. q: q,
  33491. sideOrientation: sideOrientation,
  33492. updatable: updatable
  33493. };
  33494. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33495. };
  33496. /**
  33497. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  33498. * @param name defines the name of the mesh to create
  33499. * @param points is an array successive Vector3
  33500. * @param scene defines the hosting scene
  33501. * @param updatable defines if the mesh must be flagged as updatable
  33502. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  33503. * @returns a new Mesh
  33504. */
  33505. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33506. if (scene === void 0) { scene = null; }
  33507. if (updatable === void 0) { updatable = false; }
  33508. if (instance === void 0) { instance = null; }
  33509. var options = {
  33510. points: points,
  33511. updatable: updatable,
  33512. instance: instance
  33513. };
  33514. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33515. };
  33516. /**
  33517. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  33518. * @param name defines the name of the mesh to create
  33519. * @param points is an array successive Vector3
  33520. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  33521. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  33522. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  33523. * @param scene defines the hosting scene
  33524. * @param updatable defines if the mesh must be flagged as updatable
  33525. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  33526. * @returns a new Mesh
  33527. */
  33528. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33529. if (scene === void 0) { scene = null; }
  33530. var options = {
  33531. points: points,
  33532. dashSize: dashSize,
  33533. gapSize: gapSize,
  33534. dashNb: dashNb,
  33535. updatable: updatable,
  33536. instance: instance
  33537. };
  33538. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33539. };
  33540. /**
  33541. * Creates a polygon mesh.
  33542. * Please consider using the same method from the MeshBuilder class instead.
  33543. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33544. * 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.
  33545. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33546. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33547. * Remember you can only change the shape positions, not their number when updating a polygon.
  33548. */
  33549. /**
  33550. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  33551. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  33552. * @param name defines the name of the mesh to create
  33553. * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  33554. * @param scene defines the hosting scene
  33555. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33556. * @param updatable defines if the mesh must be flagged as updatable
  33557. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33558. * @returns a new Mesh
  33559. */
  33560. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33561. var options = {
  33562. shape: shape,
  33563. holes: holes,
  33564. updatable: updatable,
  33565. sideOrientation: sideOrientation
  33566. };
  33567. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33568. };
  33569. /**
  33570. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  33571. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  33572. * @param name defines the name of the mesh to create
  33573. * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  33574. * @param depth defines the height of extrusion
  33575. * @param scene defines the hosting scene
  33576. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33577. * @param updatable defines if the mesh must be flagged as updatable
  33578. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33579. * @returns a new Mesh
  33580. */
  33581. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33582. var options = {
  33583. shape: shape,
  33584. holes: holes,
  33585. depth: depth,
  33586. updatable: updatable,
  33587. sideOrientation: sideOrientation
  33588. };
  33589. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33590. };
  33591. /**
  33592. * Creates an extruded shape mesh.
  33593. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  33594. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33595. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33596. * @param name defines the name of the mesh to create
  33597. * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
  33598. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33599. * @param scale is the value to scale the shape
  33600. * @param rotation is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve
  33601. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33602. * @param scene defines the hosting scene
  33603. * @param updatable defines if the mesh must be flagged as updatable
  33604. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33605. * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  33606. * @returns a new Mesh
  33607. */
  33608. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33609. if (scene === void 0) { scene = null; }
  33610. var options = {
  33611. shape: shape,
  33612. path: path,
  33613. scale: scale,
  33614. rotation: rotation,
  33615. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33616. sideOrientation: sideOrientation,
  33617. instance: instance,
  33618. updatable: updatable
  33619. };
  33620. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33621. };
  33622. /**
  33623. * Creates an custom extruded shape mesh.
  33624. * The custom extrusion is a parametric shape.
  33625. * It has no predefined shape. Its final shape will depend on the input parameters.
  33626. * Please consider using the same method from the MeshBuilder class instead
  33627. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33628. * @param name defines the name of the mesh to create
  33629. * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
  33630. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33631. * @param scaleFunction is a custom Javascript function called on each path point
  33632. * @param rotationFunction is a custom Javascript function called on each path point
  33633. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  33634. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  33635. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33636. * @param scene defines the hosting scene
  33637. * @param updatable defines if the mesh must be flagged as updatable
  33638. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33639. * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  33640. * @returns a new Mesh
  33641. */
  33642. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33643. var options = {
  33644. shape: shape,
  33645. path: path,
  33646. scaleFunction: scaleFunction,
  33647. rotationFunction: rotationFunction,
  33648. ribbonCloseArray: ribbonCloseArray,
  33649. ribbonClosePath: ribbonClosePath,
  33650. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33651. sideOrientation: sideOrientation,
  33652. instance: instance,
  33653. updatable: updatable
  33654. };
  33655. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33656. };
  33657. /**
  33658. * Creates lathe mesh.
  33659. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33660. * Please consider using the same method from the MeshBuilder class instead
  33661. * @param name defines the name of the mesh to create
  33662. * @param shape is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  33663. * @param radius is the radius value of the lathe
  33664. * @param tessellation is the side number of the lathe.
  33665. * @param scene defines the hosting scene
  33666. * @param updatable defines if the mesh must be flagged as updatable
  33667. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33668. * @returns a new Mesh
  33669. */
  33670. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33671. var options = {
  33672. shape: shape,
  33673. radius: radius,
  33674. tessellation: tessellation,
  33675. sideOrientation: sideOrientation,
  33676. updatable: updatable
  33677. };
  33678. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33679. };
  33680. /**
  33681. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  33682. * @param name defines the name of the mesh to create
  33683. * @param size sets the size (float) of both sides of the plane at once (default 1)
  33684. * @param scene defines the hosting scene
  33685. * @param updatable defines if the mesh must be flagged as updatable
  33686. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33687. * @returns a new Mesh
  33688. */
  33689. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33690. var options = {
  33691. size: size,
  33692. width: size,
  33693. height: size,
  33694. sideOrientation: sideOrientation,
  33695. updatable: updatable
  33696. };
  33697. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33698. };
  33699. /**
  33700. * Creates a ground mesh.
  33701. * Please consider using the same method from the MeshBuilder class instead
  33702. * @param name defines the name of the mesh to create
  33703. * @param width set the width of the ground
  33704. * @param height set the height of the ground
  33705. * @param subdivisions sets the number of subdivisions per side
  33706. * @param scene defines the hosting scene
  33707. * @param updatable defines if the mesh must be flagged as updatable
  33708. * @returns a new Mesh
  33709. */
  33710. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33711. var options = {
  33712. width: width,
  33713. height: height,
  33714. subdivisions: subdivisions,
  33715. updatable: updatable
  33716. };
  33717. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33718. };
  33719. /**
  33720. * Creates a tiled ground mesh.
  33721. * Please consider using the same method from the MeshBuilder class instead
  33722. * @param name defines the name of the mesh to create
  33723. * @param xmin set the ground minimum X coordinate
  33724. * @param zmin set the ground minimum Y coordinate
  33725. * @param xmax set the ground maximum X coordinate
  33726. * @param zmax set the ground maximum Z coordinate
  33727. * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  33728. * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  33729. * @param scene defines the hosting scene
  33730. * @param updatable defines if the mesh must be flagged as updatable
  33731. * @returns a new Mesh
  33732. */
  33733. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33734. var options = {
  33735. xmin: xmin,
  33736. zmin: zmin,
  33737. xmax: xmax,
  33738. zmax: zmax,
  33739. subdivisions: subdivisions,
  33740. precision: precision,
  33741. updatable: updatable
  33742. };
  33743. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33744. };
  33745. /**
  33746. * Creates a ground mesh from a height map.
  33747. * Please consider using the same method from the MeshBuilder class instead
  33748. * @see http://doc.babylonjs.com/babylon101/height_map
  33749. * @param name defines the name of the mesh to create
  33750. * @param url sets the URL of the height map image resource
  33751. * @param width set the ground width size
  33752. * @param height set the ground height size
  33753. * @param subdivisions sets the number of subdivision per side
  33754. * @param minHeight is the minimum altitude on the ground
  33755. * @param maxHeight is the maximum altitude on the ground
  33756. * @param scene defines the hosting scene
  33757. * @param updatable defines if the mesh must be flagged as updatable
  33758. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  33759. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  33760. * @returns a new Mesh
  33761. */
  33762. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33763. var options = {
  33764. width: width,
  33765. height: height,
  33766. subdivisions: subdivisions,
  33767. minHeight: minHeight,
  33768. maxHeight: maxHeight,
  33769. updatable: updatable,
  33770. onReady: onReady,
  33771. alphaFilter: alphaFilter
  33772. };
  33773. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33774. };
  33775. /**
  33776. * Creates a tube mesh.
  33777. * The tube is a parametric shape.
  33778. * It has no predefined shape. Its final shape will depend on the input parameters.
  33779. * Please consider using the same method from the MeshBuilder class instead
  33780. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33781. * @param name defines the name of the mesh to create
  33782. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  33783. * @param radius sets the tube radius size
  33784. * @param tessellation is the number of sides on the tubular surface
  33785. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path
  33786. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33787. * @param scene defines the hosting scene
  33788. * @param updatable defines if the mesh must be flagged as updatable
  33789. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33790. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  33791. * @returns a new Mesh
  33792. */
  33793. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33794. var options = {
  33795. path: path,
  33796. radius: radius,
  33797. tessellation: tessellation,
  33798. radiusFunction: radiusFunction,
  33799. arc: 1,
  33800. cap: cap,
  33801. updatable: updatable,
  33802. sideOrientation: sideOrientation,
  33803. instance: instance
  33804. };
  33805. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33806. };
  33807. /**
  33808. * Creates a polyhedron mesh.
  33809. * Please consider using the same method from the MeshBuilder class instead.
  33810. * * 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
  33811. * * The parameter `size` (positive float, default 1) sets the polygon size
  33812. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  33813. * * 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`
  33814. * * 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
  33815. * * 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)`)
  33816. * * 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
  33817. * * 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
  33818. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33819. * * 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
  33820. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33821. * @param name defines the name of the mesh to create
  33822. * @param options defines the options used to create the mesh
  33823. * @param scene defines the hosting scene
  33824. * @returns a new Mesh
  33825. */
  33826. Mesh.CreatePolyhedron = function (name, options, scene) {
  33827. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33828. };
  33829. /**
  33830. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  33831. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  33832. * * 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`)
  33833. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  33834. * * 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
  33835. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33836. * * 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
  33837. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33838. * @param name defines the name of the mesh
  33839. * @param options defines the options used to create the mesh
  33840. * @param scene defines the hosting scene
  33841. * @returns a new Mesh
  33842. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  33843. */
  33844. Mesh.CreateIcoSphere = function (name, options, scene) {
  33845. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33846. };
  33847. /**
  33848. * Creates a decal mesh.
  33849. * Please consider using the same method from the MeshBuilder class instead.
  33850. * A decal is a mesh usually applied as a model onto the surface of another mesh
  33851. * @param name defines the name of the mesh
  33852. * @param sourceMesh defines the mesh receiving the decal
  33853. * @param position sets the position of the decal in world coordinates
  33854. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  33855. * @param size sets the decal scaling
  33856. * @param angle sets the angle to rotate the decal
  33857. * @returns a new Mesh
  33858. */
  33859. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33860. var options = {
  33861. position: position,
  33862. normal: normal,
  33863. size: size,
  33864. angle: angle
  33865. };
  33866. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33867. };
  33868. // Skeletons
  33869. /**
  33870. * Prepare internal position array for software CPU skinning
  33871. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  33872. */
  33873. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33874. if (!this._sourcePositions) {
  33875. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33876. if (!source) {
  33877. return this._sourcePositions;
  33878. }
  33879. this._sourcePositions = new Float32Array(source);
  33880. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33881. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33882. }
  33883. }
  33884. return this._sourcePositions;
  33885. };
  33886. /**
  33887. * Prepare internal normal array for software CPU skinning
  33888. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33889. */
  33890. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33891. if (!this._sourceNormals) {
  33892. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33893. if (!source) {
  33894. return this._sourceNormals;
  33895. }
  33896. this._sourceNormals = new Float32Array(source);
  33897. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33898. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33899. }
  33900. }
  33901. return this._sourceNormals;
  33902. };
  33903. /**
  33904. * Updates the vertex buffer by applying transformation from the bones
  33905. * @param skeleton defines the skeleton to apply to current mesh
  33906. * @returns the current mesh
  33907. */
  33908. Mesh.prototype.applySkeleton = function (skeleton) {
  33909. if (!this.geometry) {
  33910. return this;
  33911. }
  33912. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33913. return this;
  33914. }
  33915. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33916. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33917. return this;
  33918. }
  33919. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33920. return this;
  33921. }
  33922. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33923. return this;
  33924. }
  33925. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33926. return this;
  33927. }
  33928. if (!this._sourcePositions) {
  33929. var submeshes = this.subMeshes.slice();
  33930. this.setPositionsForCPUSkinning();
  33931. this.subMeshes = submeshes;
  33932. }
  33933. if (!this._sourceNormals) {
  33934. this.setNormalsForCPUSkinning();
  33935. }
  33936. // positionsData checks for not being Float32Array will only pass at most once
  33937. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33938. if (!positionsData) {
  33939. return this;
  33940. }
  33941. if (!(positionsData instanceof Float32Array)) {
  33942. positionsData = new Float32Array(positionsData);
  33943. }
  33944. // normalsData checks for not being Float32Array will only pass at most once
  33945. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33946. if (!normalsData) {
  33947. return this;
  33948. }
  33949. if (!(normalsData instanceof Float32Array)) {
  33950. normalsData = new Float32Array(normalsData);
  33951. }
  33952. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33953. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33954. if (!matricesWeightsData || !matricesIndicesData) {
  33955. return this;
  33956. }
  33957. var needExtras = this.numBoneInfluencers > 4;
  33958. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33959. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33960. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33961. var tempVector3 = BABYLON.Vector3.Zero();
  33962. var finalMatrix = new BABYLON.Matrix();
  33963. var tempMatrix = new BABYLON.Matrix();
  33964. var matWeightIdx = 0;
  33965. var inf;
  33966. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33967. var weight;
  33968. for (inf = 0; inf < 4; inf++) {
  33969. weight = matricesWeightsData[matWeightIdx + inf];
  33970. if (weight > 0) {
  33971. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33972. finalMatrix.addToSelf(tempMatrix);
  33973. }
  33974. }
  33975. if (needExtras) {
  33976. for (inf = 0; inf < 4; inf++) {
  33977. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33978. if (weight > 0) {
  33979. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33980. finalMatrix.addToSelf(tempMatrix);
  33981. }
  33982. }
  33983. }
  33984. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33985. tempVector3.toArray(positionsData, index);
  33986. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33987. tempVector3.toArray(normalsData, index);
  33988. finalMatrix.reset();
  33989. }
  33990. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33991. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33992. return this;
  33993. };
  33994. // Tools
  33995. /**
  33996. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  33997. * @param meshes defines the list of meshes to scan
  33998. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  33999. */
  34000. Mesh.MinMax = function (meshes) {
  34001. var minVector = null;
  34002. var maxVector = null;
  34003. meshes.forEach(function (mesh, index, array) {
  34004. var boundingInfo = mesh.getBoundingInfo();
  34005. var boundingBox = boundingInfo.boundingBox;
  34006. if (!minVector || !maxVector) {
  34007. minVector = boundingBox.minimumWorld;
  34008. maxVector = boundingBox.maximumWorld;
  34009. }
  34010. else {
  34011. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34012. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34013. }
  34014. });
  34015. if (!minVector || !maxVector) {
  34016. return {
  34017. min: BABYLON.Vector3.Zero(),
  34018. max: BABYLON.Vector3.Zero()
  34019. };
  34020. }
  34021. return {
  34022. min: minVector,
  34023. max: maxVector
  34024. };
  34025. };
  34026. /**
  34027. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  34028. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  34029. * @returns a vector3
  34030. */
  34031. Mesh.Center = function (meshesOrMinMaxVector) {
  34032. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34033. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34034. };
  34035. /**
  34036. * Merge the array of meshes into a single mesh for performance reasons.
  34037. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  34038. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  34039. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  34040. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34041. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  34042. * @returns a new mesh
  34043. */
  34044. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34045. if (disposeSource === void 0) { disposeSource = true; }
  34046. var index;
  34047. if (!allow32BitsIndices) {
  34048. var totalVertices = 0;
  34049. // Counting vertices
  34050. for (index = 0; index < meshes.length; index++) {
  34051. if (meshes[index]) {
  34052. totalVertices += meshes[index].getTotalVertices();
  34053. if (totalVertices > 65536) {
  34054. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34055. return null;
  34056. }
  34057. }
  34058. }
  34059. }
  34060. // Merge
  34061. var vertexData = null;
  34062. var otherVertexData;
  34063. var indiceArray = new Array();
  34064. var source = null;
  34065. for (index = 0; index < meshes.length; index++) {
  34066. if (meshes[index]) {
  34067. var wm = meshes[index].computeWorldMatrix(true);
  34068. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34069. otherVertexData.transform(wm);
  34070. if (vertexData) {
  34071. vertexData.merge(otherVertexData, allow32BitsIndices);
  34072. }
  34073. else {
  34074. vertexData = otherVertexData;
  34075. source = meshes[index];
  34076. }
  34077. if (subdivideWithSubMeshes) {
  34078. indiceArray.push(meshes[index].getTotalIndices());
  34079. }
  34080. }
  34081. }
  34082. source = source;
  34083. if (!meshSubclass) {
  34084. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34085. }
  34086. vertexData.applyToMesh(meshSubclass);
  34087. // Setting properties
  34088. meshSubclass.material = source.material;
  34089. meshSubclass.checkCollisions = source.checkCollisions;
  34090. // Cleaning
  34091. if (disposeSource) {
  34092. for (index = 0; index < meshes.length; index++) {
  34093. if (meshes[index]) {
  34094. meshes[index].dispose();
  34095. }
  34096. }
  34097. }
  34098. // Subdivide
  34099. if (subdivideWithSubMeshes) {
  34100. //-- removal of global submesh
  34101. meshSubclass.releaseSubMeshes();
  34102. index = 0;
  34103. var offset = 0;
  34104. //-- apply subdivision according to index table
  34105. while (index < indiceArray.length) {
  34106. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34107. offset += indiceArray[index];
  34108. index++;
  34109. }
  34110. }
  34111. return meshSubclass;
  34112. };
  34113. // Consts
  34114. /**
  34115. * Mesh side orientation : usually the external or front surface
  34116. */
  34117. Mesh.FRONTSIDE = 0;
  34118. /**
  34119. * Mesh side orientation : usually the internal or back surface
  34120. */
  34121. Mesh.BACKSIDE = 1;
  34122. /**
  34123. * Mesh side orientation : both internal and external or front and back surfaces
  34124. */
  34125. Mesh.DOUBLESIDE = 2;
  34126. /**
  34127. * Mesh side orientation : by default, `FRONTSIDE`
  34128. */
  34129. Mesh.DEFAULTSIDE = 0;
  34130. /**
  34131. * Mesh cap setting : no cap
  34132. */
  34133. Mesh.NO_CAP = 0;
  34134. /**
  34135. * Mesh cap setting : one cap at the beginning of the mesh
  34136. */
  34137. Mesh.CAP_START = 1;
  34138. /**
  34139. * Mesh cap setting : one cap at the end of the mesh
  34140. */
  34141. Mesh.CAP_END = 2;
  34142. /**
  34143. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34144. */
  34145. Mesh.CAP_ALL = 3;
  34146. return Mesh;
  34147. }(BABYLON.AbstractMesh));
  34148. BABYLON.Mesh = Mesh;
  34149. })(BABYLON || (BABYLON = {}));
  34150. //# sourceMappingURL=babylon.mesh.js.map
  34151. var BABYLON;
  34152. (function (BABYLON) {
  34153. var BaseSubMesh = /** @class */ (function () {
  34154. function BaseSubMesh() {
  34155. }
  34156. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34157. get: function () {
  34158. return this._materialEffect;
  34159. },
  34160. enumerable: true,
  34161. configurable: true
  34162. });
  34163. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34164. if (defines === void 0) { defines = null; }
  34165. if (this._materialEffect === effect) {
  34166. if (!effect) {
  34167. this._materialDefines = null;
  34168. }
  34169. return;
  34170. }
  34171. this._materialDefines = defines;
  34172. this._materialEffect = effect;
  34173. };
  34174. return BaseSubMesh;
  34175. }());
  34176. BABYLON.BaseSubMesh = BaseSubMesh;
  34177. var SubMesh = /** @class */ (function (_super) {
  34178. __extends(SubMesh, _super);
  34179. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34180. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34181. var _this = _super.call(this) || this;
  34182. _this.materialIndex = materialIndex;
  34183. _this.verticesStart = verticesStart;
  34184. _this.verticesCount = verticesCount;
  34185. _this.indexStart = indexStart;
  34186. _this.indexCount = indexCount;
  34187. /** @hidden */
  34188. _this._renderId = 0;
  34189. _this._mesh = mesh;
  34190. _this._renderingMesh = renderingMesh || mesh;
  34191. mesh.subMeshes.push(_this);
  34192. _this._trianglePlanes = [];
  34193. _this._id = mesh.subMeshes.length - 1;
  34194. if (createBoundingBox) {
  34195. _this.refreshBoundingInfo();
  34196. mesh.computeWorldMatrix(true);
  34197. }
  34198. return _this;
  34199. }
  34200. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34201. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34202. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34203. };
  34204. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34205. get: function () {
  34206. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  34207. },
  34208. enumerable: true,
  34209. configurable: true
  34210. });
  34211. /**
  34212. * Returns the submesh BoudingInfo object.
  34213. */
  34214. SubMesh.prototype.getBoundingInfo = function () {
  34215. if (this.IsGlobal) {
  34216. return this._mesh.getBoundingInfo();
  34217. }
  34218. return this._boundingInfo;
  34219. };
  34220. /**
  34221. * Sets the submesh BoundingInfo.
  34222. * Return the SubMesh.
  34223. */
  34224. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34225. this._boundingInfo = boundingInfo;
  34226. return this;
  34227. };
  34228. /**
  34229. * Returns the mesh of the current submesh.
  34230. */
  34231. SubMesh.prototype.getMesh = function () {
  34232. return this._mesh;
  34233. };
  34234. /**
  34235. * Returns the rendering mesh of the submesh.
  34236. */
  34237. SubMesh.prototype.getRenderingMesh = function () {
  34238. return this._renderingMesh;
  34239. };
  34240. /**
  34241. * Returns the submesh material.
  34242. */
  34243. SubMesh.prototype.getMaterial = function () {
  34244. var rootMaterial = this._renderingMesh.material;
  34245. if (rootMaterial === null || rootMaterial === undefined) {
  34246. return this._mesh.getScene().defaultMaterial;
  34247. }
  34248. else if (rootMaterial.getSubMaterial) {
  34249. var multiMaterial = rootMaterial;
  34250. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34251. if (this._currentMaterial !== effectiveMaterial) {
  34252. this._currentMaterial = effectiveMaterial;
  34253. this._materialDefines = null;
  34254. }
  34255. return effectiveMaterial;
  34256. }
  34257. return rootMaterial;
  34258. };
  34259. // Methods
  34260. /**
  34261. * Sets a new updated BoundingInfo object to the submesh.
  34262. * Returns the SubMesh.
  34263. */
  34264. SubMesh.prototype.refreshBoundingInfo = function () {
  34265. this._lastColliderWorldVertices = null;
  34266. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34267. return this;
  34268. }
  34269. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34270. if (!data) {
  34271. this._boundingInfo = this._mesh.getBoundingInfo();
  34272. return this;
  34273. }
  34274. var indices = this._renderingMesh.getIndices();
  34275. var extend;
  34276. //is this the only submesh?
  34277. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34278. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34279. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34280. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34281. }
  34282. else {
  34283. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34284. }
  34285. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34286. return this;
  34287. };
  34288. /** @hidden */
  34289. SubMesh.prototype._checkCollision = function (collider) {
  34290. var boundingInfo = this.getBoundingInfo();
  34291. return boundingInfo._checkCollision(collider);
  34292. };
  34293. /**
  34294. * Updates the submesh BoundingInfo.
  34295. * Returns the Submesh.
  34296. */
  34297. SubMesh.prototype.updateBoundingInfo = function (world) {
  34298. var boundingInfo = this.getBoundingInfo();
  34299. if (!boundingInfo) {
  34300. this.refreshBoundingInfo();
  34301. boundingInfo = this.getBoundingInfo();
  34302. }
  34303. boundingInfo.update(world);
  34304. return this;
  34305. };
  34306. /**
  34307. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34308. * Boolean returned.
  34309. */
  34310. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34311. var boundingInfo = this.getBoundingInfo();
  34312. if (!boundingInfo) {
  34313. return false;
  34314. }
  34315. return boundingInfo.isInFrustum(frustumPlanes);
  34316. };
  34317. /**
  34318. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34319. * Boolean returned.
  34320. */
  34321. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34322. var boundingInfo = this.getBoundingInfo();
  34323. if (!boundingInfo) {
  34324. return false;
  34325. }
  34326. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34327. };
  34328. /**
  34329. * Renders the submesh.
  34330. * Returns it.
  34331. */
  34332. SubMesh.prototype.render = function (enableAlphaMode) {
  34333. this._renderingMesh.render(this, enableAlphaMode);
  34334. return this;
  34335. };
  34336. /**
  34337. * Returns a new Index Buffer.
  34338. * Type returned : WebGLBuffer.
  34339. */
  34340. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34341. if (!this._linesIndexBuffer) {
  34342. var linesIndices = [];
  34343. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34344. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34345. }
  34346. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34347. this.linesIndexCount = linesIndices.length;
  34348. }
  34349. return this._linesIndexBuffer;
  34350. };
  34351. /**
  34352. * True is the passed Ray intersects the submesh bounding box.
  34353. * Boolean returned.
  34354. */
  34355. SubMesh.prototype.canIntersects = function (ray) {
  34356. var boundingInfo = this.getBoundingInfo();
  34357. if (!boundingInfo) {
  34358. return false;
  34359. }
  34360. return ray.intersectsBox(boundingInfo.boundingBox);
  34361. };
  34362. /**
  34363. * Returns an object IntersectionInfo.
  34364. */
  34365. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34366. var intersectInfo = null;
  34367. var material = this.getMaterial();
  34368. if (!material) {
  34369. return null;
  34370. }
  34371. switch (material.fillMode) {
  34372. case BABYLON.Material.PointListDrawMode:
  34373. case BABYLON.Material.LineListDrawMode:
  34374. case BABYLON.Material.LineLoopDrawMode:
  34375. case BABYLON.Material.LineStripDrawMode:
  34376. case BABYLON.Material.TriangleFanDrawMode:
  34377. case BABYLON.Material.TriangleStripDrawMode:
  34378. return null;
  34379. }
  34380. // LineMesh first as it's also a Mesh...
  34381. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34382. var lineMesh = this._mesh;
  34383. // Line test
  34384. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34385. var p0 = positions[indices[index]];
  34386. var p1 = positions[indices[index + 1]];
  34387. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34388. if (length < 0) {
  34389. continue;
  34390. }
  34391. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34392. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34393. if (fastCheck) {
  34394. break;
  34395. }
  34396. }
  34397. }
  34398. }
  34399. else {
  34400. // Triangles test
  34401. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34402. var p0 = positions[indices[index]];
  34403. var p1 = positions[indices[index + 1]];
  34404. var p2 = positions[indices[index + 2]];
  34405. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34406. if (currentIntersectInfo) {
  34407. if (currentIntersectInfo.distance < 0) {
  34408. continue;
  34409. }
  34410. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34411. intersectInfo = currentIntersectInfo;
  34412. intersectInfo.faceId = index / 3;
  34413. if (fastCheck) {
  34414. break;
  34415. }
  34416. }
  34417. }
  34418. }
  34419. }
  34420. return intersectInfo;
  34421. };
  34422. /** @hidden */
  34423. SubMesh.prototype._rebuild = function () {
  34424. if (this._linesIndexBuffer) {
  34425. this._linesIndexBuffer = null;
  34426. }
  34427. };
  34428. // Clone
  34429. /**
  34430. * Creates a new Submesh from the passed Mesh.
  34431. */
  34432. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34433. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34434. if (!this.IsGlobal) {
  34435. var boundingInfo = this.getBoundingInfo();
  34436. if (!boundingInfo) {
  34437. return result;
  34438. }
  34439. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34440. }
  34441. return result;
  34442. };
  34443. // Dispose
  34444. /**
  34445. * Disposes the Submesh.
  34446. * Returns nothing.
  34447. */
  34448. SubMesh.prototype.dispose = function () {
  34449. if (this._linesIndexBuffer) {
  34450. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34451. this._linesIndexBuffer = null;
  34452. }
  34453. // Remove from mesh
  34454. var index = this._mesh.subMeshes.indexOf(this);
  34455. this._mesh.subMeshes.splice(index, 1);
  34456. };
  34457. // Statics
  34458. /**
  34459. * Creates a new Submesh from the passed parameters :
  34460. * - materialIndex (integer) : the index of the main mesh material.
  34461. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34462. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34463. * - mesh (Mesh) : the main mesh to create the submesh from.
  34464. * - renderingMesh (optional Mesh) : rendering mesh.
  34465. */
  34466. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34467. var minVertexIndex = Number.MAX_VALUE;
  34468. var maxVertexIndex = -Number.MAX_VALUE;
  34469. renderingMesh = (renderingMesh || mesh);
  34470. var indices = renderingMesh.getIndices();
  34471. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34472. var vertexIndex = indices[index];
  34473. if (vertexIndex < minVertexIndex)
  34474. minVertexIndex = vertexIndex;
  34475. if (vertexIndex > maxVertexIndex)
  34476. maxVertexIndex = vertexIndex;
  34477. }
  34478. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34479. };
  34480. return SubMesh;
  34481. }(BaseSubMesh));
  34482. BABYLON.SubMesh = SubMesh;
  34483. })(BABYLON || (BABYLON = {}));
  34484. //# sourceMappingURL=babylon.subMesh.js.map
  34485. var __assign = (this && this.__assign) || function () {
  34486. __assign = Object.assign || function(t) {
  34487. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34488. s = arguments[i];
  34489. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34490. t[p] = s[p];
  34491. }
  34492. return t;
  34493. };
  34494. return __assign.apply(this, arguments);
  34495. };
  34496. var BABYLON;
  34497. (function (BABYLON) {
  34498. /**
  34499. * Manages the defines for the Material
  34500. */
  34501. var MaterialDefines = /** @class */ (function () {
  34502. function MaterialDefines() {
  34503. this._isDirty = true;
  34504. /** @hidden */
  34505. this._areLightsDirty = true;
  34506. /** @hidden */
  34507. this._areAttributesDirty = true;
  34508. /** @hidden */
  34509. this._areTexturesDirty = true;
  34510. /** @hidden */
  34511. this._areFresnelDirty = true;
  34512. /** @hidden */
  34513. this._areMiscDirty = true;
  34514. /** @hidden */
  34515. this._areImageProcessingDirty = true;
  34516. /** @hidden */
  34517. this._normals = false;
  34518. /** @hidden */
  34519. this._uvs = false;
  34520. /** @hidden */
  34521. this._needNormals = false;
  34522. /** @hidden */
  34523. this._needUVs = false;
  34524. }
  34525. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34526. /**
  34527. * Specifies if the material needs to be re-calculated
  34528. */
  34529. get: function () {
  34530. return this._isDirty;
  34531. },
  34532. enumerable: true,
  34533. configurable: true
  34534. });
  34535. /**
  34536. * Marks the material to indicate that it has been re-calculated
  34537. */
  34538. MaterialDefines.prototype.markAsProcessed = function () {
  34539. this._isDirty = false;
  34540. this._areAttributesDirty = false;
  34541. this._areTexturesDirty = false;
  34542. this._areFresnelDirty = false;
  34543. this._areLightsDirty = false;
  34544. this._areMiscDirty = false;
  34545. this._areImageProcessingDirty = false;
  34546. };
  34547. /**
  34548. * Marks the material to indicate that it needs to be re-calculated
  34549. */
  34550. MaterialDefines.prototype.markAsUnprocessed = function () {
  34551. this._isDirty = true;
  34552. };
  34553. /**
  34554. * Marks the material to indicate all of its defines need to be re-calculated
  34555. */
  34556. MaterialDefines.prototype.markAllAsDirty = function () {
  34557. this._areTexturesDirty = true;
  34558. this._areAttributesDirty = true;
  34559. this._areLightsDirty = true;
  34560. this._areFresnelDirty = true;
  34561. this._areMiscDirty = true;
  34562. this._areImageProcessingDirty = true;
  34563. this._isDirty = true;
  34564. };
  34565. /**
  34566. * Marks the material to indicate that image processing needs to be re-calculated
  34567. */
  34568. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34569. this._areImageProcessingDirty = true;
  34570. this._isDirty = true;
  34571. };
  34572. /**
  34573. * Marks the material to indicate the lights need to be re-calculated
  34574. */
  34575. MaterialDefines.prototype.markAsLightDirty = function () {
  34576. this._areLightsDirty = true;
  34577. this._isDirty = true;
  34578. };
  34579. /**
  34580. * Marks the attribute state as changed
  34581. */
  34582. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34583. this._areAttributesDirty = true;
  34584. this._isDirty = true;
  34585. };
  34586. /**
  34587. * Marks the texture state as changed
  34588. */
  34589. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34590. this._areTexturesDirty = true;
  34591. this._isDirty = true;
  34592. };
  34593. /**
  34594. * Marks the fresnel state as changed
  34595. */
  34596. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34597. this._areFresnelDirty = true;
  34598. this._isDirty = true;
  34599. };
  34600. /**
  34601. * Marks the misc state as changed
  34602. */
  34603. MaterialDefines.prototype.markAsMiscDirty = function () {
  34604. this._areMiscDirty = true;
  34605. this._isDirty = true;
  34606. };
  34607. /**
  34608. * Rebuilds the material defines
  34609. */
  34610. MaterialDefines.prototype.rebuild = function () {
  34611. if (this._keys) {
  34612. delete this._keys;
  34613. }
  34614. this._keys = [];
  34615. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34616. var key = _a[_i];
  34617. if (key[0] === "_") {
  34618. continue;
  34619. }
  34620. this._keys.push(key);
  34621. }
  34622. };
  34623. /**
  34624. * Specifies if two material defines are equal
  34625. * @param other - A material define instance to compare to
  34626. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34627. */
  34628. MaterialDefines.prototype.isEqual = function (other) {
  34629. if (this._keys.length !== other._keys.length) {
  34630. return false;
  34631. }
  34632. for (var index = 0; index < this._keys.length; index++) {
  34633. var prop = this._keys[index];
  34634. if (this[prop] !== other[prop]) {
  34635. return false;
  34636. }
  34637. }
  34638. return true;
  34639. };
  34640. /**
  34641. * Clones this instance's defines to another instance
  34642. * @param other - material defines to clone values to
  34643. */
  34644. MaterialDefines.prototype.cloneTo = function (other) {
  34645. if (this._keys.length !== other._keys.length) {
  34646. other._keys = this._keys.slice(0);
  34647. }
  34648. for (var index = 0; index < this._keys.length; index++) {
  34649. var prop = this._keys[index];
  34650. other[prop] = this[prop];
  34651. }
  34652. };
  34653. /**
  34654. * Resets the material define values
  34655. */
  34656. MaterialDefines.prototype.reset = function () {
  34657. for (var index = 0; index < this._keys.length; index++) {
  34658. var prop = this._keys[index];
  34659. var type = typeof this[prop];
  34660. switch (type) {
  34661. case "number":
  34662. this[prop] = 0;
  34663. break;
  34664. case "string":
  34665. this[prop] = "";
  34666. break;
  34667. default:
  34668. this[prop] = false;
  34669. break;
  34670. }
  34671. }
  34672. };
  34673. /**
  34674. * Converts the material define values to a string
  34675. * @returns - String of material define information
  34676. */
  34677. MaterialDefines.prototype.toString = function () {
  34678. var result = "";
  34679. for (var index = 0; index < this._keys.length; index++) {
  34680. var prop = this._keys[index];
  34681. var value = this[prop];
  34682. var type = typeof value;
  34683. switch (type) {
  34684. case "number":
  34685. case "string":
  34686. result += "#define " + prop + " " + value + "\n";
  34687. break;
  34688. default:
  34689. if (value) {
  34690. result += "#define " + prop + "\n";
  34691. }
  34692. break;
  34693. }
  34694. }
  34695. return result;
  34696. };
  34697. return MaterialDefines;
  34698. }());
  34699. BABYLON.MaterialDefines = MaterialDefines;
  34700. /**
  34701. * Base class for the main features of a material in Babylon.js
  34702. */
  34703. var Material = /** @class */ (function () {
  34704. /**
  34705. * Creates a material instance
  34706. * @param name defines the name of the material
  34707. * @param scene defines the scene to reference
  34708. * @param doNotAdd specifies if the material should be added to the scene
  34709. */
  34710. function Material(name, scene, doNotAdd) {
  34711. /**
  34712. * Specifies if the ready state should be checked on each call
  34713. */
  34714. this.checkReadyOnEveryCall = false;
  34715. /**
  34716. * Specifies if the ready state should be checked once
  34717. */
  34718. this.checkReadyOnlyOnce = false;
  34719. /**
  34720. * The state of the material
  34721. */
  34722. this.state = "";
  34723. /**
  34724. * The alpha value of the material
  34725. */
  34726. this._alpha = 1.0;
  34727. /**
  34728. * Specifies if back face culling is enabled
  34729. */
  34730. this._backFaceCulling = true;
  34731. /**
  34732. * Specifies if the material should be serialized
  34733. */
  34734. this.doNotSerialize = false;
  34735. /**
  34736. * Specifies if the effect should be stored on sub meshes
  34737. */
  34738. this.storeEffectOnSubMeshes = false;
  34739. /**
  34740. * An event triggered when the material is disposed
  34741. */
  34742. this.onDisposeObservable = new BABYLON.Observable();
  34743. /**
  34744. * Stores the value of the alpha mode
  34745. */
  34746. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34747. /**
  34748. * Stores the state of the need depth pre-pass value
  34749. */
  34750. this._needDepthPrePass = false;
  34751. /**
  34752. * Specifies if depth writing should be disabled
  34753. */
  34754. this.disableDepthWrite = false;
  34755. /**
  34756. * Specifies if depth writing should be forced
  34757. */
  34758. this.forceDepthWrite = false;
  34759. /**
  34760. * Specifies if there should be a separate pass for culling
  34761. */
  34762. this.separateCullingPass = false;
  34763. /**
  34764. * Stores the state specifing if fog should be enabled
  34765. */
  34766. this._fogEnabled = true;
  34767. /**
  34768. * Stores the size of points
  34769. */
  34770. this.pointSize = 1.0;
  34771. /**
  34772. * Stores the z offset value
  34773. */
  34774. this.zOffset = 0;
  34775. /**
  34776. * @hidden
  34777. * Specifies if the material was previously ready
  34778. */
  34779. this._wasPreviouslyReady = false;
  34780. /**
  34781. * Stores the fill mode state
  34782. */
  34783. this._fillMode = Material.TriangleFillMode;
  34784. this.name = name;
  34785. this.id = name || BABYLON.Tools.RandomId();
  34786. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34787. this.uniqueId = this._scene.getUniqueId();
  34788. if (this._scene.useRightHandedSystem) {
  34789. this.sideOrientation = Material.ClockWiseSideOrientation;
  34790. }
  34791. else {
  34792. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34793. }
  34794. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34795. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34796. if (!doNotAdd) {
  34797. this._scene.materials.push(this);
  34798. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  34799. }
  34800. }
  34801. Object.defineProperty(Material, "TriangleFillMode", {
  34802. /**
  34803. * Returns the triangle fill mode
  34804. */
  34805. get: function () {
  34806. return Material._TriangleFillMode;
  34807. },
  34808. enumerable: true,
  34809. configurable: true
  34810. });
  34811. Object.defineProperty(Material, "WireFrameFillMode", {
  34812. /**
  34813. * Returns the wireframe mode
  34814. */
  34815. get: function () {
  34816. return Material._WireFrameFillMode;
  34817. },
  34818. enumerable: true,
  34819. configurable: true
  34820. });
  34821. Object.defineProperty(Material, "PointFillMode", {
  34822. /**
  34823. * Returns the point fill mode
  34824. */
  34825. get: function () {
  34826. return Material._PointFillMode;
  34827. },
  34828. enumerable: true,
  34829. configurable: true
  34830. });
  34831. Object.defineProperty(Material, "PointListDrawMode", {
  34832. /**
  34833. * Returns the point list draw mode
  34834. */
  34835. get: function () {
  34836. return Material._PointListDrawMode;
  34837. },
  34838. enumerable: true,
  34839. configurable: true
  34840. });
  34841. Object.defineProperty(Material, "LineListDrawMode", {
  34842. /**
  34843. * Returns the line list draw mode
  34844. */
  34845. get: function () {
  34846. return Material._LineListDrawMode;
  34847. },
  34848. enumerable: true,
  34849. configurable: true
  34850. });
  34851. Object.defineProperty(Material, "LineLoopDrawMode", {
  34852. /**
  34853. * Returns the line loop draw mode
  34854. */
  34855. get: function () {
  34856. return Material._LineLoopDrawMode;
  34857. },
  34858. enumerable: true,
  34859. configurable: true
  34860. });
  34861. Object.defineProperty(Material, "LineStripDrawMode", {
  34862. /**
  34863. * Returns the line strip draw mode
  34864. */
  34865. get: function () {
  34866. return Material._LineStripDrawMode;
  34867. },
  34868. enumerable: true,
  34869. configurable: true
  34870. });
  34871. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34872. /**
  34873. * Returns the triangle strip draw mode
  34874. */
  34875. get: function () {
  34876. return Material._TriangleStripDrawMode;
  34877. },
  34878. enumerable: true,
  34879. configurable: true
  34880. });
  34881. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34882. /**
  34883. * Returns the triangle fan draw mode
  34884. */
  34885. get: function () {
  34886. return Material._TriangleFanDrawMode;
  34887. },
  34888. enumerable: true,
  34889. configurable: true
  34890. });
  34891. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34892. /**
  34893. * Returns the clock-wise side orientation
  34894. */
  34895. get: function () {
  34896. return Material._ClockWiseSideOrientation;
  34897. },
  34898. enumerable: true,
  34899. configurable: true
  34900. });
  34901. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34902. /**
  34903. * Returns the counter clock-wise side orientation
  34904. */
  34905. get: function () {
  34906. return Material._CounterClockWiseSideOrientation;
  34907. },
  34908. enumerable: true,
  34909. configurable: true
  34910. });
  34911. Object.defineProperty(Material.prototype, "alpha", {
  34912. /**
  34913. * Gets the alpha value of the material
  34914. */
  34915. get: function () {
  34916. return this._alpha;
  34917. },
  34918. /**
  34919. * Sets the alpha value of the material
  34920. */
  34921. set: function (value) {
  34922. if (this._alpha === value) {
  34923. return;
  34924. }
  34925. this._alpha = value;
  34926. this.markAsDirty(Material.MiscDirtyFlag);
  34927. },
  34928. enumerable: true,
  34929. configurable: true
  34930. });
  34931. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34932. /**
  34933. * Gets the back-face culling state
  34934. */
  34935. get: function () {
  34936. return this._backFaceCulling;
  34937. },
  34938. /**
  34939. * Sets the back-face culling state
  34940. */
  34941. set: function (value) {
  34942. if (this._backFaceCulling === value) {
  34943. return;
  34944. }
  34945. this._backFaceCulling = value;
  34946. this.markAsDirty(Material.TextureDirtyFlag);
  34947. },
  34948. enumerable: true,
  34949. configurable: true
  34950. });
  34951. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  34952. /**
  34953. * Gets a boolean indicating that current material needs to register RTT
  34954. */
  34955. get: function () {
  34956. return false;
  34957. },
  34958. enumerable: true,
  34959. configurable: true
  34960. });
  34961. Object.defineProperty(Material.prototype, "onDispose", {
  34962. /**
  34963. * Called during a dispose event
  34964. */
  34965. set: function (callback) {
  34966. if (this._onDisposeObserver) {
  34967. this.onDisposeObservable.remove(this._onDisposeObserver);
  34968. }
  34969. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34970. },
  34971. enumerable: true,
  34972. configurable: true
  34973. });
  34974. Object.defineProperty(Material.prototype, "onBindObservable", {
  34975. /**
  34976. * An event triggered when the material is bound
  34977. */
  34978. get: function () {
  34979. if (!this._onBindObservable) {
  34980. this._onBindObservable = new BABYLON.Observable();
  34981. }
  34982. return this._onBindObservable;
  34983. },
  34984. enumerable: true,
  34985. configurable: true
  34986. });
  34987. Object.defineProperty(Material.prototype, "onBind", {
  34988. /**
  34989. * Called during a bind event
  34990. */
  34991. set: function (callback) {
  34992. if (this._onBindObserver) {
  34993. this.onBindObservable.remove(this._onBindObserver);
  34994. }
  34995. this._onBindObserver = this.onBindObservable.add(callback);
  34996. },
  34997. enumerable: true,
  34998. configurable: true
  34999. });
  35000. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35001. /**
  35002. * An event triggered when the material is unbound
  35003. */
  35004. get: function () {
  35005. if (!this._onUnBindObservable) {
  35006. this._onUnBindObservable = new BABYLON.Observable();
  35007. }
  35008. return this._onUnBindObservable;
  35009. },
  35010. enumerable: true,
  35011. configurable: true
  35012. });
  35013. Object.defineProperty(Material.prototype, "alphaMode", {
  35014. /**
  35015. * Gets the value of the alpha mode
  35016. */
  35017. get: function () {
  35018. return this._alphaMode;
  35019. },
  35020. /**
  35021. * Sets the value of the alpha mode.
  35022. *
  35023. * | Value | Type | Description |
  35024. * | --- | --- | --- |
  35025. * | 0 | ALPHA_DISABLE | |
  35026. * | 1 | ALPHA_ADD | |
  35027. * | 2 | ALPHA_COMBINE | |
  35028. * | 3 | ALPHA_SUBTRACT | |
  35029. * | 4 | ALPHA_MULTIPLY | |
  35030. * | 5 | ALPHA_MAXIMIZED | |
  35031. * | 6 | ALPHA_ONEONE | |
  35032. * | 7 | ALPHA_PREMULTIPLIED | |
  35033. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35034. * | 9 | ALPHA_INTERPOLATE | |
  35035. * | 10 | ALPHA_SCREENMODE | |
  35036. *
  35037. */
  35038. set: function (value) {
  35039. if (this._alphaMode === value) {
  35040. return;
  35041. }
  35042. this._alphaMode = value;
  35043. this.markAsDirty(Material.TextureDirtyFlag);
  35044. },
  35045. enumerable: true,
  35046. configurable: true
  35047. });
  35048. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35049. /**
  35050. * Gets the depth pre-pass value
  35051. */
  35052. get: function () {
  35053. return this._needDepthPrePass;
  35054. },
  35055. /**
  35056. * Sets the need depth pre-pass value
  35057. */
  35058. set: function (value) {
  35059. if (this._needDepthPrePass === value) {
  35060. return;
  35061. }
  35062. this._needDepthPrePass = value;
  35063. if (this._needDepthPrePass) {
  35064. this.checkReadyOnEveryCall = true;
  35065. }
  35066. },
  35067. enumerable: true,
  35068. configurable: true
  35069. });
  35070. Object.defineProperty(Material.prototype, "fogEnabled", {
  35071. /**
  35072. * Gets the value of the fog enabled state
  35073. */
  35074. get: function () {
  35075. return this._fogEnabled;
  35076. },
  35077. /**
  35078. * Sets the state for enabling fog
  35079. */
  35080. set: function (value) {
  35081. if (this._fogEnabled === value) {
  35082. return;
  35083. }
  35084. this._fogEnabled = value;
  35085. this.markAsDirty(Material.MiscDirtyFlag);
  35086. },
  35087. enumerable: true,
  35088. configurable: true
  35089. });
  35090. Object.defineProperty(Material.prototype, "wireframe", {
  35091. /**
  35092. * Gets a value specifying if wireframe mode is enabled
  35093. */
  35094. get: function () {
  35095. switch (this._fillMode) {
  35096. case Material.WireFrameFillMode:
  35097. case Material.LineListDrawMode:
  35098. case Material.LineLoopDrawMode:
  35099. case Material.LineStripDrawMode:
  35100. return true;
  35101. }
  35102. return this._scene.forceWireframe;
  35103. },
  35104. /**
  35105. * Sets the state of wireframe mode
  35106. */
  35107. set: function (value) {
  35108. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35109. },
  35110. enumerable: true,
  35111. configurable: true
  35112. });
  35113. Object.defineProperty(Material.prototype, "pointsCloud", {
  35114. /**
  35115. * Gets the value specifying if point clouds are enabled
  35116. */
  35117. get: function () {
  35118. switch (this._fillMode) {
  35119. case Material.PointFillMode:
  35120. case Material.PointListDrawMode:
  35121. return true;
  35122. }
  35123. return this._scene.forcePointsCloud;
  35124. },
  35125. /**
  35126. * Sets the state of point cloud mode
  35127. */
  35128. set: function (value) {
  35129. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35130. },
  35131. enumerable: true,
  35132. configurable: true
  35133. });
  35134. Object.defineProperty(Material.prototype, "fillMode", {
  35135. /**
  35136. * Gets the material fill mode
  35137. */
  35138. get: function () {
  35139. return this._fillMode;
  35140. },
  35141. /**
  35142. * Sets the material fill mode
  35143. */
  35144. set: function (value) {
  35145. if (this._fillMode === value) {
  35146. return;
  35147. }
  35148. this._fillMode = value;
  35149. this.markAsDirty(Material.MiscDirtyFlag);
  35150. },
  35151. enumerable: true,
  35152. configurable: true
  35153. });
  35154. /**
  35155. * Returns a string representation of the current material
  35156. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35157. * @returns a string with material information
  35158. */
  35159. Material.prototype.toString = function (fullDetails) {
  35160. var ret = "Name: " + this.name;
  35161. if (fullDetails) {
  35162. }
  35163. return ret;
  35164. };
  35165. /**
  35166. * Gets the class name of the material
  35167. * @returns a string with the class name of the material
  35168. */
  35169. Material.prototype.getClassName = function () {
  35170. return "Material";
  35171. };
  35172. Object.defineProperty(Material.prototype, "isFrozen", {
  35173. /**
  35174. * Specifies if updates for the material been locked
  35175. */
  35176. get: function () {
  35177. return this.checkReadyOnlyOnce;
  35178. },
  35179. enumerable: true,
  35180. configurable: true
  35181. });
  35182. /**
  35183. * Locks updates for the material
  35184. */
  35185. Material.prototype.freeze = function () {
  35186. this.checkReadyOnlyOnce = true;
  35187. };
  35188. /**
  35189. * Unlocks updates for the material
  35190. */
  35191. Material.prototype.unfreeze = function () {
  35192. this.checkReadyOnlyOnce = false;
  35193. };
  35194. /**
  35195. * Specifies if the material is ready to be used
  35196. * @param mesh defines the mesh to check
  35197. * @param useInstances specifies if instances should be used
  35198. * @returns a boolean indicating if the material is ready to be used
  35199. */
  35200. Material.prototype.isReady = function (mesh, useInstances) {
  35201. return true;
  35202. };
  35203. /**
  35204. * Specifies that the submesh is ready to be used
  35205. * @param mesh defines the mesh to check
  35206. * @param subMesh defines which submesh to check
  35207. * @param useInstances specifies that instances should be used
  35208. * @returns a boolean indicating that the submesh is ready or not
  35209. */
  35210. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35211. return false;
  35212. };
  35213. /**
  35214. * Returns the material effect
  35215. * @returns the effect associated with the material
  35216. */
  35217. Material.prototype.getEffect = function () {
  35218. return this._effect;
  35219. };
  35220. /**
  35221. * Returns the current scene
  35222. * @returns a Scene
  35223. */
  35224. Material.prototype.getScene = function () {
  35225. return this._scene;
  35226. };
  35227. /**
  35228. * Specifies if the material will require alpha blending
  35229. * @returns a boolean specifying if alpha blending is needed
  35230. */
  35231. Material.prototype.needAlphaBlending = function () {
  35232. return (this.alpha < 1.0);
  35233. };
  35234. /**
  35235. * Specifies if the mesh will require alpha blending
  35236. * @param mesh defines the mesh to check
  35237. * @returns a boolean specifying if alpha blending is needed for the mesh
  35238. */
  35239. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35240. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35241. };
  35242. /**
  35243. * Specifies if this material should be rendered in alpha test mode
  35244. * @returns a boolean specifying if an alpha test is needed.
  35245. */
  35246. Material.prototype.needAlphaTesting = function () {
  35247. return false;
  35248. };
  35249. /**
  35250. * Gets the texture used for the alpha test
  35251. * @returns the texture to use for alpha testing
  35252. */
  35253. Material.prototype.getAlphaTestTexture = function () {
  35254. return null;
  35255. };
  35256. /**
  35257. * Marks the material to indicate that it needs to be re-calculated
  35258. */
  35259. Material.prototype.markDirty = function () {
  35260. this._wasPreviouslyReady = false;
  35261. };
  35262. /** @hidden */
  35263. Material.prototype._preBind = function (effect, overrideOrientation) {
  35264. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35265. var engine = this._scene.getEngine();
  35266. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35267. var reverse = orientation === Material.ClockWiseSideOrientation;
  35268. engine.enableEffect(effect ? effect : this._effect);
  35269. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35270. return reverse;
  35271. };
  35272. /**
  35273. * Binds the material to the mesh
  35274. * @param world defines the world transformation matrix
  35275. * @param mesh defines the mesh to bind the material to
  35276. */
  35277. Material.prototype.bind = function (world, mesh) {
  35278. };
  35279. /**
  35280. * Binds the submesh to the material
  35281. * @param world defines the world transformation matrix
  35282. * @param mesh defines the mesh containing the submesh
  35283. * @param subMesh defines the submesh to bind the material to
  35284. */
  35285. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35286. };
  35287. /**
  35288. * Binds the world matrix to the material
  35289. * @param world defines the world transformation matrix
  35290. */
  35291. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35292. };
  35293. /**
  35294. * Binds the scene's uniform buffer to the effect.
  35295. * @param effect defines the effect to bind to the scene uniform buffer
  35296. * @param sceneUbo defines the uniform buffer storing scene data
  35297. */
  35298. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35299. sceneUbo.bindToEffect(effect, "Scene");
  35300. };
  35301. /**
  35302. * Binds the view matrix to the effect
  35303. * @param effect defines the effect to bind the view matrix to
  35304. */
  35305. Material.prototype.bindView = function (effect) {
  35306. if (!this._useUBO) {
  35307. effect.setMatrix("view", this.getScene().getViewMatrix());
  35308. }
  35309. else {
  35310. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35311. }
  35312. };
  35313. /**
  35314. * Binds the view projection matrix to the effect
  35315. * @param effect defines the effect to bind the view projection matrix to
  35316. */
  35317. Material.prototype.bindViewProjection = function (effect) {
  35318. if (!this._useUBO) {
  35319. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35320. }
  35321. else {
  35322. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35323. }
  35324. };
  35325. /**
  35326. * Specifies if material alpha testing should be turned on for the mesh
  35327. * @param mesh defines the mesh to check
  35328. */
  35329. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35330. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35331. };
  35332. /**
  35333. * Processes to execute after binding the material to a mesh
  35334. * @param mesh defines the rendered mesh
  35335. */
  35336. Material.prototype._afterBind = function (mesh) {
  35337. this._scene._cachedMaterial = this;
  35338. if (mesh) {
  35339. this._scene._cachedVisibility = mesh.visibility;
  35340. }
  35341. else {
  35342. this._scene._cachedVisibility = 1;
  35343. }
  35344. if (this._onBindObservable && mesh) {
  35345. this._onBindObservable.notifyObservers(mesh);
  35346. }
  35347. if (this.disableDepthWrite) {
  35348. var engine = this._scene.getEngine();
  35349. this._cachedDepthWriteState = engine.getDepthWrite();
  35350. engine.setDepthWrite(false);
  35351. }
  35352. };
  35353. /**
  35354. * Unbinds the material from the mesh
  35355. */
  35356. Material.prototype.unbind = function () {
  35357. if (this._onUnBindObservable) {
  35358. this._onUnBindObservable.notifyObservers(this);
  35359. }
  35360. if (this.disableDepthWrite) {
  35361. var engine = this._scene.getEngine();
  35362. engine.setDepthWrite(this._cachedDepthWriteState);
  35363. }
  35364. };
  35365. /**
  35366. * Gets the active textures from the material
  35367. * @returns an array of textures
  35368. */
  35369. Material.prototype.getActiveTextures = function () {
  35370. return [];
  35371. };
  35372. /**
  35373. * Specifies if the material uses a texture
  35374. * @param texture defines the texture to check against the material
  35375. * @returns a boolean specifying if the material uses the texture
  35376. */
  35377. Material.prototype.hasTexture = function (texture) {
  35378. return false;
  35379. };
  35380. /**
  35381. * Makes a duplicate of the material, and gives it a new name
  35382. * @param name defines the new name for the duplicated material
  35383. * @returns the cloned material
  35384. */
  35385. Material.prototype.clone = function (name) {
  35386. return null;
  35387. };
  35388. /**
  35389. * Gets the meshes bound to the material
  35390. * @returns an array of meshes bound to the material
  35391. */
  35392. Material.prototype.getBindedMeshes = function () {
  35393. var result = new Array();
  35394. for (var index = 0; index < this._scene.meshes.length; index++) {
  35395. var mesh = this._scene.meshes[index];
  35396. if (mesh.material === this) {
  35397. result.push(mesh);
  35398. }
  35399. }
  35400. return result;
  35401. };
  35402. /**
  35403. * Force shader compilation
  35404. * @param mesh defines the mesh associated with this material
  35405. * @param onCompiled defines a function to execute once the material is compiled
  35406. * @param options defines the options to configure the compilation
  35407. */
  35408. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35409. var _this = this;
  35410. var localOptions = __assign({ clipPlane: false }, options);
  35411. var subMesh = new BABYLON.BaseSubMesh();
  35412. var scene = this.getScene();
  35413. var checkReady = function () {
  35414. if (!_this._scene || !_this._scene.getEngine()) {
  35415. return;
  35416. }
  35417. if (subMesh._materialDefines) {
  35418. subMesh._materialDefines._renderId = -1;
  35419. }
  35420. var clipPlaneState = scene.clipPlane;
  35421. if (localOptions.clipPlane) {
  35422. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35423. }
  35424. if (_this.storeEffectOnSubMeshes) {
  35425. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35426. if (onCompiled) {
  35427. onCompiled(_this);
  35428. }
  35429. }
  35430. else {
  35431. setTimeout(checkReady, 16);
  35432. }
  35433. }
  35434. else {
  35435. if (_this.isReady(mesh)) {
  35436. if (onCompiled) {
  35437. onCompiled(_this);
  35438. }
  35439. }
  35440. else {
  35441. setTimeout(checkReady, 16);
  35442. }
  35443. }
  35444. if (localOptions.clipPlane) {
  35445. scene.clipPlane = clipPlaneState;
  35446. }
  35447. };
  35448. checkReady();
  35449. };
  35450. /**
  35451. * Force shader compilation
  35452. * @param mesh defines the mesh that will use this material
  35453. * @param options defines additional options for compiling the shaders
  35454. * @returns a promise that resolves when the compilation completes
  35455. */
  35456. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35457. var _this = this;
  35458. return new Promise(function (resolve) {
  35459. _this.forceCompilation(mesh, function () {
  35460. resolve();
  35461. }, options);
  35462. });
  35463. };
  35464. /**
  35465. * Marks a define in the material to indicate that it needs to be re-computed
  35466. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35467. */
  35468. Material.prototype.markAsDirty = function (flag) {
  35469. if (flag & Material.TextureDirtyFlag) {
  35470. this._markAllSubMeshesAsTexturesDirty();
  35471. }
  35472. if (flag & Material.LightDirtyFlag) {
  35473. this._markAllSubMeshesAsLightsDirty();
  35474. }
  35475. if (flag & Material.FresnelDirtyFlag) {
  35476. this._markAllSubMeshesAsFresnelDirty();
  35477. }
  35478. if (flag & Material.AttributesDirtyFlag) {
  35479. this._markAllSubMeshesAsAttributesDirty();
  35480. }
  35481. if (flag & Material.MiscDirtyFlag) {
  35482. this._markAllSubMeshesAsMiscDirty();
  35483. }
  35484. this.getScene().resetCachedMaterial();
  35485. };
  35486. /**
  35487. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35488. * @param func defines a function which checks material defines against the submeshes
  35489. */
  35490. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35491. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35492. var mesh = _a[_i];
  35493. if (!mesh.subMeshes) {
  35494. continue;
  35495. }
  35496. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35497. var subMesh = _c[_b];
  35498. if (subMesh.getMaterial() !== this) {
  35499. continue;
  35500. }
  35501. if (!subMesh._materialDefines) {
  35502. continue;
  35503. }
  35504. func(subMesh._materialDefines);
  35505. }
  35506. }
  35507. };
  35508. /**
  35509. * Indicates that image processing needs to be re-calculated for all submeshes
  35510. */
  35511. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35512. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35513. };
  35514. /**
  35515. * Indicates that textures need to be re-calculated for all submeshes
  35516. */
  35517. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35518. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35519. };
  35520. /**
  35521. * Indicates that fresnel needs to be re-calculated for all submeshes
  35522. */
  35523. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35524. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35525. };
  35526. /**
  35527. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35528. */
  35529. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35530. this._markAllSubMeshesAsDirty(function (defines) {
  35531. defines.markAsFresnelDirty();
  35532. defines.markAsMiscDirty();
  35533. });
  35534. };
  35535. /**
  35536. * Indicates that lights need to be re-calculated for all submeshes
  35537. */
  35538. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35539. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35540. };
  35541. /**
  35542. * Indicates that attributes need to be re-calculated for all submeshes
  35543. */
  35544. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35545. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35546. };
  35547. /**
  35548. * Indicates that misc needs to be re-calculated for all submeshes
  35549. */
  35550. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35551. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35552. };
  35553. /**
  35554. * Indicates that textures and misc need to be re-calculated for all submeshes
  35555. */
  35556. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35557. this._markAllSubMeshesAsDirty(function (defines) {
  35558. defines.markAsTexturesDirty();
  35559. defines.markAsMiscDirty();
  35560. });
  35561. };
  35562. /**
  35563. * Disposes the material
  35564. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35565. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35566. */
  35567. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35568. // Animations
  35569. this.getScene().stopAnimation(this);
  35570. this.getScene().freeProcessedMaterials();
  35571. // Remove from scene
  35572. var index = this._scene.materials.indexOf(this);
  35573. if (index >= 0) {
  35574. this._scene.materials.splice(index, 1);
  35575. }
  35576. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  35577. // Remove from meshes
  35578. for (index = 0; index < this._scene.meshes.length; index++) {
  35579. var mesh = this._scene.meshes[index];
  35580. if (mesh.material === this) {
  35581. mesh.material = null;
  35582. if (mesh.geometry) {
  35583. var geometry = (mesh.geometry);
  35584. if (this.storeEffectOnSubMeshes) {
  35585. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35586. var subMesh = _a[_i];
  35587. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35588. if (forceDisposeEffect && subMesh._materialEffect) {
  35589. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35590. }
  35591. }
  35592. }
  35593. else {
  35594. geometry._releaseVertexArrayObject(this._effect);
  35595. }
  35596. }
  35597. }
  35598. }
  35599. this._uniformBuffer.dispose();
  35600. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35601. if (forceDisposeEffect && this._effect) {
  35602. if (!this.storeEffectOnSubMeshes) {
  35603. this._scene.getEngine()._releaseEffect(this._effect);
  35604. }
  35605. this._effect = null;
  35606. }
  35607. // Callback
  35608. this.onDisposeObservable.notifyObservers(this);
  35609. this.onDisposeObservable.clear();
  35610. if (this._onBindObservable) {
  35611. this._onBindObservable.clear();
  35612. }
  35613. if (this._onUnBindObservable) {
  35614. this._onUnBindObservable.clear();
  35615. }
  35616. };
  35617. /**
  35618. * Serializes this material
  35619. * @returns the serialized material object
  35620. */
  35621. Material.prototype.serialize = function () {
  35622. return BABYLON.SerializationHelper.Serialize(this);
  35623. };
  35624. /**
  35625. * Creates a MultiMaterial from parsed MultiMaterial data.
  35626. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35627. * @param scene defines the hosting scene
  35628. * @returns a new MultiMaterial
  35629. */
  35630. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35631. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35632. multiMaterial.id = parsedMultiMaterial.id;
  35633. if (BABYLON.Tags) {
  35634. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35635. }
  35636. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35637. var subMatId = parsedMultiMaterial.materials[matIndex];
  35638. if (subMatId) {
  35639. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35640. }
  35641. else {
  35642. multiMaterial.subMaterials.push(null);
  35643. }
  35644. }
  35645. return multiMaterial;
  35646. };
  35647. /**
  35648. * Creates a material from parsed material data
  35649. * @param parsedMaterial defines parsed material data
  35650. * @param scene defines the hosting scene
  35651. * @param rootUrl defines the root URL to use to load textures
  35652. * @returns a new material
  35653. */
  35654. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35655. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35656. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35657. }
  35658. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35659. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35660. if (!BABYLON.LegacyPBRMaterial) {
  35661. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35662. return;
  35663. }
  35664. }
  35665. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35666. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35667. };
  35668. // Triangle views
  35669. Material._TriangleFillMode = 0;
  35670. Material._WireFrameFillMode = 1;
  35671. Material._PointFillMode = 2;
  35672. // Draw modes
  35673. Material._PointListDrawMode = 3;
  35674. Material._LineListDrawMode = 4;
  35675. Material._LineLoopDrawMode = 5;
  35676. Material._LineStripDrawMode = 6;
  35677. Material._TriangleStripDrawMode = 7;
  35678. Material._TriangleFanDrawMode = 8;
  35679. /**
  35680. * Stores the clock-wise side orientation
  35681. */
  35682. Material._ClockWiseSideOrientation = 0;
  35683. /**
  35684. * Stores the counter clock-wise side orientation
  35685. */
  35686. Material._CounterClockWiseSideOrientation = 1;
  35687. /**
  35688. * The dirty texture flag value
  35689. */
  35690. Material.TextureDirtyFlag = 1;
  35691. /**
  35692. * The dirty light flag value
  35693. */
  35694. Material.LightDirtyFlag = 2;
  35695. /**
  35696. * The dirty fresnel flag value
  35697. */
  35698. Material.FresnelDirtyFlag = 4;
  35699. /**
  35700. * The dirty attribute flag value
  35701. */
  35702. Material.AttributesDirtyFlag = 8;
  35703. /**
  35704. * The dirty misc flag value
  35705. */
  35706. Material.MiscDirtyFlag = 16;
  35707. /**
  35708. * The all dirty flag value
  35709. */
  35710. Material.AllDirtyFlag = 31;
  35711. __decorate([
  35712. BABYLON.serialize()
  35713. ], Material.prototype, "id", void 0);
  35714. __decorate([
  35715. BABYLON.serialize()
  35716. ], Material.prototype, "uniqueId", void 0);
  35717. __decorate([
  35718. BABYLON.serialize()
  35719. ], Material.prototype, "name", void 0);
  35720. __decorate([
  35721. BABYLON.serialize()
  35722. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35723. __decorate([
  35724. BABYLON.serialize()
  35725. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35726. __decorate([
  35727. BABYLON.serialize()
  35728. ], Material.prototype, "state", void 0);
  35729. __decorate([
  35730. BABYLON.serialize("alpha")
  35731. ], Material.prototype, "_alpha", void 0);
  35732. __decorate([
  35733. BABYLON.serialize("backFaceCulling")
  35734. ], Material.prototype, "_backFaceCulling", void 0);
  35735. __decorate([
  35736. BABYLON.serialize()
  35737. ], Material.prototype, "sideOrientation", void 0);
  35738. __decorate([
  35739. BABYLON.serialize("alphaMode")
  35740. ], Material.prototype, "_alphaMode", void 0);
  35741. __decorate([
  35742. BABYLON.serialize()
  35743. ], Material.prototype, "_needDepthPrePass", void 0);
  35744. __decorate([
  35745. BABYLON.serialize()
  35746. ], Material.prototype, "disableDepthWrite", void 0);
  35747. __decorate([
  35748. BABYLON.serialize()
  35749. ], Material.prototype, "forceDepthWrite", void 0);
  35750. __decorate([
  35751. BABYLON.serialize()
  35752. ], Material.prototype, "separateCullingPass", void 0);
  35753. __decorate([
  35754. BABYLON.serialize("fogEnabled")
  35755. ], Material.prototype, "_fogEnabled", void 0);
  35756. __decorate([
  35757. BABYLON.serialize()
  35758. ], Material.prototype, "pointSize", void 0);
  35759. __decorate([
  35760. BABYLON.serialize()
  35761. ], Material.prototype, "zOffset", void 0);
  35762. __decorate([
  35763. BABYLON.serialize()
  35764. ], Material.prototype, "wireframe", null);
  35765. __decorate([
  35766. BABYLON.serialize()
  35767. ], Material.prototype, "pointsCloud", null);
  35768. __decorate([
  35769. BABYLON.serialize()
  35770. ], Material.prototype, "fillMode", null);
  35771. return Material;
  35772. }());
  35773. BABYLON.Material = Material;
  35774. })(BABYLON || (BABYLON = {}));
  35775. //# sourceMappingURL=babylon.material.js.map
  35776. var BABYLON;
  35777. (function (BABYLON) {
  35778. var UniformBuffer = /** @class */ (function () {
  35779. /**
  35780. * Uniform buffer objects.
  35781. *
  35782. * Handles blocks of uniform on the GPU.
  35783. *
  35784. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35785. *
  35786. * For more information, please refer to :
  35787. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35788. */
  35789. function UniformBuffer(engine, data, dynamic) {
  35790. this._engine = engine;
  35791. this._noUBO = !engine.supportsUniformBuffers;
  35792. this._dynamic = dynamic;
  35793. this._data = data || [];
  35794. this._uniformLocations = {};
  35795. this._uniformSizes = {};
  35796. this._uniformLocationPointer = 0;
  35797. this._needSync = false;
  35798. if (this._noUBO) {
  35799. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35800. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35801. this.updateFloat = this._updateFloatForEffect;
  35802. this.updateFloat2 = this._updateFloat2ForEffect;
  35803. this.updateFloat3 = this._updateFloat3ForEffect;
  35804. this.updateFloat4 = this._updateFloat4ForEffect;
  35805. this.updateMatrix = this._updateMatrixForEffect;
  35806. this.updateVector3 = this._updateVector3ForEffect;
  35807. this.updateVector4 = this._updateVector4ForEffect;
  35808. this.updateColor3 = this._updateColor3ForEffect;
  35809. this.updateColor4 = this._updateColor4ForEffect;
  35810. }
  35811. else {
  35812. this._engine._uniformBuffers.push(this);
  35813. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35814. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35815. this.updateFloat = this._updateFloatForUniform;
  35816. this.updateFloat2 = this._updateFloat2ForUniform;
  35817. this.updateFloat3 = this._updateFloat3ForUniform;
  35818. this.updateFloat4 = this._updateFloat4ForUniform;
  35819. this.updateMatrix = this._updateMatrixForUniform;
  35820. this.updateVector3 = this._updateVector3ForUniform;
  35821. this.updateVector4 = this._updateVector4ForUniform;
  35822. this.updateColor3 = this._updateColor3ForUniform;
  35823. this.updateColor4 = this._updateColor4ForUniform;
  35824. }
  35825. }
  35826. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35827. // Properties
  35828. /**
  35829. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35830. * or just falling back on setUniformXXX calls.
  35831. */
  35832. get: function () {
  35833. return !this._noUBO;
  35834. },
  35835. enumerable: true,
  35836. configurable: true
  35837. });
  35838. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35839. /**
  35840. * Indicates if the WebGL underlying uniform buffer is in sync
  35841. * with the javascript cache data.
  35842. */
  35843. get: function () {
  35844. return !this._needSync;
  35845. },
  35846. enumerable: true,
  35847. configurable: true
  35848. });
  35849. /**
  35850. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35851. * Also, a dynamic UniformBuffer will disable cache verification and always
  35852. * update the underlying WebGL uniform buffer to the GPU.
  35853. */
  35854. UniformBuffer.prototype.isDynamic = function () {
  35855. return this._dynamic !== undefined;
  35856. };
  35857. /**
  35858. * The data cache on JS side.
  35859. */
  35860. UniformBuffer.prototype.getData = function () {
  35861. return this._bufferData;
  35862. };
  35863. /**
  35864. * The underlying WebGL Uniform buffer.
  35865. */
  35866. UniformBuffer.prototype.getBuffer = function () {
  35867. return this._buffer;
  35868. };
  35869. /**
  35870. * std140 layout specifies how to align data within an UBO structure.
  35871. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35872. * for specs.
  35873. */
  35874. UniformBuffer.prototype._fillAlignment = function (size) {
  35875. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35876. // and 4x4 matrices
  35877. // TODO : change if other types are used
  35878. var alignment;
  35879. if (size <= 2) {
  35880. alignment = size;
  35881. }
  35882. else {
  35883. alignment = 4;
  35884. }
  35885. if ((this._uniformLocationPointer % alignment) !== 0) {
  35886. var oldPointer = this._uniformLocationPointer;
  35887. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35888. var diff = this._uniformLocationPointer - oldPointer;
  35889. for (var i = 0; i < diff; i++) {
  35890. this._data.push(0);
  35891. }
  35892. }
  35893. };
  35894. /**
  35895. * Adds an uniform in the buffer.
  35896. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35897. * for the layout to be correct !
  35898. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35899. * @param {number|number[]} size Data size, or data directly.
  35900. */
  35901. UniformBuffer.prototype.addUniform = function (name, size) {
  35902. if (this._noUBO) {
  35903. return;
  35904. }
  35905. if (this._uniformLocations[name] !== undefined) {
  35906. // Already existing uniform
  35907. return;
  35908. }
  35909. // This function must be called in the order of the shader layout !
  35910. // size can be the size of the uniform, or data directly
  35911. var data;
  35912. if (size instanceof Array) {
  35913. data = size;
  35914. size = data.length;
  35915. }
  35916. else {
  35917. size = size;
  35918. data = [];
  35919. // Fill with zeros
  35920. for (var i = 0; i < size; i++) {
  35921. data.push(0);
  35922. }
  35923. }
  35924. this._fillAlignment(size);
  35925. this._uniformSizes[name] = size;
  35926. this._uniformLocations[name] = this._uniformLocationPointer;
  35927. this._uniformLocationPointer += size;
  35928. for (var i = 0; i < size; i++) {
  35929. this._data.push(data[i]);
  35930. }
  35931. this._needSync = true;
  35932. };
  35933. /**
  35934. * Wrapper for addUniform.
  35935. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35936. * @param {Matrix} mat A 4x4 matrix.
  35937. */
  35938. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35939. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35940. };
  35941. /**
  35942. * Wrapper for addUniform.
  35943. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35944. * @param {number} x
  35945. * @param {number} y
  35946. */
  35947. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35948. var temp = [x, y];
  35949. this.addUniform(name, temp);
  35950. };
  35951. /**
  35952. * Wrapper for addUniform.
  35953. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35954. * @param {number} x
  35955. * @param {number} y
  35956. * @param {number} z
  35957. */
  35958. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35959. var temp = [x, y, z];
  35960. this.addUniform(name, temp);
  35961. };
  35962. /**
  35963. * Wrapper for addUniform.
  35964. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35965. * @param {Color3} color
  35966. */
  35967. UniformBuffer.prototype.addColor3 = function (name, color) {
  35968. var temp = new Array();
  35969. color.toArray(temp);
  35970. this.addUniform(name, temp);
  35971. };
  35972. /**
  35973. * Wrapper for addUniform.
  35974. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35975. * @param {Color3} color
  35976. * @param {number} alpha
  35977. */
  35978. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35979. var temp = new Array();
  35980. color.toArray(temp);
  35981. temp.push(alpha);
  35982. this.addUniform(name, temp);
  35983. };
  35984. /**
  35985. * Wrapper for addUniform.
  35986. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35987. * @param {Vector3} vector
  35988. */
  35989. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35990. var temp = new Array();
  35991. vector.toArray(temp);
  35992. this.addUniform(name, temp);
  35993. };
  35994. /**
  35995. * Wrapper for addUniform.
  35996. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35997. */
  35998. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35999. this.addUniform(name, 12);
  36000. };
  36001. /**
  36002. * Wrapper for addUniform.
  36003. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36004. */
  36005. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36006. this.addUniform(name, 8);
  36007. };
  36008. /**
  36009. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36010. */
  36011. UniformBuffer.prototype.create = function () {
  36012. if (this._noUBO) {
  36013. return;
  36014. }
  36015. if (this._buffer) {
  36016. return; // nothing to do
  36017. }
  36018. // See spec, alignment must be filled as a vec4
  36019. this._fillAlignment(4);
  36020. this._bufferData = new Float32Array(this._data);
  36021. this._rebuild();
  36022. this._needSync = true;
  36023. };
  36024. /** @hidden */
  36025. UniformBuffer.prototype._rebuild = function () {
  36026. if (this._noUBO) {
  36027. return;
  36028. }
  36029. if (this._dynamic) {
  36030. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36031. }
  36032. else {
  36033. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36034. }
  36035. };
  36036. /**
  36037. * Updates the WebGL Uniform Buffer on the GPU.
  36038. * If the `dynamic` flag is set to true, no cache comparison is done.
  36039. * Otherwise, the buffer will be updated only if the cache differs.
  36040. */
  36041. UniformBuffer.prototype.update = function () {
  36042. if (!this._buffer) {
  36043. this.create();
  36044. return;
  36045. }
  36046. if (!this._dynamic && !this._needSync) {
  36047. return;
  36048. }
  36049. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36050. this._needSync = false;
  36051. };
  36052. /**
  36053. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36054. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36055. * @param {number[]|Float32Array} data Flattened data
  36056. * @param {number} size Size of the data.
  36057. */
  36058. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36059. var location = this._uniformLocations[uniformName];
  36060. if (location === undefined) {
  36061. if (this._buffer) {
  36062. // Cannot add an uniform if the buffer is already created
  36063. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36064. return;
  36065. }
  36066. this.addUniform(uniformName, size);
  36067. location = this._uniformLocations[uniformName];
  36068. }
  36069. if (!this._buffer) {
  36070. this.create();
  36071. }
  36072. if (!this._dynamic) {
  36073. // Cache for static uniform buffers
  36074. var changed = false;
  36075. for (var i = 0; i < size; i++) {
  36076. if (this._bufferData[location + i] !== data[i]) {
  36077. changed = true;
  36078. this._bufferData[location + i] = data[i];
  36079. }
  36080. }
  36081. this._needSync = this._needSync || changed;
  36082. }
  36083. else {
  36084. // No cache for dynamic
  36085. for (var i = 0; i < size; i++) {
  36086. this._bufferData[location + i] = data[i];
  36087. }
  36088. }
  36089. };
  36090. // Update methods
  36091. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36092. // To match std140, matrix must be realigned
  36093. for (var i = 0; i < 3; i++) {
  36094. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36095. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36096. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36097. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36098. }
  36099. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36100. };
  36101. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36102. this._currentEffect.setMatrix3x3(name, matrix);
  36103. };
  36104. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36105. this._currentEffect.setMatrix2x2(name, matrix);
  36106. };
  36107. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36108. // To match std140, matrix must be realigned
  36109. for (var i = 0; i < 2; i++) {
  36110. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36111. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36112. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36113. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36114. }
  36115. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36116. };
  36117. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36118. this._currentEffect.setFloat(name, x);
  36119. };
  36120. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36121. UniformBuffer._tempBuffer[0] = x;
  36122. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36123. };
  36124. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36125. if (suffix === void 0) { suffix = ""; }
  36126. this._currentEffect.setFloat2(name + suffix, x, y);
  36127. };
  36128. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36129. if (suffix === void 0) { suffix = ""; }
  36130. UniformBuffer._tempBuffer[0] = x;
  36131. UniformBuffer._tempBuffer[1] = y;
  36132. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36133. };
  36134. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36135. if (suffix === void 0) { suffix = ""; }
  36136. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36137. };
  36138. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36139. if (suffix === void 0) { suffix = ""; }
  36140. UniformBuffer._tempBuffer[0] = x;
  36141. UniformBuffer._tempBuffer[1] = y;
  36142. UniformBuffer._tempBuffer[2] = z;
  36143. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36144. };
  36145. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36146. if (suffix === void 0) { suffix = ""; }
  36147. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36148. };
  36149. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36150. if (suffix === void 0) { suffix = ""; }
  36151. UniformBuffer._tempBuffer[0] = x;
  36152. UniformBuffer._tempBuffer[1] = y;
  36153. UniformBuffer._tempBuffer[2] = z;
  36154. UniformBuffer._tempBuffer[3] = w;
  36155. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36156. };
  36157. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36158. this._currentEffect.setMatrix(name, mat);
  36159. };
  36160. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36161. this.updateUniform(name, mat.toArray(), 16);
  36162. };
  36163. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36164. this._currentEffect.setVector3(name, vector);
  36165. };
  36166. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36167. vector.toArray(UniformBuffer._tempBuffer);
  36168. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36169. };
  36170. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36171. this._currentEffect.setVector4(name, vector);
  36172. };
  36173. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36174. vector.toArray(UniformBuffer._tempBuffer);
  36175. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36176. };
  36177. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36178. if (suffix === void 0) { suffix = ""; }
  36179. this._currentEffect.setColor3(name + suffix, color);
  36180. };
  36181. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36182. if (suffix === void 0) { suffix = ""; }
  36183. color.toArray(UniformBuffer._tempBuffer);
  36184. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36185. };
  36186. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36187. if (suffix === void 0) { suffix = ""; }
  36188. this._currentEffect.setColor4(name + suffix, color, alpha);
  36189. };
  36190. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36191. if (suffix === void 0) { suffix = ""; }
  36192. color.toArray(UniformBuffer._tempBuffer);
  36193. UniformBuffer._tempBuffer[3] = alpha;
  36194. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36195. };
  36196. /**
  36197. * Sets a sampler uniform on the effect.
  36198. * @param {string} name Name of the sampler.
  36199. * @param {Texture} texture
  36200. */
  36201. UniformBuffer.prototype.setTexture = function (name, texture) {
  36202. this._currentEffect.setTexture(name, texture);
  36203. };
  36204. /**
  36205. * Directly updates the value of the uniform in the cache AND on the GPU.
  36206. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36207. * @param {number[]|Float32Array} data Flattened data
  36208. */
  36209. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36210. this.updateUniform(uniformName, data, data.length);
  36211. this.update();
  36212. };
  36213. /**
  36214. * Binds this uniform buffer to an effect.
  36215. * @param {Effect} effect
  36216. * @param {string} name Name of the uniform block in the shader.
  36217. */
  36218. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36219. this._currentEffect = effect;
  36220. if (this._noUBO || !this._buffer) {
  36221. return;
  36222. }
  36223. effect.bindUniformBuffer(this._buffer, name);
  36224. };
  36225. /**
  36226. * Disposes the uniform buffer.
  36227. */
  36228. UniformBuffer.prototype.dispose = function () {
  36229. if (this._noUBO) {
  36230. return;
  36231. }
  36232. var index = this._engine._uniformBuffers.indexOf(this);
  36233. if (index !== -1) {
  36234. this._engine._uniformBuffers.splice(index, 1);
  36235. }
  36236. if (!this._buffer) {
  36237. return;
  36238. }
  36239. if (this._engine._releaseBuffer(this._buffer)) {
  36240. this._buffer = null;
  36241. }
  36242. };
  36243. // Pool for avoiding memory leaks
  36244. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36245. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36246. return UniformBuffer;
  36247. }());
  36248. BABYLON.UniformBuffer = UniformBuffer;
  36249. })(BABYLON || (BABYLON = {}));
  36250. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36251. var BABYLON;
  36252. (function (BABYLON) {
  36253. /**
  36254. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36255. */
  36256. var VertexData = /** @class */ (function () {
  36257. function VertexData() {
  36258. }
  36259. /**
  36260. * Uses the passed data array to set the set the values for the specified kind of data
  36261. * @param data a linear array of floating numbers
  36262. * @param kind the type of data that is being set, eg positions, colors etc
  36263. */
  36264. VertexData.prototype.set = function (data, kind) {
  36265. switch (kind) {
  36266. case BABYLON.VertexBuffer.PositionKind:
  36267. this.positions = data;
  36268. break;
  36269. case BABYLON.VertexBuffer.NormalKind:
  36270. this.normals = data;
  36271. break;
  36272. case BABYLON.VertexBuffer.TangentKind:
  36273. this.tangents = data;
  36274. break;
  36275. case BABYLON.VertexBuffer.UVKind:
  36276. this.uvs = data;
  36277. break;
  36278. case BABYLON.VertexBuffer.UV2Kind:
  36279. this.uvs2 = data;
  36280. break;
  36281. case BABYLON.VertexBuffer.UV3Kind:
  36282. this.uvs3 = data;
  36283. break;
  36284. case BABYLON.VertexBuffer.UV4Kind:
  36285. this.uvs4 = data;
  36286. break;
  36287. case BABYLON.VertexBuffer.UV5Kind:
  36288. this.uvs5 = data;
  36289. break;
  36290. case BABYLON.VertexBuffer.UV6Kind:
  36291. this.uvs6 = data;
  36292. break;
  36293. case BABYLON.VertexBuffer.ColorKind:
  36294. this.colors = data;
  36295. break;
  36296. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36297. this.matricesIndices = data;
  36298. break;
  36299. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36300. this.matricesWeights = data;
  36301. break;
  36302. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36303. this.matricesIndicesExtra = data;
  36304. break;
  36305. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36306. this.matricesWeightsExtra = data;
  36307. break;
  36308. }
  36309. };
  36310. /**
  36311. * Associates the vertexData to the passed Mesh.
  36312. * Sets it as updatable or not (default `false`)
  36313. * @param mesh the mesh the vertexData is applied to
  36314. * @param updatable when used and having the value true allows new data to update the vertexData
  36315. * @returns the VertexData
  36316. */
  36317. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36318. this._applyTo(mesh, updatable);
  36319. return this;
  36320. };
  36321. /**
  36322. * Associates the vertexData to the passed Geometry.
  36323. * Sets it as updatable or not (default `false`)
  36324. * @param geometry the geometry the vertexData is applied to
  36325. * @param updatable when used and having the value true allows new data to update the vertexData
  36326. * @returns VertexData
  36327. */
  36328. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36329. this._applyTo(geometry, updatable);
  36330. return this;
  36331. };
  36332. /**
  36333. * Updates the associated mesh
  36334. * @param mesh the mesh to be updated
  36335. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36336. * @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
  36337. * @returns VertexData
  36338. */
  36339. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36340. this._update(mesh);
  36341. return this;
  36342. };
  36343. /**
  36344. * Updates the associated geometry
  36345. * @param geometry the geometry to be updated
  36346. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36347. * @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
  36348. * @returns VertexData.
  36349. */
  36350. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36351. this._update(geometry);
  36352. return this;
  36353. };
  36354. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36355. if (updatable === void 0) { updatable = false; }
  36356. if (this.positions) {
  36357. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36358. }
  36359. if (this.normals) {
  36360. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36361. }
  36362. if (this.tangents) {
  36363. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36364. }
  36365. if (this.uvs) {
  36366. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36367. }
  36368. if (this.uvs2) {
  36369. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36370. }
  36371. if (this.uvs3) {
  36372. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36373. }
  36374. if (this.uvs4) {
  36375. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36376. }
  36377. if (this.uvs5) {
  36378. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36379. }
  36380. if (this.uvs6) {
  36381. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36382. }
  36383. if (this.colors) {
  36384. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36385. }
  36386. if (this.matricesIndices) {
  36387. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36388. }
  36389. if (this.matricesWeights) {
  36390. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36391. }
  36392. if (this.matricesIndicesExtra) {
  36393. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36394. }
  36395. if (this.matricesWeightsExtra) {
  36396. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36397. }
  36398. if (this.indices) {
  36399. meshOrGeometry.setIndices(this.indices, null, updatable);
  36400. }
  36401. else {
  36402. meshOrGeometry.setIndices([], null);
  36403. }
  36404. return this;
  36405. };
  36406. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36407. if (this.positions) {
  36408. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36409. }
  36410. if (this.normals) {
  36411. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36412. }
  36413. if (this.tangents) {
  36414. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36415. }
  36416. if (this.uvs) {
  36417. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36418. }
  36419. if (this.uvs2) {
  36420. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36421. }
  36422. if (this.uvs3) {
  36423. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36424. }
  36425. if (this.uvs4) {
  36426. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36427. }
  36428. if (this.uvs5) {
  36429. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36430. }
  36431. if (this.uvs6) {
  36432. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36433. }
  36434. if (this.colors) {
  36435. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36436. }
  36437. if (this.matricesIndices) {
  36438. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36439. }
  36440. if (this.matricesWeights) {
  36441. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36442. }
  36443. if (this.matricesIndicesExtra) {
  36444. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36445. }
  36446. if (this.matricesWeightsExtra) {
  36447. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36448. }
  36449. if (this.indices) {
  36450. meshOrGeometry.setIndices(this.indices, null);
  36451. }
  36452. return this;
  36453. };
  36454. /**
  36455. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36456. * @param matrix the transforming matrix
  36457. * @returns the VertexData
  36458. */
  36459. VertexData.prototype.transform = function (matrix) {
  36460. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36461. var transformed = BABYLON.Vector3.Zero();
  36462. var index;
  36463. if (this.positions) {
  36464. var position = BABYLON.Vector3.Zero();
  36465. for (index = 0; index < this.positions.length; index += 3) {
  36466. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36467. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36468. this.positions[index] = transformed.x;
  36469. this.positions[index + 1] = transformed.y;
  36470. this.positions[index + 2] = transformed.z;
  36471. }
  36472. }
  36473. if (this.normals) {
  36474. var normal = BABYLON.Vector3.Zero();
  36475. for (index = 0; index < this.normals.length; index += 3) {
  36476. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36477. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36478. this.normals[index] = transformed.x;
  36479. this.normals[index + 1] = transformed.y;
  36480. this.normals[index + 2] = transformed.z;
  36481. }
  36482. }
  36483. if (this.tangents) {
  36484. var tangent = BABYLON.Vector4.Zero();
  36485. var tangentTransformed = BABYLON.Vector4.Zero();
  36486. for (index = 0; index < this.tangents.length; index += 4) {
  36487. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36488. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36489. this.tangents[index] = tangentTransformed.x;
  36490. this.tangents[index + 1] = tangentTransformed.y;
  36491. this.tangents[index + 2] = tangentTransformed.z;
  36492. this.tangents[index + 3] = tangentTransformed.w;
  36493. }
  36494. }
  36495. if (flip && this.indices) {
  36496. for (index = 0; index < this.indices.length; index += 3) {
  36497. var tmp = this.indices[index + 1];
  36498. this.indices[index + 1] = this.indices[index + 2];
  36499. this.indices[index + 2] = tmp;
  36500. }
  36501. }
  36502. return this;
  36503. };
  36504. /**
  36505. * Merges the passed VertexData into the current one
  36506. * @param other the VertexData to be merged into the current one
  36507. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36508. * @returns the modified VertexData
  36509. */
  36510. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36511. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36512. this._validate();
  36513. other._validate();
  36514. if (!this.normals !== !other.normals ||
  36515. !this.tangents !== !other.tangents ||
  36516. !this.uvs !== !other.uvs ||
  36517. !this.uvs2 !== !other.uvs2 ||
  36518. !this.uvs3 !== !other.uvs3 ||
  36519. !this.uvs4 !== !other.uvs4 ||
  36520. !this.uvs5 !== !other.uvs5 ||
  36521. !this.uvs6 !== !other.uvs6 ||
  36522. !this.colors !== !other.colors ||
  36523. !this.matricesIndices !== !other.matricesIndices ||
  36524. !this.matricesWeights !== !other.matricesWeights ||
  36525. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36526. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36527. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36528. }
  36529. if (other.indices) {
  36530. if (!this.indices) {
  36531. this.indices = [];
  36532. }
  36533. var offset = this.positions ? this.positions.length / 3 : 0;
  36534. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36535. if (isSrcTypedArray) {
  36536. var len = this.indices.length + other.indices.length;
  36537. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36538. temp.set(this.indices);
  36539. var decal = this.indices.length;
  36540. for (var index = 0; index < other.indices.length; index++) {
  36541. temp[decal + index] = other.indices[index] + offset;
  36542. }
  36543. this.indices = temp;
  36544. }
  36545. else {
  36546. for (var index = 0; index < other.indices.length; index++) {
  36547. this.indices.push(other.indices[index] + offset);
  36548. }
  36549. }
  36550. }
  36551. this.positions = this._mergeElement(this.positions, other.positions);
  36552. this.normals = this._mergeElement(this.normals, other.normals);
  36553. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36554. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36555. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36556. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36557. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36558. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36559. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36560. this.colors = this._mergeElement(this.colors, other.colors);
  36561. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36562. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36563. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36564. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36565. return this;
  36566. };
  36567. VertexData.prototype._mergeElement = function (source, other) {
  36568. if (!source) {
  36569. return other;
  36570. }
  36571. if (!other) {
  36572. return source;
  36573. }
  36574. var len = other.length + source.length;
  36575. var isSrcTypedArray = source instanceof Float32Array;
  36576. var isOthTypedArray = other instanceof Float32Array;
  36577. // use non-loop method when the source is Float32Array
  36578. if (isSrcTypedArray) {
  36579. var ret32 = new Float32Array(len);
  36580. ret32.set(source);
  36581. ret32.set(other, source.length);
  36582. return ret32;
  36583. // source is number[], when other is also use concat
  36584. }
  36585. else if (!isOthTypedArray) {
  36586. return source.concat(other);
  36587. // source is a number[], but other is a Float32Array, loop required
  36588. }
  36589. else {
  36590. var ret = source.slice(0); // copy source to a separate array
  36591. for (var i = 0, len = other.length; i < len; i++) {
  36592. ret.push(other[i]);
  36593. }
  36594. return ret;
  36595. }
  36596. };
  36597. VertexData.prototype._validate = function () {
  36598. if (!this.positions) {
  36599. throw new Error("Positions are required");
  36600. }
  36601. var getElementCount = function (kind, values) {
  36602. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36603. if ((values.length % stride) !== 0) {
  36604. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36605. }
  36606. return values.length / stride;
  36607. };
  36608. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36609. var validateElementCount = function (kind, values) {
  36610. var elementCount = getElementCount(kind, values);
  36611. if (elementCount !== positionsElementCount) {
  36612. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36613. }
  36614. };
  36615. if (this.normals)
  36616. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36617. if (this.tangents)
  36618. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36619. if (this.uvs)
  36620. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36621. if (this.uvs2)
  36622. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36623. if (this.uvs3)
  36624. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36625. if (this.uvs4)
  36626. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36627. if (this.uvs5)
  36628. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36629. if (this.uvs6)
  36630. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36631. if (this.colors)
  36632. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36633. if (this.matricesIndices)
  36634. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36635. if (this.matricesWeights)
  36636. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36637. if (this.matricesIndicesExtra)
  36638. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36639. if (this.matricesWeightsExtra)
  36640. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36641. };
  36642. /**
  36643. * Serializes the VertexData
  36644. * @returns a serialized object
  36645. */
  36646. VertexData.prototype.serialize = function () {
  36647. var serializationObject = this.serialize();
  36648. if (this.positions) {
  36649. serializationObject.positions = this.positions;
  36650. }
  36651. if (this.normals) {
  36652. serializationObject.normals = this.normals;
  36653. }
  36654. if (this.tangents) {
  36655. serializationObject.tangents = this.tangents;
  36656. }
  36657. if (this.uvs) {
  36658. serializationObject.uvs = this.uvs;
  36659. }
  36660. if (this.uvs2) {
  36661. serializationObject.uvs2 = this.uvs2;
  36662. }
  36663. if (this.uvs3) {
  36664. serializationObject.uvs3 = this.uvs3;
  36665. }
  36666. if (this.uvs4) {
  36667. serializationObject.uvs4 = this.uvs4;
  36668. }
  36669. if (this.uvs5) {
  36670. serializationObject.uvs5 = this.uvs5;
  36671. }
  36672. if (this.uvs6) {
  36673. serializationObject.uvs6 = this.uvs6;
  36674. }
  36675. if (this.colors) {
  36676. serializationObject.colors = this.colors;
  36677. }
  36678. if (this.matricesIndices) {
  36679. serializationObject.matricesIndices = this.matricesIndices;
  36680. serializationObject.matricesIndices._isExpanded = true;
  36681. }
  36682. if (this.matricesWeights) {
  36683. serializationObject.matricesWeights = this.matricesWeights;
  36684. }
  36685. if (this.matricesIndicesExtra) {
  36686. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36687. serializationObject.matricesIndicesExtra._isExpanded = true;
  36688. }
  36689. if (this.matricesWeightsExtra) {
  36690. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36691. }
  36692. serializationObject.indices = this.indices;
  36693. return serializationObject;
  36694. };
  36695. // Statics
  36696. /**
  36697. * Extracts the vertexData from a mesh
  36698. * @param mesh the mesh from which to extract the VertexData
  36699. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36700. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36701. * @returns the object VertexData associated to the passed mesh
  36702. */
  36703. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36704. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36705. };
  36706. /**
  36707. * Extracts the vertexData from the geometry
  36708. * @param geometry the geometry from which to extract the VertexData
  36709. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36710. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36711. * @returns the object VertexData associated to the passed mesh
  36712. */
  36713. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36714. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36715. };
  36716. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36717. var result = new VertexData();
  36718. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36719. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36720. }
  36721. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36722. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36723. }
  36724. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36725. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36726. }
  36727. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36728. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36729. }
  36730. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36731. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36732. }
  36733. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36734. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36735. }
  36736. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36737. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36738. }
  36739. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36740. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36741. }
  36742. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36743. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36744. }
  36745. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36746. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36747. }
  36748. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36749. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36750. }
  36751. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36752. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36753. }
  36754. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36755. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36756. }
  36757. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36758. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36759. }
  36760. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36761. return result;
  36762. };
  36763. /**
  36764. * Creates the VertexData for a Ribbon
  36765. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36766. * * pathArray array of paths, each of which an array of successive Vector3
  36767. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36768. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36769. * * 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
  36770. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36771. * * 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)
  36772. * * 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)
  36773. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36774. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36775. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36776. * @returns the VertexData of the ribbon
  36777. */
  36778. VertexData.CreateRibbon = function (options) {
  36779. var pathArray = options.pathArray;
  36780. var closeArray = options.closeArray || false;
  36781. var closePath = options.closePath || false;
  36782. var invertUV = options.invertUV || false;
  36783. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36784. var offset = options.offset || defaultOffset;
  36785. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36786. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36787. var customUV = options.uvs;
  36788. var customColors = options.colors;
  36789. var positions = [];
  36790. var indices = [];
  36791. var normals = [];
  36792. var uvs = [];
  36793. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36794. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36795. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36796. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36797. var minlg; // minimal length among all paths from pathArray
  36798. var lg = []; // array of path lengths : nb of vertex per path
  36799. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36800. var p; // path iterator
  36801. var i; // point iterator
  36802. var j; // point iterator
  36803. // if single path in pathArray
  36804. if (pathArray.length < 2) {
  36805. var ar1 = [];
  36806. var ar2 = [];
  36807. for (i = 0; i < pathArray[0].length - offset; i++) {
  36808. ar1.push(pathArray[0][i]);
  36809. ar2.push(pathArray[0][i + offset]);
  36810. }
  36811. pathArray = [ar1, ar2];
  36812. }
  36813. // positions and horizontal distances (u)
  36814. var idc = 0;
  36815. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36816. var path;
  36817. var l;
  36818. minlg = pathArray[0].length;
  36819. var vectlg;
  36820. var dist;
  36821. for (p = 0; p < pathArray.length; p++) {
  36822. uTotalDistance[p] = 0;
  36823. us[p] = [0];
  36824. path = pathArray[p];
  36825. l = path.length;
  36826. minlg = (minlg < l) ? minlg : l;
  36827. j = 0;
  36828. while (j < l) {
  36829. positions.push(path[j].x, path[j].y, path[j].z);
  36830. if (j > 0) {
  36831. vectlg = path[j].subtract(path[j - 1]).length();
  36832. dist = vectlg + uTotalDistance[p];
  36833. us[p].push(dist);
  36834. uTotalDistance[p] = dist;
  36835. }
  36836. j++;
  36837. }
  36838. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36839. j--;
  36840. positions.push(path[0].x, path[0].y, path[0].z);
  36841. vectlg = path[j].subtract(path[0]).length();
  36842. dist = vectlg + uTotalDistance[p];
  36843. us[p].push(dist);
  36844. uTotalDistance[p] = dist;
  36845. }
  36846. lg[p] = l + closePathCorr;
  36847. idx[p] = idc;
  36848. idc += (l + closePathCorr);
  36849. }
  36850. // vertical distances (v)
  36851. var path1;
  36852. var path2;
  36853. var vertex1 = null;
  36854. var vertex2 = null;
  36855. for (i = 0; i < minlg + closePathCorr; i++) {
  36856. vTotalDistance[i] = 0;
  36857. vs[i] = [0];
  36858. for (p = 0; p < pathArray.length - 1; p++) {
  36859. path1 = pathArray[p];
  36860. path2 = pathArray[p + 1];
  36861. if (i === minlg) { // closePath
  36862. vertex1 = path1[0];
  36863. vertex2 = path2[0];
  36864. }
  36865. else {
  36866. vertex1 = path1[i];
  36867. vertex2 = path2[i];
  36868. }
  36869. vectlg = vertex2.subtract(vertex1).length();
  36870. dist = vectlg + vTotalDistance[i];
  36871. vs[i].push(dist);
  36872. vTotalDistance[i] = dist;
  36873. }
  36874. if (closeArray && vertex2 && vertex1) {
  36875. path1 = pathArray[p];
  36876. path2 = pathArray[0];
  36877. if (i === minlg) { // closePath
  36878. vertex2 = path2[0];
  36879. }
  36880. vectlg = vertex2.subtract(vertex1).length();
  36881. dist = vectlg + vTotalDistance[i];
  36882. vTotalDistance[i] = dist;
  36883. }
  36884. }
  36885. // uvs
  36886. var u;
  36887. var v;
  36888. if (customUV) {
  36889. for (p = 0; p < customUV.length; p++) {
  36890. uvs.push(customUV[p].x, customUV[p].y);
  36891. }
  36892. }
  36893. else {
  36894. for (p = 0; p < pathArray.length; p++) {
  36895. for (i = 0; i < minlg + closePathCorr; i++) {
  36896. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36897. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36898. if (invertUV) {
  36899. uvs.push(v, u);
  36900. }
  36901. else {
  36902. uvs.push(u, v);
  36903. }
  36904. }
  36905. }
  36906. }
  36907. // indices
  36908. p = 0; // path index
  36909. var pi = 0; // positions array index
  36910. var l1 = lg[p] - 1; // path1 length
  36911. var l2 = lg[p + 1] - 1; // path2 length
  36912. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36913. var shft = idx[1] - idx[0]; // shift
  36914. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36915. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36916. // 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
  36917. indices.push(pi, pi + shft, pi + 1);
  36918. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36919. pi += 1;
  36920. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36921. p++;
  36922. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36923. shft = idx[0] - idx[p];
  36924. l1 = lg[p] - 1;
  36925. l2 = lg[0] - 1;
  36926. }
  36927. else {
  36928. shft = idx[p + 1] - idx[p];
  36929. l1 = lg[p] - 1;
  36930. l2 = lg[p + 1] - 1;
  36931. }
  36932. pi = idx[p];
  36933. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36934. }
  36935. }
  36936. // normals
  36937. VertexData.ComputeNormals(positions, indices, normals);
  36938. if (closePath) { // update both the first and last vertex normals to their average value
  36939. var indexFirst = 0;
  36940. var indexLast = 0;
  36941. for (p = 0; p < pathArray.length; p++) {
  36942. indexFirst = idx[p] * 3;
  36943. if (p + 1 < pathArray.length) {
  36944. indexLast = (idx[p + 1] - 1) * 3;
  36945. }
  36946. else {
  36947. indexLast = normals.length - 3;
  36948. }
  36949. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36950. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36951. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36952. normals[indexLast] = normals[indexFirst];
  36953. normals[indexLast + 1] = normals[indexFirst + 1];
  36954. normals[indexLast + 2] = normals[indexFirst + 2];
  36955. }
  36956. }
  36957. // sides
  36958. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36959. // Colors
  36960. var colors = null;
  36961. if (customColors) {
  36962. colors = new Float32Array(customColors.length * 4);
  36963. for (var c = 0; c < customColors.length; c++) {
  36964. colors[c * 4] = customColors[c].r;
  36965. colors[c * 4 + 1] = customColors[c].g;
  36966. colors[c * 4 + 2] = customColors[c].b;
  36967. colors[c * 4 + 3] = customColors[c].a;
  36968. }
  36969. }
  36970. // Result
  36971. var vertexData = new VertexData();
  36972. var positions32 = new Float32Array(positions);
  36973. var normals32 = new Float32Array(normals);
  36974. var uvs32 = new Float32Array(uvs);
  36975. vertexData.indices = indices;
  36976. vertexData.positions = positions32;
  36977. vertexData.normals = normals32;
  36978. vertexData.uvs = uvs32;
  36979. if (colors) {
  36980. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36981. }
  36982. if (closePath) {
  36983. vertexData._idx = idx;
  36984. }
  36985. return vertexData;
  36986. };
  36987. /**
  36988. * Creates the VertexData for a box
  36989. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36990. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36991. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36992. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36993. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36994. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36995. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36996. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36997. * * 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)
  36998. * * 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)
  36999. * @returns the VertexData of the box
  37000. */
  37001. VertexData.CreateBox = function (options) {
  37002. var normalsSource = [
  37003. new BABYLON.Vector3(0, 0, 1),
  37004. new BABYLON.Vector3(0, 0, -1),
  37005. new BABYLON.Vector3(1, 0, 0),
  37006. new BABYLON.Vector3(-1, 0, 0),
  37007. new BABYLON.Vector3(0, 1, 0),
  37008. new BABYLON.Vector3(0, -1, 0)
  37009. ];
  37010. var indices = [];
  37011. var positions = [];
  37012. var normals = [];
  37013. var uvs = [];
  37014. var width = options.width || options.size || 1;
  37015. var height = options.height || options.size || 1;
  37016. var depth = options.depth || options.size || 1;
  37017. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37018. var faceUV = options.faceUV || new Array(6);
  37019. var faceColors = options.faceColors;
  37020. var colors = [];
  37021. // default face colors and UV if undefined
  37022. for (var f = 0; f < 6; f++) {
  37023. if (faceUV[f] === undefined) {
  37024. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37025. }
  37026. if (faceColors && faceColors[f] === undefined) {
  37027. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37028. }
  37029. }
  37030. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37031. // Create each face in turn.
  37032. for (var index = 0; index < normalsSource.length; index++) {
  37033. var normal = normalsSource[index];
  37034. // Get two vectors perpendicular to the face normal and to each other.
  37035. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37036. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37037. // Six indices (two triangles) per face.
  37038. var verticesLength = positions.length / 3;
  37039. indices.push(verticesLength);
  37040. indices.push(verticesLength + 1);
  37041. indices.push(verticesLength + 2);
  37042. indices.push(verticesLength);
  37043. indices.push(verticesLength + 2);
  37044. indices.push(verticesLength + 3);
  37045. // Four vertices per face.
  37046. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37047. positions.push(vertex.x, vertex.y, vertex.z);
  37048. normals.push(normal.x, normal.y, normal.z);
  37049. uvs.push(faceUV[index].z, faceUV[index].w);
  37050. if (faceColors) {
  37051. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37052. }
  37053. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37054. positions.push(vertex.x, vertex.y, vertex.z);
  37055. normals.push(normal.x, normal.y, normal.z);
  37056. uvs.push(faceUV[index].x, faceUV[index].w);
  37057. if (faceColors) {
  37058. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37059. }
  37060. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37061. positions.push(vertex.x, vertex.y, vertex.z);
  37062. normals.push(normal.x, normal.y, normal.z);
  37063. uvs.push(faceUV[index].x, faceUV[index].y);
  37064. if (faceColors) {
  37065. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37066. }
  37067. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37068. positions.push(vertex.x, vertex.y, vertex.z);
  37069. normals.push(normal.x, normal.y, normal.z);
  37070. uvs.push(faceUV[index].z, faceUV[index].y);
  37071. if (faceColors) {
  37072. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37073. }
  37074. }
  37075. // sides
  37076. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37077. // Result
  37078. var vertexData = new VertexData();
  37079. vertexData.indices = indices;
  37080. vertexData.positions = positions;
  37081. vertexData.normals = normals;
  37082. vertexData.uvs = uvs;
  37083. if (faceColors) {
  37084. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37085. vertexData.colors = totalColors;
  37086. }
  37087. return vertexData;
  37088. };
  37089. /**
  37090. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37091. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37092. * * segments sets the number of horizontal strips optional, default 32
  37093. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37094. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37095. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37096. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37097. * * 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
  37098. * * 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
  37099. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37100. * * 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)
  37101. * * 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)
  37102. * @returns the VertexData of the ellipsoid
  37103. */
  37104. VertexData.CreateSphere = function (options) {
  37105. var segments = options.segments || 32;
  37106. var diameterX = options.diameterX || options.diameter || 1;
  37107. var diameterY = options.diameterY || options.diameter || 1;
  37108. var diameterZ = options.diameterZ || options.diameter || 1;
  37109. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37110. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37111. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37112. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37113. var totalZRotationSteps = 2 + segments;
  37114. var totalYRotationSteps = 2 * totalZRotationSteps;
  37115. var indices = [];
  37116. var positions = [];
  37117. var normals = [];
  37118. var uvs = [];
  37119. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37120. var normalizedZ = zRotationStep / totalZRotationSteps;
  37121. var angleZ = normalizedZ * Math.PI * slice;
  37122. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37123. var normalizedY = yRotationStep / totalYRotationSteps;
  37124. var angleY = normalizedY * Math.PI * 2 * arc;
  37125. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37126. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37127. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37128. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37129. var vertex = complete.multiply(radius);
  37130. var normal = complete.divide(radius).normalize();
  37131. positions.push(vertex.x, vertex.y, vertex.z);
  37132. normals.push(normal.x, normal.y, normal.z);
  37133. uvs.push(normalizedY, normalizedZ);
  37134. }
  37135. if (zRotationStep > 0) {
  37136. var verticesCount = positions.length / 3;
  37137. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37138. indices.push((firstIndex));
  37139. indices.push((firstIndex + 1));
  37140. indices.push(firstIndex + totalYRotationSteps + 1);
  37141. indices.push((firstIndex + totalYRotationSteps + 1));
  37142. indices.push((firstIndex + 1));
  37143. indices.push((firstIndex + totalYRotationSteps + 2));
  37144. }
  37145. }
  37146. }
  37147. // Sides
  37148. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37149. // Result
  37150. var vertexData = new VertexData();
  37151. vertexData.indices = indices;
  37152. vertexData.positions = positions;
  37153. vertexData.normals = normals;
  37154. vertexData.uvs = uvs;
  37155. return vertexData;
  37156. };
  37157. /**
  37158. * Creates the VertexData for a cylinder, cone or prism
  37159. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37160. * * height sets the height (y direction) of the cylinder, optional, default 2
  37161. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37162. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37163. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37164. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37165. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37166. * * 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
  37167. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37168. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37169. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37170. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37171. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37172. * * 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)
  37173. * * 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)
  37174. * @returns the VertexData of the cylinder, cone or prism
  37175. */
  37176. VertexData.CreateCylinder = function (options) {
  37177. var height = options.height || 2;
  37178. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37179. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37180. var tessellation = options.tessellation || 24;
  37181. var subdivisions = options.subdivisions || 1;
  37182. var hasRings = options.hasRings ? true : false;
  37183. var enclose = options.enclose ? true : false;
  37184. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37185. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37186. var faceUV = options.faceUV || new Array(3);
  37187. var faceColors = options.faceColors;
  37188. // default face colors and UV if undefined
  37189. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37190. var ringNb = (hasRings) ? subdivisions : 1;
  37191. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37192. var f;
  37193. for (f = 0; f < surfaceNb; f++) {
  37194. if (faceColors && faceColors[f] === undefined) {
  37195. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37196. }
  37197. }
  37198. for (f = 0; f < surfaceNb; f++) {
  37199. if (faceUV && faceUV[f] === undefined) {
  37200. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37201. }
  37202. }
  37203. var indices = new Array();
  37204. var positions = new Array();
  37205. var normals = new Array();
  37206. var uvs = new Array();
  37207. var colors = new Array();
  37208. var angle_step = Math.PI * 2 * arc / tessellation;
  37209. var angle;
  37210. var h;
  37211. var radius;
  37212. var tan = (diameterBottom - diameterTop) / 2 / height;
  37213. var ringVertex = BABYLON.Vector3.Zero();
  37214. var ringNormal = BABYLON.Vector3.Zero();
  37215. var ringFirstVertex = BABYLON.Vector3.Zero();
  37216. var ringFirstNormal = BABYLON.Vector3.Zero();
  37217. var quadNormal = BABYLON.Vector3.Zero();
  37218. var Y = BABYLON.Axis.Y;
  37219. // positions, normals, uvs
  37220. var i;
  37221. var j;
  37222. var r;
  37223. var ringIdx = 1;
  37224. var s = 1; // surface index
  37225. var cs = 0;
  37226. var v = 0;
  37227. for (i = 0; i <= subdivisions; i++) {
  37228. h = i / subdivisions;
  37229. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37230. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37231. for (r = 0; r < ringIdx; r++) {
  37232. if (hasRings) {
  37233. s += r;
  37234. }
  37235. if (enclose) {
  37236. s += 2 * r;
  37237. }
  37238. for (j = 0; j <= tessellation; j++) {
  37239. angle = j * angle_step;
  37240. // position
  37241. ringVertex.x = Math.cos(-angle) * radius;
  37242. ringVertex.y = -height / 2 + h * height;
  37243. ringVertex.z = Math.sin(-angle) * radius;
  37244. // normal
  37245. if (diameterTop === 0 && i === subdivisions) {
  37246. // if no top cap, reuse former normals
  37247. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37248. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37249. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37250. }
  37251. else {
  37252. ringNormal.x = ringVertex.x;
  37253. ringNormal.z = ringVertex.z;
  37254. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37255. ringNormal.normalize();
  37256. }
  37257. // keep first ring vertex values for enclose
  37258. if (j === 0) {
  37259. ringFirstVertex.copyFrom(ringVertex);
  37260. ringFirstNormal.copyFrom(ringNormal);
  37261. }
  37262. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37263. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37264. if (hasRings) {
  37265. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37266. }
  37267. else {
  37268. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37269. }
  37270. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37271. if (faceColors) {
  37272. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37273. }
  37274. }
  37275. // if enclose, add four vertices and their dedicated normals
  37276. if (arc !== 1 && enclose) {
  37277. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37278. positions.push(0, ringVertex.y, 0);
  37279. positions.push(0, ringVertex.y, 0);
  37280. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37281. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37282. quadNormal.normalize();
  37283. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37284. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37285. quadNormal.normalize();
  37286. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37287. if (hasRings) {
  37288. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37289. }
  37290. else {
  37291. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37292. }
  37293. uvs.push(faceUV[s + 1].x, v);
  37294. uvs.push(faceUV[s + 1].z, v);
  37295. if (hasRings) {
  37296. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37297. }
  37298. else {
  37299. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37300. }
  37301. uvs.push(faceUV[s + 2].x, v);
  37302. uvs.push(faceUV[s + 2].z, v);
  37303. if (faceColors) {
  37304. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37305. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37306. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37307. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37308. }
  37309. }
  37310. if (cs !== s) {
  37311. cs = s;
  37312. }
  37313. }
  37314. }
  37315. // indices
  37316. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37317. var s;
  37318. i = 0;
  37319. for (s = 0; s < subdivisions; s++) {
  37320. var i0 = 0;
  37321. var i1 = 0;
  37322. var i2 = 0;
  37323. var i3 = 0;
  37324. for (j = 0; j < tessellation; j++) {
  37325. i0 = i * (e + 1) + j;
  37326. i1 = (i + 1) * (e + 1) + j;
  37327. i2 = i * (e + 1) + (j + 1);
  37328. i3 = (i + 1) * (e + 1) + (j + 1);
  37329. indices.push(i0, i1, i2);
  37330. indices.push(i3, i2, i1);
  37331. }
  37332. if (arc !== 1 && enclose) { // if enclose, add two quads
  37333. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37334. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37335. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37336. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37337. }
  37338. i = (hasRings) ? (i + 2) : (i + 1);
  37339. }
  37340. // Caps
  37341. var createCylinderCap = function (isTop) {
  37342. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37343. if (radius === 0) {
  37344. return;
  37345. }
  37346. // Cap positions, normals & uvs
  37347. var angle;
  37348. var circleVector;
  37349. var i;
  37350. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37351. var c = null;
  37352. if (faceColors) {
  37353. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37354. }
  37355. // cap center
  37356. var vbase = positions.length / 3;
  37357. var offset = isTop ? height / 2 : -height / 2;
  37358. var center = new BABYLON.Vector3(0, offset, 0);
  37359. positions.push(center.x, center.y, center.z);
  37360. normals.push(0, isTop ? 1 : -1, 0);
  37361. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37362. if (c) {
  37363. colors.push(c.r, c.g, c.b, c.a);
  37364. }
  37365. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37366. for (i = 0; i <= tessellation; i++) {
  37367. angle = Math.PI * 2 * i * arc / tessellation;
  37368. var cos = Math.cos(-angle);
  37369. var sin = Math.sin(-angle);
  37370. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37371. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37372. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37373. normals.push(0, isTop ? 1 : -1, 0);
  37374. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37375. if (c) {
  37376. colors.push(c.r, c.g, c.b, c.a);
  37377. }
  37378. }
  37379. // Cap indices
  37380. for (i = 0; i < tessellation; i++) {
  37381. if (!isTop) {
  37382. indices.push(vbase);
  37383. indices.push(vbase + (i + 1));
  37384. indices.push(vbase + (i + 2));
  37385. }
  37386. else {
  37387. indices.push(vbase);
  37388. indices.push(vbase + (i + 2));
  37389. indices.push(vbase + (i + 1));
  37390. }
  37391. }
  37392. };
  37393. // add caps to geometry
  37394. createCylinderCap(false);
  37395. createCylinderCap(true);
  37396. // Sides
  37397. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37398. var vertexData = new VertexData();
  37399. vertexData.indices = indices;
  37400. vertexData.positions = positions;
  37401. vertexData.normals = normals;
  37402. vertexData.uvs = uvs;
  37403. if (faceColors) {
  37404. vertexData.colors = colors;
  37405. }
  37406. return vertexData;
  37407. };
  37408. /**
  37409. * Creates the VertexData for a torus
  37410. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37411. * * diameter the diameter of the torus, optional default 1
  37412. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37413. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37414. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37415. * * 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)
  37416. * * 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)
  37417. * @returns the VertexData of the torus
  37418. */
  37419. VertexData.CreateTorus = function (options) {
  37420. var indices = [];
  37421. var positions = [];
  37422. var normals = [];
  37423. var uvs = [];
  37424. var diameter = options.diameter || 1;
  37425. var thickness = options.thickness || 0.5;
  37426. var tessellation = options.tessellation || 16;
  37427. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37428. var stride = tessellation + 1;
  37429. for (var i = 0; i <= tessellation; i++) {
  37430. var u = i / tessellation;
  37431. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37432. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37433. for (var j = 0; j <= tessellation; j++) {
  37434. var v = 1 - j / tessellation;
  37435. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37436. var dx = Math.cos(innerAngle);
  37437. var dy = Math.sin(innerAngle);
  37438. // Create a vertex.
  37439. var normal = new BABYLON.Vector3(dx, dy, 0);
  37440. var position = normal.scale(thickness / 2);
  37441. var textureCoordinate = new BABYLON.Vector2(u, v);
  37442. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37443. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37444. positions.push(position.x, position.y, position.z);
  37445. normals.push(normal.x, normal.y, normal.z);
  37446. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37447. // And create indices for two triangles.
  37448. var nextI = (i + 1) % stride;
  37449. var nextJ = (j + 1) % stride;
  37450. indices.push(i * stride + j);
  37451. indices.push(i * stride + nextJ);
  37452. indices.push(nextI * stride + j);
  37453. indices.push(i * stride + nextJ);
  37454. indices.push(nextI * stride + nextJ);
  37455. indices.push(nextI * stride + j);
  37456. }
  37457. }
  37458. // Sides
  37459. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37460. // Result
  37461. var vertexData = new VertexData();
  37462. vertexData.indices = indices;
  37463. vertexData.positions = positions;
  37464. vertexData.normals = normals;
  37465. vertexData.uvs = uvs;
  37466. return vertexData;
  37467. };
  37468. /**
  37469. * Creates the VertexData of the LineSystem
  37470. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37471. * - lines an array of lines, each line being an array of successive Vector3
  37472. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37473. * @returns the VertexData of the LineSystem
  37474. */
  37475. VertexData.CreateLineSystem = function (options) {
  37476. var indices = [];
  37477. var positions = [];
  37478. var lines = options.lines;
  37479. var colors = options.colors;
  37480. var vertexColors = [];
  37481. var idx = 0;
  37482. for (var l = 0; l < lines.length; l++) {
  37483. var points = lines[l];
  37484. for (var index = 0; index < points.length; index++) {
  37485. positions.push(points[index].x, points[index].y, points[index].z);
  37486. if (colors) {
  37487. var color = colors[l];
  37488. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37489. }
  37490. if (index > 0) {
  37491. indices.push(idx - 1);
  37492. indices.push(idx);
  37493. }
  37494. idx++;
  37495. }
  37496. }
  37497. var vertexData = new VertexData();
  37498. vertexData.indices = indices;
  37499. vertexData.positions = positions;
  37500. if (colors) {
  37501. vertexData.colors = vertexColors;
  37502. }
  37503. return vertexData;
  37504. };
  37505. /**
  37506. * Create the VertexData for a DashedLines
  37507. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37508. * - points an array successive Vector3
  37509. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37510. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37511. * - dashNb the intended total number of dashes, optional, default 200
  37512. * @returns the VertexData for the DashedLines
  37513. */
  37514. VertexData.CreateDashedLines = function (options) {
  37515. var dashSize = options.dashSize || 3;
  37516. var gapSize = options.gapSize || 1;
  37517. var dashNb = options.dashNb || 200;
  37518. var points = options.points;
  37519. var positions = new Array();
  37520. var indices = new Array();
  37521. var curvect = BABYLON.Vector3.Zero();
  37522. var lg = 0;
  37523. var nb = 0;
  37524. var shft = 0;
  37525. var dashshft = 0;
  37526. var curshft = 0;
  37527. var idx = 0;
  37528. var i = 0;
  37529. for (i = 0; i < points.length - 1; i++) {
  37530. points[i + 1].subtractToRef(points[i], curvect);
  37531. lg += curvect.length();
  37532. }
  37533. shft = lg / dashNb;
  37534. dashshft = dashSize * shft / (dashSize + gapSize);
  37535. for (i = 0; i < points.length - 1; i++) {
  37536. points[i + 1].subtractToRef(points[i], curvect);
  37537. nb = Math.floor(curvect.length() / shft);
  37538. curvect.normalize();
  37539. for (var j = 0; j < nb; j++) {
  37540. curshft = shft * j;
  37541. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37542. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37543. indices.push(idx, idx + 1);
  37544. idx += 2;
  37545. }
  37546. }
  37547. // Result
  37548. var vertexData = new VertexData();
  37549. vertexData.positions = positions;
  37550. vertexData.indices = indices;
  37551. return vertexData;
  37552. };
  37553. /**
  37554. * Creates the VertexData for a Ground
  37555. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37556. * - width the width (x direction) of the ground, optional, default 1
  37557. * - height the height (z direction) of the ground, optional, default 1
  37558. * - subdivisions the number of subdivisions per side, optional, default 1
  37559. * @returns the VertexData of the Ground
  37560. */
  37561. VertexData.CreateGround = function (options) {
  37562. var indices = [];
  37563. var positions = [];
  37564. var normals = [];
  37565. var uvs = [];
  37566. var row, col;
  37567. var width = options.width || 1;
  37568. var height = options.height || 1;
  37569. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37570. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37571. for (row = 0; row <= subdivisionsY; row++) {
  37572. for (col = 0; col <= subdivisionsX; col++) {
  37573. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37574. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37575. positions.push(position.x, position.y, position.z);
  37576. normals.push(normal.x, normal.y, normal.z);
  37577. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37578. }
  37579. }
  37580. for (row = 0; row < subdivisionsY; row++) {
  37581. for (col = 0; col < subdivisionsX; col++) {
  37582. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37583. indices.push(col + 1 + row * (subdivisionsX + 1));
  37584. indices.push(col + row * (subdivisionsX + 1));
  37585. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37586. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37587. indices.push(col + row * (subdivisionsX + 1));
  37588. }
  37589. }
  37590. // Result
  37591. var vertexData = new VertexData();
  37592. vertexData.indices = indices;
  37593. vertexData.positions = positions;
  37594. vertexData.normals = normals;
  37595. vertexData.uvs = uvs;
  37596. return vertexData;
  37597. };
  37598. /**
  37599. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37600. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37601. * * xmin the ground minimum X coordinate, optional, default -1
  37602. * * zmin the ground minimum Z coordinate, optional, default -1
  37603. * * xmax the ground maximum X coordinate, optional, default 1
  37604. * * zmax the ground maximum Z coordinate, optional, default 1
  37605. * * 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}
  37606. * * 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}
  37607. * @returns the VertexData of the TiledGround
  37608. */
  37609. VertexData.CreateTiledGround = function (options) {
  37610. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37611. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37612. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37613. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37614. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37615. var precision = options.precision || { w: 1, h: 1 };
  37616. var indices = new Array();
  37617. var positions = new Array();
  37618. var normals = new Array();
  37619. var uvs = new Array();
  37620. var row, col, tileRow, tileCol;
  37621. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37622. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37623. precision.w = (precision.w < 1) ? 1 : precision.w;
  37624. precision.h = (precision.h < 1) ? 1 : precision.h;
  37625. var tileSize = {
  37626. 'w': (xmax - xmin) / subdivisions.w,
  37627. 'h': (zmax - zmin) / subdivisions.h
  37628. };
  37629. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37630. // Indices
  37631. var base = positions.length / 3;
  37632. var rowLength = precision.w + 1;
  37633. for (row = 0; row < precision.h; row++) {
  37634. for (col = 0; col < precision.w; col++) {
  37635. var square = [
  37636. base + col + row * rowLength,
  37637. base + (col + 1) + row * rowLength,
  37638. base + (col + 1) + (row + 1) * rowLength,
  37639. base + col + (row + 1) * rowLength
  37640. ];
  37641. indices.push(square[1]);
  37642. indices.push(square[2]);
  37643. indices.push(square[3]);
  37644. indices.push(square[0]);
  37645. indices.push(square[1]);
  37646. indices.push(square[3]);
  37647. }
  37648. }
  37649. // Position, normals and uvs
  37650. var position = BABYLON.Vector3.Zero();
  37651. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37652. for (row = 0; row <= precision.h; row++) {
  37653. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37654. for (col = 0; col <= precision.w; col++) {
  37655. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37656. position.y = 0;
  37657. positions.push(position.x, position.y, position.z);
  37658. normals.push(normal.x, normal.y, normal.z);
  37659. uvs.push(col / precision.w, row / precision.h);
  37660. }
  37661. }
  37662. }
  37663. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37664. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37665. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37666. }
  37667. }
  37668. // Result
  37669. var vertexData = new VertexData();
  37670. vertexData.indices = indices;
  37671. vertexData.positions = positions;
  37672. vertexData.normals = normals;
  37673. vertexData.uvs = uvs;
  37674. return vertexData;
  37675. };
  37676. /**
  37677. * Creates the VertexData of the Ground designed from a heightmap
  37678. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37679. * * width the width (x direction) of the ground
  37680. * * height the height (z direction) of the ground
  37681. * * subdivisions the number of subdivisions per side
  37682. * * minHeight the minimum altitude on the ground, optional, default 0
  37683. * * maxHeight the maximum altitude on the ground, optional default 1
  37684. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37685. * * buffer the array holding the image color data
  37686. * * bufferWidth the width of image
  37687. * * bufferHeight the height of image
  37688. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37689. * @returns the VertexData of the Ground designed from a heightmap
  37690. */
  37691. VertexData.CreateGroundFromHeightMap = function (options) {
  37692. var indices = [];
  37693. var positions = [];
  37694. var normals = [];
  37695. var uvs = [];
  37696. var row, col;
  37697. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37698. var alphaFilter = options.alphaFilter || 0.0;
  37699. // Vertices
  37700. for (row = 0; row <= options.subdivisions; row++) {
  37701. for (col = 0; col <= options.subdivisions; col++) {
  37702. 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));
  37703. // Compute height
  37704. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37705. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37706. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37707. var r = options.buffer[pos] / 255.0;
  37708. var g = options.buffer[pos + 1] / 255.0;
  37709. var b = options.buffer[pos + 2] / 255.0;
  37710. var a = options.buffer[pos + 3] / 255.0;
  37711. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37712. // If our alpha channel is not within our filter then we will assign a 'special' height
  37713. // Then when building the indices, we will ignore any vertex that is using the special height
  37714. if (a >= alphaFilter)
  37715. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37716. else {
  37717. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37718. }
  37719. // Add vertex
  37720. positions.push(position.x, position.y, position.z);
  37721. normals.push(0, 0, 0);
  37722. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37723. }
  37724. }
  37725. // Indices
  37726. for (row = 0; row < options.subdivisions; row++) {
  37727. for (col = 0; col < options.subdivisions; col++) {
  37728. // Calculate Indices
  37729. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37730. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37731. var idx3 = (col + row * (options.subdivisions + 1));
  37732. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37733. // Check that all indices are visible (based on our special height)
  37734. // Only display the vertex if all Indices are visible
  37735. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37736. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37737. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37738. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37739. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37740. indices.push(idx1);
  37741. indices.push(idx2);
  37742. indices.push(idx3);
  37743. }
  37744. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37745. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37746. indices.push(idx4);
  37747. indices.push(idx1);
  37748. indices.push(idx3);
  37749. }
  37750. }
  37751. }
  37752. // Normals
  37753. VertexData.ComputeNormals(positions, indices, normals);
  37754. // Result
  37755. var vertexData = new VertexData();
  37756. vertexData.indices = indices;
  37757. vertexData.positions = positions;
  37758. vertexData.normals = normals;
  37759. vertexData.uvs = uvs;
  37760. return vertexData;
  37761. };
  37762. /**
  37763. * Creates the VertexData for a Plane
  37764. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37765. * * size sets the width and height of the plane to the value of size, optional default 1
  37766. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37767. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37768. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37769. * * 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)
  37770. * * 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)
  37771. * @returns the VertexData of the box
  37772. */
  37773. VertexData.CreatePlane = function (options) {
  37774. var indices = [];
  37775. var positions = [];
  37776. var normals = [];
  37777. var uvs = [];
  37778. var width = options.width || options.size || 1;
  37779. var height = options.height || options.size || 1;
  37780. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37781. // Vertices
  37782. var halfWidth = width / 2.0;
  37783. var halfHeight = height / 2.0;
  37784. positions.push(-halfWidth, -halfHeight, 0);
  37785. normals.push(0, 0, -1.0);
  37786. uvs.push(0.0, 0.0);
  37787. positions.push(halfWidth, -halfHeight, 0);
  37788. normals.push(0, 0, -1.0);
  37789. uvs.push(1.0, 0.0);
  37790. positions.push(halfWidth, halfHeight, 0);
  37791. normals.push(0, 0, -1.0);
  37792. uvs.push(1.0, 1.0);
  37793. positions.push(-halfWidth, halfHeight, 0);
  37794. normals.push(0, 0, -1.0);
  37795. uvs.push(0.0, 1.0);
  37796. // Indices
  37797. indices.push(0);
  37798. indices.push(1);
  37799. indices.push(2);
  37800. indices.push(0);
  37801. indices.push(2);
  37802. indices.push(3);
  37803. // Sides
  37804. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37805. // Result
  37806. var vertexData = new VertexData();
  37807. vertexData.indices = indices;
  37808. vertexData.positions = positions;
  37809. vertexData.normals = normals;
  37810. vertexData.uvs = uvs;
  37811. return vertexData;
  37812. };
  37813. /**
  37814. * Creates the VertexData of the Disc or regular Polygon
  37815. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37816. * * radius the radius of the disc, optional default 0.5
  37817. * * tessellation the number of polygon sides, optional, default 64
  37818. * * 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
  37819. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37820. * * 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)
  37821. * * 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)
  37822. * @returns the VertexData of the box
  37823. */
  37824. VertexData.CreateDisc = function (options) {
  37825. var positions = new Array();
  37826. var indices = new Array();
  37827. var normals = new Array();
  37828. var uvs = new Array();
  37829. var radius = options.radius || 0.5;
  37830. var tessellation = options.tessellation || 64;
  37831. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37832. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37833. // positions and uvs
  37834. positions.push(0, 0, 0); // disc center first
  37835. uvs.push(0.5, 0.5);
  37836. var theta = Math.PI * 2 * arc;
  37837. var step = theta / tessellation;
  37838. for (var a = 0; a < theta; a += step) {
  37839. var x = Math.cos(a);
  37840. var y = Math.sin(a);
  37841. var u = (x + 1) / 2;
  37842. var v = (1 - y) / 2;
  37843. positions.push(radius * x, radius * y, 0);
  37844. uvs.push(u, v);
  37845. }
  37846. if (arc === 1) {
  37847. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37848. uvs.push(uvs[2], uvs[3]);
  37849. }
  37850. //indices
  37851. var vertexNb = positions.length / 3;
  37852. for (var i = 1; i < vertexNb - 1; i++) {
  37853. indices.push(i + 1, 0, i);
  37854. }
  37855. // result
  37856. VertexData.ComputeNormals(positions, indices, normals);
  37857. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37858. var vertexData = new VertexData();
  37859. vertexData.indices = indices;
  37860. vertexData.positions = positions;
  37861. vertexData.normals = normals;
  37862. vertexData.uvs = uvs;
  37863. return vertexData;
  37864. };
  37865. /**
  37866. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37867. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37868. * @param polygon a mesh built from polygonTriangulation.build()
  37869. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37870. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37871. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37872. * @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)
  37873. * @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)
  37874. * @returns the VertexData of the Polygon
  37875. */
  37876. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37877. var faceUV = fUV || new Array(3);
  37878. var faceColors = fColors;
  37879. var colors = [];
  37880. // default face colors and UV if undefined
  37881. for (var f = 0; f < 3; f++) {
  37882. if (faceUV[f] === undefined) {
  37883. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37884. }
  37885. if (faceColors && faceColors[f] === undefined) {
  37886. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37887. }
  37888. }
  37889. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37890. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37891. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37892. var indices = polygon.getIndices();
  37893. // set face colours and textures
  37894. var idx = 0;
  37895. var face = 0;
  37896. for (var index = 0; index < normals.length; index += 3) {
  37897. //Edge Face no. 1
  37898. if (Math.abs(normals[index + 1]) < 0.001) {
  37899. face = 1;
  37900. }
  37901. //Top Face no. 0
  37902. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37903. face = 0;
  37904. }
  37905. //Bottom Face no. 2
  37906. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37907. face = 2;
  37908. }
  37909. idx = index / 3;
  37910. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37911. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37912. if (faceColors) {
  37913. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37914. }
  37915. }
  37916. // sides
  37917. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37918. // Result
  37919. var vertexData = new VertexData();
  37920. vertexData.indices = indices;
  37921. vertexData.positions = positions;
  37922. vertexData.normals = normals;
  37923. vertexData.uvs = uvs;
  37924. if (faceColors) {
  37925. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37926. vertexData.colors = totalColors;
  37927. }
  37928. return vertexData;
  37929. };
  37930. /**
  37931. * Creates the VertexData of the IcoSphere
  37932. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37933. * * radius the radius of the IcoSphere, optional default 1
  37934. * * radiusX allows stretching in the x direction, optional, default radius
  37935. * * radiusY allows stretching in the y direction, optional, default radius
  37936. * * radiusZ allows stretching in the z direction, optional, default radius
  37937. * * flat when true creates a flat shaded mesh, optional, default true
  37938. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37939. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37940. * * 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)
  37941. * * 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)
  37942. * @returns the VertexData of the IcoSphere
  37943. */
  37944. VertexData.CreateIcoSphere = function (options) {
  37945. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37946. var radius = options.radius || 1;
  37947. var flat = (options.flat === undefined) ? true : options.flat;
  37948. var subdivisions = options.subdivisions || 4;
  37949. var radiusX = options.radiusX || radius;
  37950. var radiusY = options.radiusY || radius;
  37951. var radiusZ = options.radiusZ || radius;
  37952. var t = (1 + Math.sqrt(5)) / 2;
  37953. // 12 vertex x,y,z
  37954. var ico_vertices = [
  37955. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37956. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37957. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37958. ];
  37959. // index of 3 vertex makes a face of icopshere
  37960. var ico_indices = [
  37961. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37962. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37963. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37964. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37965. ];
  37966. // vertex for uv have aliased position, not for UV
  37967. var vertices_unalias_id = [
  37968. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37969. // vertex alias
  37970. 0,
  37971. 2,
  37972. 3,
  37973. 3,
  37974. 3,
  37975. 4,
  37976. 7,
  37977. 8,
  37978. 9,
  37979. 9,
  37980. 10,
  37981. 11 // 23: B + 12
  37982. ];
  37983. // uv as integer step (not pixels !)
  37984. var ico_vertexuv = [
  37985. 5, 1, 3, 1, 6, 4, 0, 0,
  37986. 5, 3, 4, 2, 2, 2, 4, 0,
  37987. 2, 0, 1, 1, 6, 0, 6, 2,
  37988. // vertex alias (for same vertex on different faces)
  37989. 0, 4,
  37990. 3, 3,
  37991. 4, 4,
  37992. 3, 1,
  37993. 4, 2,
  37994. 4, 4,
  37995. 0, 2,
  37996. 1, 1,
  37997. 2, 2,
  37998. 3, 3,
  37999. 1, 3,
  38000. 2, 4 // 23: B + 12
  38001. ];
  38002. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38003. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38004. // First island of uv mapping
  38005. // v = 4h 3+ 2
  38006. // v = 3h 9+ 4
  38007. // v = 2h 9+ 5 B
  38008. // v = 1h 9 1 0
  38009. // v = 0h 3 8 7 A
  38010. // u = 0 1 2 3 4 5 6 *a
  38011. // Second island of uv mapping
  38012. // v = 4h 0+ B+ 4+
  38013. // v = 3h A+ 2+
  38014. // v = 2h 7+ 6 3+
  38015. // v = 1h 8+ 3+
  38016. // v = 0h
  38017. // u = 0 1 2 3 4 5 6 *a
  38018. // Face layout on texture UV mapping
  38019. // ============
  38020. // \ 4 /\ 16 / ======
  38021. // \ / \ / /\ 11 /
  38022. // \/ 7 \/ / \ /
  38023. // ======= / 10 \/
  38024. // /\ 17 /\ =======
  38025. // / \ / \ \ 15 /\
  38026. // / 8 \/ 12 \ \ / \
  38027. // ============ \/ 6 \
  38028. // \ 18 /\ ============
  38029. // \ / \ \ 5 /\ 0 /
  38030. // \/ 13 \ \ / \ /
  38031. // ======= \/ 1 \/
  38032. // =============
  38033. // /\ 19 /\ 2 /\
  38034. // / \ / \ / \
  38035. // / 14 \/ 9 \/ 3 \
  38036. // ===================
  38037. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38038. var ustep = 138 / 1024;
  38039. var vstep = 239 / 1024;
  38040. var uoffset = 60 / 1024;
  38041. var voffset = 26 / 1024;
  38042. // Second island should have margin, not to touch the first island
  38043. // avoid any borderline artefact in pixel rounding
  38044. var island_u_offset = -40 / 1024;
  38045. var island_v_offset = +20 / 1024;
  38046. // face is either island 0 or 1 :
  38047. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38048. var island = [
  38049. 0, 0, 0, 0, 1,
  38050. 0, 0, 1, 1, 0,
  38051. 0, 0, 1, 1, 0,
  38052. 0, 1, 1, 1, 0 // 15 - 19
  38053. ];
  38054. var indices = new Array();
  38055. var positions = new Array();
  38056. var normals = new Array();
  38057. var uvs = new Array();
  38058. var current_indice = 0;
  38059. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38060. var face_vertex_pos = new Array(3);
  38061. var face_vertex_uv = new Array(3);
  38062. var v012;
  38063. for (v012 = 0; v012 < 3; v012++) {
  38064. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38065. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38066. }
  38067. // create all with normals
  38068. for (var face = 0; face < 20; face++) {
  38069. // 3 vertex per face
  38070. for (v012 = 0; v012 < 3; v012++) {
  38071. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38072. var v_id = ico_indices[3 * face + v012];
  38073. // vertex have 3D position (x,y,z)
  38074. 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]);
  38075. // Normalize to get normal, then scale to radius
  38076. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38077. // uv Coordinates from vertex ID
  38078. 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);
  38079. }
  38080. // Subdivide the face (interpolate pos, norm, uv)
  38081. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38082. // - norm is linear interpolation of vertex corner normal
  38083. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38084. // - uv is linear interpolation
  38085. //
  38086. // Topology is as below for sub-divide by 2
  38087. // vertex shown as v0,v1,v2
  38088. // interp index is i1 to progress in range [v0,v1[
  38089. // interp index is i2 to progress in range [v0,v2[
  38090. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38091. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38092. //
  38093. //
  38094. // i2 v2
  38095. // ^ ^
  38096. // / / \
  38097. // / / \
  38098. // / / \
  38099. // / / (0,1) \
  38100. // / #---------\
  38101. // / / \ (0,0)'/ \
  38102. // / / \ / \
  38103. // / / \ / \
  38104. // / / (0,0) \ / (1,0) \
  38105. // / #---------#---------\
  38106. // v0 v1
  38107. //
  38108. // --------------------> i1
  38109. //
  38110. // interp of (i1,i2):
  38111. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38112. // along i1 : lerp(x0,x1, i1/(S-i2))
  38113. //
  38114. // centroid of triangle is needed to get help normal computation
  38115. // (c1,c2) are used for centroid location
  38116. var interp_vertex = function (i1, i2, c1, c2) {
  38117. // vertex is interpolated from
  38118. // - face_vertex_pos[0..2]
  38119. // - face_vertex_uv[0..2]
  38120. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38121. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38122. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38123. pos_interp.normalize();
  38124. var vertex_normal;
  38125. if (flat) {
  38126. // in flat mode, recalculate normal as face centroid normal
  38127. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38128. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38129. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38130. }
  38131. else {
  38132. // in smooth mode, recalculate normal from each single vertex position
  38133. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38134. }
  38135. // Vertex normal need correction due to X,Y,Z radius scaling
  38136. vertex_normal.x /= radiusX;
  38137. vertex_normal.y /= radiusY;
  38138. vertex_normal.z /= radiusZ;
  38139. vertex_normal.normalize();
  38140. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38141. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38142. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38143. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38144. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38145. uvs.push(uv_interp.x, uv_interp.y);
  38146. // push each vertex has member of a face
  38147. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38148. indices.push(current_indice);
  38149. current_indice++;
  38150. };
  38151. for (var i2 = 0; i2 < subdivisions; i2++) {
  38152. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38153. // face : (i1,i2) for /\ :
  38154. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38155. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38156. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38157. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38158. if (i1 + i2 + 1 < subdivisions) {
  38159. // face : (i1,i2)' for \/ :
  38160. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38161. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38162. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38163. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38164. }
  38165. }
  38166. }
  38167. }
  38168. // Sides
  38169. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38170. // Result
  38171. var vertexData = new VertexData();
  38172. vertexData.indices = indices;
  38173. vertexData.positions = positions;
  38174. vertexData.normals = normals;
  38175. vertexData.uvs = uvs;
  38176. return vertexData;
  38177. };
  38178. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38179. /**
  38180. * Creates the VertexData for a Polyhedron
  38181. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38182. * * type provided types are:
  38183. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38184. * * 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)
  38185. * * size the size of the IcoSphere, optional default 1
  38186. * * sizeX allows stretching in the x direction, optional, default size
  38187. * * sizeY allows stretching in the y direction, optional, default size
  38188. * * sizeZ allows stretching in the z direction, optional, default size
  38189. * * 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
  38190. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38191. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38192. * * flat when true creates a flat shaded mesh, optional, default true
  38193. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38194. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38195. * * 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)
  38196. * * 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)
  38197. * @returns the VertexData of the Polyhedron
  38198. */
  38199. VertexData.CreatePolyhedron = function (options) {
  38200. // provided polyhedron types :
  38201. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38202. // 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)
  38203. var polyhedra = [];
  38204. 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]] };
  38205. 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]] };
  38206. polyhedra[2] = {
  38207. 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]],
  38208. 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]]
  38209. };
  38210. polyhedra[3] = {
  38211. 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]],
  38212. 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]]
  38213. };
  38214. polyhedra[4] = {
  38215. 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]],
  38216. 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]]
  38217. };
  38218. 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]] };
  38219. 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]] };
  38220. 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]] };
  38221. 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]] };
  38222. 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]] };
  38223. 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]] };
  38224. 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]] };
  38225. 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]] };
  38226. 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]] };
  38227. polyhedra[14] = {
  38228. 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]],
  38229. 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]]
  38230. };
  38231. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38232. var size = options.size;
  38233. var sizeX = options.sizeX || size || 1;
  38234. var sizeY = options.sizeY || size || 1;
  38235. var sizeZ = options.sizeZ || size || 1;
  38236. var data = options.custom || polyhedra[type];
  38237. var nbfaces = data.face.length;
  38238. var faceUV = options.faceUV || new Array(nbfaces);
  38239. var faceColors = options.faceColors;
  38240. var flat = (options.flat === undefined) ? true : options.flat;
  38241. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38242. var positions = new Array();
  38243. var indices = new Array();
  38244. var normals = new Array();
  38245. var uvs = new Array();
  38246. var colors = new Array();
  38247. var index = 0;
  38248. var faceIdx = 0; // face cursor in the array "indexes"
  38249. var indexes = new Array();
  38250. var i = 0;
  38251. var f = 0;
  38252. var u, v, ang, x, y, tmp;
  38253. // default face colors and UV if undefined
  38254. if (flat) {
  38255. for (f = 0; f < nbfaces; f++) {
  38256. if (faceColors && faceColors[f] === undefined) {
  38257. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38258. }
  38259. if (faceUV && faceUV[f] === undefined) {
  38260. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38261. }
  38262. }
  38263. }
  38264. if (!flat) {
  38265. for (i = 0; i < data.vertex.length; i++) {
  38266. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38267. uvs.push(0, 0);
  38268. }
  38269. for (f = 0; f < nbfaces; f++) {
  38270. for (i = 0; i < data.face[f].length - 2; i++) {
  38271. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38272. }
  38273. }
  38274. }
  38275. else {
  38276. for (f = 0; f < nbfaces; f++) {
  38277. var fl = data.face[f].length; // number of vertices of the current face
  38278. ang = 2 * Math.PI / fl;
  38279. x = 0.5 * Math.tan(ang / 2);
  38280. y = 0.5;
  38281. // positions, uvs, colors
  38282. for (i = 0; i < fl; i++) {
  38283. // positions
  38284. 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);
  38285. indexes.push(index);
  38286. index++;
  38287. // uvs
  38288. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38289. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38290. uvs.push(u, v);
  38291. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38292. y = x * Math.sin(ang) + y * Math.cos(ang);
  38293. x = tmp;
  38294. // colors
  38295. if (faceColors) {
  38296. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38297. }
  38298. }
  38299. // indices from indexes
  38300. for (i = 0; i < fl - 2; i++) {
  38301. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38302. }
  38303. faceIdx += fl;
  38304. }
  38305. }
  38306. VertexData.ComputeNormals(positions, indices, normals);
  38307. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38308. var vertexData = new VertexData();
  38309. vertexData.positions = positions;
  38310. vertexData.indices = indices;
  38311. vertexData.normals = normals;
  38312. vertexData.uvs = uvs;
  38313. if (faceColors && flat) {
  38314. vertexData.colors = colors;
  38315. }
  38316. return vertexData;
  38317. };
  38318. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38319. /**
  38320. * Creates the VertexData for a TorusKnot
  38321. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38322. * * radius the radius of the torus knot, optional, default 2
  38323. * * tube the thickness of the tube, optional, default 0.5
  38324. * * radialSegments the number of sides on each tube segments, optional, default 32
  38325. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38326. * * p the number of windings around the z axis, optional, default 2
  38327. * * q the number of windings around the x axis, optional, default 3
  38328. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38329. * * 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)
  38330. * * 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)
  38331. * @returns the VertexData of the Torus Knot
  38332. */
  38333. VertexData.CreateTorusKnot = function (options) {
  38334. var indices = new Array();
  38335. var positions = new Array();
  38336. var normals = new Array();
  38337. var uvs = new Array();
  38338. var radius = options.radius || 2;
  38339. var tube = options.tube || 0.5;
  38340. var radialSegments = options.radialSegments || 32;
  38341. var tubularSegments = options.tubularSegments || 32;
  38342. var p = options.p || 2;
  38343. var q = options.q || 3;
  38344. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38345. // Helper
  38346. var getPos = function (angle) {
  38347. var cu = Math.cos(angle);
  38348. var su = Math.sin(angle);
  38349. var quOverP = q / p * angle;
  38350. var cs = Math.cos(quOverP);
  38351. var tx = radius * (2 + cs) * 0.5 * cu;
  38352. var ty = radius * (2 + cs) * su * 0.5;
  38353. var tz = radius * Math.sin(quOverP) * 0.5;
  38354. return new BABYLON.Vector3(tx, ty, tz);
  38355. };
  38356. // Vertices
  38357. var i;
  38358. var j;
  38359. for (i = 0; i <= radialSegments; i++) {
  38360. var modI = i % radialSegments;
  38361. var u = modI / radialSegments * 2 * p * Math.PI;
  38362. var p1 = getPos(u);
  38363. var p2 = getPos(u + 0.01);
  38364. var tang = p2.subtract(p1);
  38365. var n = p2.add(p1);
  38366. var bitan = BABYLON.Vector3.Cross(tang, n);
  38367. n = BABYLON.Vector3.Cross(bitan, tang);
  38368. bitan.normalize();
  38369. n.normalize();
  38370. for (j = 0; j < tubularSegments; j++) {
  38371. var modJ = j % tubularSegments;
  38372. var v = modJ / tubularSegments * 2 * Math.PI;
  38373. var cx = -tube * Math.cos(v);
  38374. var cy = tube * Math.sin(v);
  38375. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38376. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38377. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38378. uvs.push(i / radialSegments);
  38379. uvs.push(j / tubularSegments);
  38380. }
  38381. }
  38382. for (i = 0; i < radialSegments; i++) {
  38383. for (j = 0; j < tubularSegments; j++) {
  38384. var jNext = (j + 1) % tubularSegments;
  38385. var a = i * tubularSegments + j;
  38386. var b = (i + 1) * tubularSegments + j;
  38387. var c = (i + 1) * tubularSegments + jNext;
  38388. var d = i * tubularSegments + jNext;
  38389. indices.push(d);
  38390. indices.push(b);
  38391. indices.push(a);
  38392. indices.push(d);
  38393. indices.push(c);
  38394. indices.push(b);
  38395. }
  38396. }
  38397. // Normals
  38398. VertexData.ComputeNormals(positions, indices, normals);
  38399. // Sides
  38400. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38401. // Result
  38402. var vertexData = new VertexData();
  38403. vertexData.indices = indices;
  38404. vertexData.positions = positions;
  38405. vertexData.normals = normals;
  38406. vertexData.uvs = uvs;
  38407. return vertexData;
  38408. };
  38409. // Tools
  38410. /**
  38411. * Compute normals for given positions and indices
  38412. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38413. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38414. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38415. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38416. * * facetNormals : optional array of facet normals (vector3)
  38417. * * facetPositions : optional array of facet positions (vector3)
  38418. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38419. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38420. * * bInfo : optional bounding info, required for facetPartitioning computation
  38421. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38422. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38423. * * useRightHandedSystem: optional boolean to for right handed system computation
  38424. * * depthSort : optional boolean to enable the facet depth sort computation
  38425. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38426. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38427. */
  38428. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38429. // temporary scalar variables
  38430. var index = 0; // facet index
  38431. var p1p2x = 0.0; // p1p2 vector x coordinate
  38432. var p1p2y = 0.0; // p1p2 vector y coordinate
  38433. var p1p2z = 0.0; // p1p2 vector z coordinate
  38434. var p3p2x = 0.0; // p3p2 vector x coordinate
  38435. var p3p2y = 0.0; // p3p2 vector y coordinate
  38436. var p3p2z = 0.0; // p3p2 vector z coordinate
  38437. var faceNormalx = 0.0; // facet normal x coordinate
  38438. var faceNormaly = 0.0; // facet normal y coordinate
  38439. var faceNormalz = 0.0; // facet normal z coordinate
  38440. var length = 0.0; // facet normal length before normalization
  38441. var v1x = 0; // vector1 x index in the positions array
  38442. var v1y = 0; // vector1 y index in the positions array
  38443. var v1z = 0; // vector1 z index in the positions array
  38444. var v2x = 0; // vector2 x index in the positions array
  38445. var v2y = 0; // vector2 y index in the positions array
  38446. var v2z = 0; // vector2 z index in the positions array
  38447. var v3x = 0; // vector3 x index in the positions array
  38448. var v3y = 0; // vector3 y index in the positions array
  38449. var v3z = 0; // vector3 z index in the positions array
  38450. var computeFacetNormals = false;
  38451. var computeFacetPositions = false;
  38452. var computeFacetPartitioning = false;
  38453. var computeDepthSort = false;
  38454. var faceNormalSign = 1;
  38455. var ratio = 0;
  38456. var distanceTo = null;
  38457. if (options) {
  38458. computeFacetNormals = (options.facetNormals) ? true : false;
  38459. computeFacetPositions = (options.facetPositions) ? true : false;
  38460. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38461. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38462. ratio = options.ratio || 0;
  38463. computeDepthSort = (options.depthSort) ? true : false;
  38464. distanceTo = (options.distanceTo);
  38465. if (computeDepthSort) {
  38466. if (distanceTo === undefined) {
  38467. distanceTo = BABYLON.Vector3.Zero();
  38468. }
  38469. var depthSortedFacets = options.depthSortedFacets;
  38470. }
  38471. }
  38472. // facetPartitioning reinit if needed
  38473. var xSubRatio = 0;
  38474. var ySubRatio = 0;
  38475. var zSubRatio = 0;
  38476. var subSq = 0;
  38477. if (computeFacetPartitioning && options && options.bbSize) {
  38478. var ox = 0; // X partitioning index for facet position
  38479. var oy = 0; // Y partinioning index for facet position
  38480. var oz = 0; // Z partinioning index for facet position
  38481. var b1x = 0; // X partitioning index for facet v1 vertex
  38482. var b1y = 0; // Y partitioning index for facet v1 vertex
  38483. var b1z = 0; // z partitioning index for facet v1 vertex
  38484. var b2x = 0; // X partitioning index for facet v2 vertex
  38485. var b2y = 0; // Y partitioning index for facet v2 vertex
  38486. var b2z = 0; // Z partitioning index for facet v2 vertex
  38487. var b3x = 0; // X partitioning index for facet v3 vertex
  38488. var b3y = 0; // Y partitioning index for facet v3 vertex
  38489. var b3z = 0; // Z partitioning index for facet v3 vertex
  38490. var block_idx_o = 0; // facet barycenter block index
  38491. var block_idx_v1 = 0; // v1 vertex block index
  38492. var block_idx_v2 = 0; // v2 vertex block index
  38493. var block_idx_v3 = 0; // v3 vertex block index
  38494. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38495. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38496. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38497. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38498. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38499. subSq = options.subDiv.max * options.subDiv.max;
  38500. options.facetPartitioning.length = 0;
  38501. }
  38502. // reset the normals
  38503. for (index = 0; index < positions.length; index++) {
  38504. normals[index] = 0.0;
  38505. }
  38506. // Loop : 1 indice triplet = 1 facet
  38507. var nbFaces = (indices.length / 3) | 0;
  38508. for (index = 0; index < nbFaces; index++) {
  38509. // get the indexes of the coordinates of each vertex of the facet
  38510. v1x = indices[index * 3] * 3;
  38511. v1y = v1x + 1;
  38512. v1z = v1x + 2;
  38513. v2x = indices[index * 3 + 1] * 3;
  38514. v2y = v2x + 1;
  38515. v2z = v2x + 2;
  38516. v3x = indices[index * 3 + 2] * 3;
  38517. v3y = v3x + 1;
  38518. v3z = v3x + 2;
  38519. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38520. p1p2y = positions[v1y] - positions[v2y];
  38521. p1p2z = positions[v1z] - positions[v2z];
  38522. p3p2x = positions[v3x] - positions[v2x];
  38523. p3p2y = positions[v3y] - positions[v2y];
  38524. p3p2z = positions[v3z] - positions[v2z];
  38525. // compute the face normal with the cross product
  38526. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38527. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38528. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38529. // normalize this normal and store it in the array facetData
  38530. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38531. length = (length === 0) ? 1.0 : length;
  38532. faceNormalx /= length;
  38533. faceNormaly /= length;
  38534. faceNormalz /= length;
  38535. if (computeFacetNormals && options) {
  38536. options.facetNormals[index].x = faceNormalx;
  38537. options.facetNormals[index].y = faceNormaly;
  38538. options.facetNormals[index].z = faceNormalz;
  38539. }
  38540. if (computeFacetPositions && options) {
  38541. // compute and the facet barycenter coordinates in the array facetPositions
  38542. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38543. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38544. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38545. }
  38546. if (computeFacetPartitioning && options) {
  38547. // store the facet indexes in arrays in the main facetPartitioning array :
  38548. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38549. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38550. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38551. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38552. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38553. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38554. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38555. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38556. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38557. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38558. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38559. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38560. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38561. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38562. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38563. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38564. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38565. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38566. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38567. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38568. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38569. // push each facet index in each block containing the vertex
  38570. options.facetPartitioning[block_idx_v1].push(index);
  38571. if (block_idx_v2 != block_idx_v1) {
  38572. options.facetPartitioning[block_idx_v2].push(index);
  38573. }
  38574. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38575. options.facetPartitioning[block_idx_v3].push(index);
  38576. }
  38577. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38578. options.facetPartitioning[block_idx_o].push(index);
  38579. }
  38580. }
  38581. if (computeDepthSort && options && options.facetPositions) {
  38582. var dsf = depthSortedFacets[index];
  38583. dsf.ind = index * 3;
  38584. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38585. }
  38586. // compute the normals anyway
  38587. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38588. normals[v1y] += faceNormaly;
  38589. normals[v1z] += faceNormalz;
  38590. normals[v2x] += faceNormalx;
  38591. normals[v2y] += faceNormaly;
  38592. normals[v2z] += faceNormalz;
  38593. normals[v3x] += faceNormalx;
  38594. normals[v3y] += faceNormaly;
  38595. normals[v3z] += faceNormalz;
  38596. }
  38597. // last normalization of each normal
  38598. for (index = 0; index < normals.length / 3; index++) {
  38599. faceNormalx = normals[index * 3];
  38600. faceNormaly = normals[index * 3 + 1];
  38601. faceNormalz = normals[index * 3 + 2];
  38602. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38603. length = (length === 0) ? 1.0 : length;
  38604. faceNormalx /= length;
  38605. faceNormaly /= length;
  38606. faceNormalz /= length;
  38607. normals[index * 3] = faceNormalx;
  38608. normals[index * 3 + 1] = faceNormaly;
  38609. normals[index * 3 + 2] = faceNormalz;
  38610. }
  38611. };
  38612. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38613. var li = indices.length;
  38614. var ln = normals.length;
  38615. var i;
  38616. var n;
  38617. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38618. switch (sideOrientation) {
  38619. case BABYLON.Mesh.FRONTSIDE:
  38620. // nothing changed
  38621. break;
  38622. case BABYLON.Mesh.BACKSIDE:
  38623. var tmp;
  38624. // indices
  38625. for (i = 0; i < li; i += 3) {
  38626. tmp = indices[i];
  38627. indices[i] = indices[i + 2];
  38628. indices[i + 2] = tmp;
  38629. }
  38630. // normals
  38631. for (n = 0; n < ln; n++) {
  38632. normals[n] = -normals[n];
  38633. }
  38634. break;
  38635. case BABYLON.Mesh.DOUBLESIDE:
  38636. // positions
  38637. var lp = positions.length;
  38638. var l = lp / 3;
  38639. for (var p = 0; p < lp; p++) {
  38640. positions[lp + p] = positions[p];
  38641. }
  38642. // indices
  38643. for (i = 0; i < li; i += 3) {
  38644. indices[i + li] = indices[i + 2] + l;
  38645. indices[i + 1 + li] = indices[i + 1] + l;
  38646. indices[i + 2 + li] = indices[i] + l;
  38647. }
  38648. // normals
  38649. for (n = 0; n < ln; n++) {
  38650. normals[ln + n] = -normals[n];
  38651. }
  38652. // uvs
  38653. var lu = uvs.length;
  38654. var u = 0;
  38655. for (u = 0; u < lu; u++) {
  38656. uvs[u + lu] = uvs[u];
  38657. }
  38658. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38659. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38660. u = 0;
  38661. for (i = 0; i < lu / 2; i++) {
  38662. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38663. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38664. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38665. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38666. u += 2;
  38667. }
  38668. break;
  38669. }
  38670. };
  38671. /**
  38672. * Applies VertexData created from the imported parameters to the geometry
  38673. * @param parsedVertexData the parsed data from an imported file
  38674. * @param geometry the geometry to apply the VertexData to
  38675. */
  38676. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38677. var vertexData = new VertexData();
  38678. // positions
  38679. var positions = parsedVertexData.positions;
  38680. if (positions) {
  38681. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38682. }
  38683. // normals
  38684. var normals = parsedVertexData.normals;
  38685. if (normals) {
  38686. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38687. }
  38688. // tangents
  38689. var tangents = parsedVertexData.tangents;
  38690. if (tangents) {
  38691. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38692. }
  38693. // uvs
  38694. var uvs = parsedVertexData.uvs;
  38695. if (uvs) {
  38696. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38697. }
  38698. // uv2s
  38699. var uv2s = parsedVertexData.uv2s;
  38700. if (uv2s) {
  38701. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38702. }
  38703. // uv3s
  38704. var uv3s = parsedVertexData.uv3s;
  38705. if (uv3s) {
  38706. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38707. }
  38708. // uv4s
  38709. var uv4s = parsedVertexData.uv4s;
  38710. if (uv4s) {
  38711. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38712. }
  38713. // uv5s
  38714. var uv5s = parsedVertexData.uv5s;
  38715. if (uv5s) {
  38716. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38717. }
  38718. // uv6s
  38719. var uv6s = parsedVertexData.uv6s;
  38720. if (uv6s) {
  38721. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38722. }
  38723. // colors
  38724. var colors = parsedVertexData.colors;
  38725. if (colors) {
  38726. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38727. }
  38728. // matricesIndices
  38729. var matricesIndices = parsedVertexData.matricesIndices;
  38730. if (matricesIndices) {
  38731. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38732. }
  38733. // matricesWeights
  38734. var matricesWeights = parsedVertexData.matricesWeights;
  38735. if (matricesWeights) {
  38736. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38737. }
  38738. // indices
  38739. var indices = parsedVertexData.indices;
  38740. if (indices) {
  38741. vertexData.indices = indices;
  38742. }
  38743. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38744. };
  38745. return VertexData;
  38746. }());
  38747. BABYLON.VertexData = VertexData;
  38748. })(BABYLON || (BABYLON = {}));
  38749. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38750. var BABYLON;
  38751. (function (BABYLON) {
  38752. /**
  38753. * Class used to store geometry data (vertex buffers + index buffer)
  38754. */
  38755. var Geometry = /** @class */ (function () {
  38756. /**
  38757. * Creates a new geometry
  38758. * @param id defines the unique ID
  38759. * @param scene defines the hosting scene
  38760. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38761. * @param updatable defines if geometry must be updatable (false by default)
  38762. * @param mesh defines the mesh that will be associated with the geometry
  38763. */
  38764. function Geometry(id, scene, vertexData, updatable, mesh) {
  38765. if (updatable === void 0) { updatable = false; }
  38766. if (mesh === void 0) { mesh = null; }
  38767. /**
  38768. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38769. */
  38770. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38771. this._totalVertices = 0;
  38772. this._isDisposed = false;
  38773. this._indexBufferIsUpdatable = false;
  38774. this.id = id;
  38775. this._engine = scene.getEngine();
  38776. this._meshes = [];
  38777. this._scene = scene;
  38778. //Init vertex buffer cache
  38779. this._vertexBuffers = {};
  38780. this._indices = [];
  38781. this._updatable = updatable;
  38782. // vertexData
  38783. if (vertexData) {
  38784. this.setAllVerticesData(vertexData, updatable);
  38785. }
  38786. else {
  38787. this._totalVertices = 0;
  38788. this._indices = [];
  38789. }
  38790. if (this._engine.getCaps().vertexArrayObject) {
  38791. this._vertexArrayObjects = {};
  38792. }
  38793. // applyToMesh
  38794. if (mesh) {
  38795. if (mesh.getClassName() === "LinesMesh") {
  38796. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38797. this._updateExtend();
  38798. }
  38799. this.applyToMesh(mesh);
  38800. mesh.computeWorldMatrix(true);
  38801. }
  38802. }
  38803. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38804. /**
  38805. * 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
  38806. */
  38807. get: function () {
  38808. return this._boundingBias;
  38809. },
  38810. /**
  38811. * 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
  38812. */
  38813. set: function (value) {
  38814. if (this._boundingBias && this._boundingBias.equals(value)) {
  38815. return;
  38816. }
  38817. this._boundingBias = value.clone();
  38818. this._updateBoundingInfo(true, null);
  38819. },
  38820. enumerable: true,
  38821. configurable: true
  38822. });
  38823. /**
  38824. * Static function used to attach a new empty geometry to a mesh
  38825. * @param mesh defines the mesh to attach the geometry to
  38826. * @returns the new {BABYLON.Geometry}
  38827. */
  38828. Geometry.CreateGeometryForMesh = function (mesh) {
  38829. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38830. geometry.applyToMesh(mesh);
  38831. return geometry;
  38832. };
  38833. Object.defineProperty(Geometry.prototype, "extend", {
  38834. /**
  38835. * Gets the current extend of the geometry
  38836. */
  38837. get: function () {
  38838. return this._extend;
  38839. },
  38840. enumerable: true,
  38841. configurable: true
  38842. });
  38843. /**
  38844. * Gets the hosting scene
  38845. * @returns the hosting {BABYLON.Scene}
  38846. */
  38847. Geometry.prototype.getScene = function () {
  38848. return this._scene;
  38849. };
  38850. /**
  38851. * Gets the hosting engine
  38852. * @returns the hosting {BABYLON.Engine}
  38853. */
  38854. Geometry.prototype.getEngine = function () {
  38855. return this._engine;
  38856. };
  38857. /**
  38858. * Defines if the geometry is ready to use
  38859. * @returns true if the geometry is ready to be used
  38860. */
  38861. Geometry.prototype.isReady = function () {
  38862. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38863. };
  38864. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38865. /**
  38866. * Gets a value indicating that the geometry should not be serialized
  38867. */
  38868. get: function () {
  38869. for (var index = 0; index < this._meshes.length; index++) {
  38870. if (!this._meshes[index].doNotSerialize) {
  38871. return false;
  38872. }
  38873. }
  38874. return true;
  38875. },
  38876. enumerable: true,
  38877. configurable: true
  38878. });
  38879. /** @hidden */
  38880. Geometry.prototype._rebuild = function () {
  38881. if (this._vertexArrayObjects) {
  38882. this._vertexArrayObjects = {};
  38883. }
  38884. // Index buffer
  38885. if (this._meshes.length !== 0 && this._indices) {
  38886. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38887. }
  38888. // Vertex buffers
  38889. for (var key in this._vertexBuffers) {
  38890. var vertexBuffer = this._vertexBuffers[key];
  38891. vertexBuffer._rebuild();
  38892. }
  38893. };
  38894. /**
  38895. * Affects all geometry data in one call
  38896. * @param vertexData defines the geometry data
  38897. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38898. */
  38899. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38900. vertexData.applyToGeometry(this, updatable);
  38901. this.notifyUpdate();
  38902. };
  38903. /**
  38904. * Set specific vertex data
  38905. * @param kind defines the data kind (Position, normal, etc...)
  38906. * @param data defines the vertex data to use
  38907. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38908. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38909. */
  38910. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38911. if (updatable === void 0) { updatable = false; }
  38912. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38913. this.setVerticesBuffer(buffer);
  38914. };
  38915. /**
  38916. * Removes a specific vertex data
  38917. * @param kind defines the data kind (Position, normal, etc...)
  38918. */
  38919. Geometry.prototype.removeVerticesData = function (kind) {
  38920. if (this._vertexBuffers[kind]) {
  38921. this._vertexBuffers[kind].dispose();
  38922. delete this._vertexBuffers[kind];
  38923. }
  38924. };
  38925. /**
  38926. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38927. * @param buffer defines the vertex buffer to use
  38928. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38929. */
  38930. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38931. if (totalVertices === void 0) { totalVertices = null; }
  38932. var kind = buffer.getKind();
  38933. if (this._vertexBuffers[kind]) {
  38934. this._vertexBuffers[kind].dispose();
  38935. }
  38936. this._vertexBuffers[kind] = buffer;
  38937. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38938. var data = buffer.getData();
  38939. if (totalVertices != null) {
  38940. this._totalVertices = totalVertices;
  38941. }
  38942. else {
  38943. if (data != null) {
  38944. this._totalVertices = data.length / (buffer.byteStride / 4);
  38945. }
  38946. }
  38947. this._updateExtend(data);
  38948. this._resetPointsArrayCache();
  38949. var meshes = this._meshes;
  38950. var numOfMeshes = meshes.length;
  38951. for (var index = 0; index < numOfMeshes; index++) {
  38952. var mesh = meshes[index];
  38953. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38954. mesh._createGlobalSubMesh(false);
  38955. mesh.computeWorldMatrix(true);
  38956. }
  38957. }
  38958. this.notifyUpdate(kind);
  38959. if (this._vertexArrayObjects) {
  38960. this._disposeVertexArrayObjects();
  38961. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38962. }
  38963. };
  38964. /**
  38965. * Update a specific vertex buffer
  38966. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38967. * It will do nothing if the buffer is not updatable
  38968. * @param kind defines the data kind (Position, normal, etc...)
  38969. * @param data defines the data to use
  38970. * @param offset defines the offset in the target buffer where to store the data
  38971. * @param useBytes set to true if the offset is in bytes
  38972. */
  38973. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38974. if (useBytes === void 0) { useBytes = false; }
  38975. var vertexBuffer = this.getVertexBuffer(kind);
  38976. if (!vertexBuffer) {
  38977. return;
  38978. }
  38979. vertexBuffer.updateDirectly(data, offset, useBytes);
  38980. this.notifyUpdate(kind);
  38981. };
  38982. /**
  38983. * Update a specific vertex buffer
  38984. * This function will create a new buffer if the current one is not updatable
  38985. * @param kind defines the data kind (Position, normal, etc...)
  38986. * @param data defines the data to use
  38987. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38988. */
  38989. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38990. if (updateExtends === void 0) { updateExtends = false; }
  38991. var vertexBuffer = this.getVertexBuffer(kind);
  38992. if (!vertexBuffer) {
  38993. return;
  38994. }
  38995. vertexBuffer.update(data);
  38996. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38997. this._updateBoundingInfo(updateExtends, data);
  38998. }
  38999. this.notifyUpdate(kind);
  39000. };
  39001. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39002. if (updateExtends) {
  39003. this._updateExtend(data);
  39004. }
  39005. var meshes = this._meshes;
  39006. var numOfMeshes = meshes.length;
  39007. this._resetPointsArrayCache();
  39008. for (var index = 0; index < numOfMeshes; index++) {
  39009. var mesh = meshes[index];
  39010. if (updateExtends) {
  39011. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39012. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39013. var subMesh = mesh.subMeshes[subIndex];
  39014. subMesh.refreshBoundingInfo();
  39015. }
  39016. }
  39017. }
  39018. };
  39019. /** @hidden */
  39020. Geometry.prototype._bind = function (effect, indexToBind) {
  39021. if (!effect) {
  39022. return;
  39023. }
  39024. if (indexToBind === undefined) {
  39025. indexToBind = this._indexBuffer;
  39026. }
  39027. var vbs = this.getVertexBuffers();
  39028. if (!vbs) {
  39029. return;
  39030. }
  39031. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39032. this._engine.bindBuffers(vbs, indexToBind, effect);
  39033. return;
  39034. }
  39035. // Using VAO
  39036. if (!this._vertexArrayObjects[effect.key]) {
  39037. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39038. }
  39039. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39040. };
  39041. /**
  39042. * Gets total number of vertices
  39043. * @returns the total number of vertices
  39044. */
  39045. Geometry.prototype.getTotalVertices = function () {
  39046. if (!this.isReady()) {
  39047. return 0;
  39048. }
  39049. return this._totalVertices;
  39050. };
  39051. /**
  39052. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39053. * @param kind defines the data kind (Position, normal, etc...)
  39054. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39055. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39056. * @returns a float array containing vertex data
  39057. */
  39058. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39059. var vertexBuffer = this.getVertexBuffer(kind);
  39060. if (!vertexBuffer) {
  39061. return null;
  39062. }
  39063. var data = vertexBuffer.getData();
  39064. if (!data) {
  39065. return null;
  39066. }
  39067. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39068. var count = this._totalVertices * vertexBuffer.getSize();
  39069. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39070. var copy_1 = new Array(count);
  39071. vertexBuffer.forEach(count, function (value, index) {
  39072. copy_1[index] = value;
  39073. });
  39074. return copy_1;
  39075. }
  39076. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39077. if (data instanceof Array) {
  39078. var offset = vertexBuffer.byteOffset / 4;
  39079. return BABYLON.Tools.Slice(data, offset, offset + count);
  39080. }
  39081. else if (data instanceof ArrayBuffer) {
  39082. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39083. }
  39084. else {
  39085. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39086. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39087. var result = new Float32Array(count);
  39088. var source = new Float32Array(data.buffer, offset, count);
  39089. result.set(source);
  39090. return result;
  39091. }
  39092. return new Float32Array(data.buffer, offset, count);
  39093. }
  39094. }
  39095. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39096. return BABYLON.Tools.Slice(data);
  39097. }
  39098. return data;
  39099. };
  39100. /**
  39101. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39102. * @param kind defines the data kind (Position, normal, etc...)
  39103. * @returns true if the vertex buffer with the specified kind is updatable
  39104. */
  39105. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39106. var vb = this._vertexBuffers[kind];
  39107. if (!vb) {
  39108. return false;
  39109. }
  39110. return vb.isUpdatable();
  39111. };
  39112. /**
  39113. * Gets a specific vertex buffer
  39114. * @param kind defines the data kind (Position, normal, etc...)
  39115. * @returns a {BABYLON.VertexBuffer}
  39116. */
  39117. Geometry.prototype.getVertexBuffer = function (kind) {
  39118. if (!this.isReady()) {
  39119. return null;
  39120. }
  39121. return this._vertexBuffers[kind];
  39122. };
  39123. /**
  39124. * Returns all vertex buffers
  39125. * @return an object holding all vertex buffers indexed by kind
  39126. */
  39127. Geometry.prototype.getVertexBuffers = function () {
  39128. if (!this.isReady()) {
  39129. return null;
  39130. }
  39131. return this._vertexBuffers;
  39132. };
  39133. /**
  39134. * Gets a boolean indicating if specific vertex buffer is present
  39135. * @param kind defines the data kind (Position, normal, etc...)
  39136. * @returns true if data is present
  39137. */
  39138. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39139. if (!this._vertexBuffers) {
  39140. if (this._delayInfo) {
  39141. return this._delayInfo.indexOf(kind) !== -1;
  39142. }
  39143. return false;
  39144. }
  39145. return this._vertexBuffers[kind] !== undefined;
  39146. };
  39147. /**
  39148. * Gets a list of all attached data kinds (Position, normal, etc...)
  39149. * @returns a list of string containing all kinds
  39150. */
  39151. Geometry.prototype.getVerticesDataKinds = function () {
  39152. var result = [];
  39153. var kind;
  39154. if (!this._vertexBuffers && this._delayInfo) {
  39155. for (kind in this._delayInfo) {
  39156. result.push(kind);
  39157. }
  39158. }
  39159. else {
  39160. for (kind in this._vertexBuffers) {
  39161. result.push(kind);
  39162. }
  39163. }
  39164. return result;
  39165. };
  39166. /**
  39167. * Update index buffer
  39168. * @param indices defines the indices to store in the index buffer
  39169. * @param offset defines the offset in the target buffer where to store the data
  39170. */
  39171. Geometry.prototype.updateIndices = function (indices, offset) {
  39172. if (!this._indexBuffer) {
  39173. return;
  39174. }
  39175. if (!this._indexBufferIsUpdatable) {
  39176. this.setIndices(indices, null, true);
  39177. }
  39178. else {
  39179. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39180. }
  39181. };
  39182. /**
  39183. * Creates a new index buffer
  39184. * @param indices defines the indices to store in the index buffer
  39185. * @param totalVertices defines the total number of vertices (could be null)
  39186. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39187. */
  39188. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39189. if (totalVertices === void 0) { totalVertices = null; }
  39190. if (updatable === void 0) { updatable = false; }
  39191. if (this._indexBuffer) {
  39192. this._engine._releaseBuffer(this._indexBuffer);
  39193. }
  39194. this._disposeVertexArrayObjects();
  39195. this._indices = indices;
  39196. this._indexBufferIsUpdatable = updatable;
  39197. if (this._meshes.length !== 0 && this._indices) {
  39198. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39199. }
  39200. if (totalVertices != undefined) { // including null and undefined
  39201. this._totalVertices = totalVertices;
  39202. }
  39203. var meshes = this._meshes;
  39204. var numOfMeshes = meshes.length;
  39205. for (var index = 0; index < numOfMeshes; index++) {
  39206. meshes[index]._createGlobalSubMesh(true);
  39207. }
  39208. this.notifyUpdate();
  39209. };
  39210. /**
  39211. * Return the total number of indices
  39212. * @returns the total number of indices
  39213. */
  39214. Geometry.prototype.getTotalIndices = function () {
  39215. if (!this.isReady()) {
  39216. return 0;
  39217. }
  39218. return this._indices.length;
  39219. };
  39220. /**
  39221. * Gets the index buffer array
  39222. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39223. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39224. * @returns the index buffer array
  39225. */
  39226. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39227. if (!this.isReady()) {
  39228. return null;
  39229. }
  39230. var orig = this._indices;
  39231. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39232. return orig;
  39233. }
  39234. else {
  39235. var len = orig.length;
  39236. var copy = [];
  39237. for (var i = 0; i < len; i++) {
  39238. copy.push(orig[i]);
  39239. }
  39240. return copy;
  39241. }
  39242. };
  39243. /**
  39244. * Gets the index buffer
  39245. * @return the index buffer
  39246. */
  39247. Geometry.prototype.getIndexBuffer = function () {
  39248. if (!this.isReady()) {
  39249. return null;
  39250. }
  39251. return this._indexBuffer;
  39252. };
  39253. /** @hidden */
  39254. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39255. if (effect === void 0) { effect = null; }
  39256. if (!effect || !this._vertexArrayObjects) {
  39257. return;
  39258. }
  39259. if (this._vertexArrayObjects[effect.key]) {
  39260. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39261. delete this._vertexArrayObjects[effect.key];
  39262. }
  39263. };
  39264. /**
  39265. * Release the associated resources for a specific mesh
  39266. * @param mesh defines the source mesh
  39267. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39268. */
  39269. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39270. var meshes = this._meshes;
  39271. var index = meshes.indexOf(mesh);
  39272. if (index === -1) {
  39273. return;
  39274. }
  39275. meshes.splice(index, 1);
  39276. mesh._geometry = null;
  39277. if (meshes.length === 0 && shouldDispose) {
  39278. this.dispose();
  39279. }
  39280. };
  39281. /**
  39282. * Apply current geometry to a given mesh
  39283. * @param mesh defines the mesh to apply geometry to
  39284. */
  39285. Geometry.prototype.applyToMesh = function (mesh) {
  39286. if (mesh._geometry === this) {
  39287. return;
  39288. }
  39289. var previousGeometry = mesh._geometry;
  39290. if (previousGeometry) {
  39291. previousGeometry.releaseForMesh(mesh);
  39292. }
  39293. var meshes = this._meshes;
  39294. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39295. mesh._geometry = this;
  39296. this._scene.pushGeometry(this);
  39297. meshes.push(mesh);
  39298. if (this.isReady()) {
  39299. this._applyToMesh(mesh);
  39300. }
  39301. else {
  39302. mesh._boundingInfo = this._boundingInfo;
  39303. }
  39304. };
  39305. Geometry.prototype._updateExtend = function (data) {
  39306. if (data === void 0) { data = null; }
  39307. if (!data) {
  39308. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39309. }
  39310. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39311. };
  39312. Geometry.prototype._applyToMesh = function (mesh) {
  39313. var numOfMeshes = this._meshes.length;
  39314. // vertexBuffers
  39315. for (var kind in this._vertexBuffers) {
  39316. if (numOfMeshes === 1) {
  39317. this._vertexBuffers[kind].create();
  39318. }
  39319. var buffer = this._vertexBuffers[kind].getBuffer();
  39320. if (buffer)
  39321. buffer.references = numOfMeshes;
  39322. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39323. if (!this._extend) {
  39324. this._updateExtend();
  39325. }
  39326. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39327. mesh._createGlobalSubMesh(false);
  39328. //bounding info was just created again, world matrix should be applied again.
  39329. mesh._updateBoundingInfo();
  39330. }
  39331. }
  39332. // indexBuffer
  39333. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39334. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39335. }
  39336. if (this._indexBuffer) {
  39337. this._indexBuffer.references = numOfMeshes;
  39338. }
  39339. };
  39340. Geometry.prototype.notifyUpdate = function (kind) {
  39341. if (this.onGeometryUpdated) {
  39342. this.onGeometryUpdated(this, kind);
  39343. }
  39344. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39345. var mesh = _a[_i];
  39346. mesh._markSubMeshesAsAttributesDirty();
  39347. }
  39348. };
  39349. /**
  39350. * Load the geometry if it was flagged as delay loaded
  39351. * @param scene defines the hosting scene
  39352. * @param onLoaded defines a callback called when the geometry is loaded
  39353. */
  39354. Geometry.prototype.load = function (scene, onLoaded) {
  39355. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39356. return;
  39357. }
  39358. if (this.isReady()) {
  39359. if (onLoaded) {
  39360. onLoaded();
  39361. }
  39362. return;
  39363. }
  39364. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39365. this._queueLoad(scene, onLoaded);
  39366. };
  39367. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39368. var _this = this;
  39369. if (!this.delayLoadingFile) {
  39370. return;
  39371. }
  39372. scene._addPendingData(this);
  39373. scene._loadFile(this.delayLoadingFile, function (data) {
  39374. if (!_this._delayLoadingFunction) {
  39375. return;
  39376. }
  39377. _this._delayLoadingFunction(JSON.parse(data), _this);
  39378. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39379. _this._delayInfo = [];
  39380. scene._removePendingData(_this);
  39381. var meshes = _this._meshes;
  39382. var numOfMeshes = meshes.length;
  39383. for (var index = 0; index < numOfMeshes; index++) {
  39384. _this._applyToMesh(meshes[index]);
  39385. }
  39386. if (onLoaded) {
  39387. onLoaded();
  39388. }
  39389. }, undefined, true);
  39390. };
  39391. /**
  39392. * Invert the geometry to move from a right handed system to a left handed one.
  39393. */
  39394. Geometry.prototype.toLeftHanded = function () {
  39395. // Flip faces
  39396. var tIndices = this.getIndices(false);
  39397. if (tIndices != null && tIndices.length > 0) {
  39398. for (var i = 0; i < tIndices.length; i += 3) {
  39399. var tTemp = tIndices[i + 0];
  39400. tIndices[i + 0] = tIndices[i + 2];
  39401. tIndices[i + 2] = tTemp;
  39402. }
  39403. this.setIndices(tIndices);
  39404. }
  39405. // Negate position.z
  39406. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39407. if (tPositions != null && tPositions.length > 0) {
  39408. for (var i = 0; i < tPositions.length; i += 3) {
  39409. tPositions[i + 2] = -tPositions[i + 2];
  39410. }
  39411. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39412. }
  39413. // Negate normal.z
  39414. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39415. if (tNormals != null && tNormals.length > 0) {
  39416. for (var i = 0; i < tNormals.length; i += 3) {
  39417. tNormals[i + 2] = -tNormals[i + 2];
  39418. }
  39419. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39420. }
  39421. };
  39422. // Cache
  39423. /** @hidden */
  39424. Geometry.prototype._resetPointsArrayCache = function () {
  39425. this._positions = null;
  39426. };
  39427. /** @hidden */
  39428. Geometry.prototype._generatePointsArray = function () {
  39429. if (this._positions)
  39430. return true;
  39431. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39432. if (!data || data.length === 0) {
  39433. return false;
  39434. }
  39435. this._positions = [];
  39436. for (var index = 0; index < data.length; index += 3) {
  39437. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39438. }
  39439. return true;
  39440. };
  39441. /**
  39442. * Gets a value indicating if the geometry is disposed
  39443. * @returns true if the geometry was disposed
  39444. */
  39445. Geometry.prototype.isDisposed = function () {
  39446. return this._isDisposed;
  39447. };
  39448. Geometry.prototype._disposeVertexArrayObjects = function () {
  39449. if (this._vertexArrayObjects) {
  39450. for (var kind in this._vertexArrayObjects) {
  39451. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39452. }
  39453. this._vertexArrayObjects = {};
  39454. }
  39455. };
  39456. /**
  39457. * Free all associated resources
  39458. */
  39459. Geometry.prototype.dispose = function () {
  39460. var meshes = this._meshes;
  39461. var numOfMeshes = meshes.length;
  39462. var index;
  39463. for (index = 0; index < numOfMeshes; index++) {
  39464. this.releaseForMesh(meshes[index]);
  39465. }
  39466. this._meshes = [];
  39467. this._disposeVertexArrayObjects();
  39468. for (var kind in this._vertexBuffers) {
  39469. this._vertexBuffers[kind].dispose();
  39470. }
  39471. this._vertexBuffers = {};
  39472. this._totalVertices = 0;
  39473. if (this._indexBuffer) {
  39474. this._engine._releaseBuffer(this._indexBuffer);
  39475. }
  39476. this._indexBuffer = null;
  39477. this._indices = [];
  39478. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39479. this.delayLoadingFile = null;
  39480. this._delayLoadingFunction = null;
  39481. this._delayInfo = [];
  39482. this._boundingInfo = null;
  39483. this._scene.removeGeometry(this);
  39484. this._isDisposed = true;
  39485. };
  39486. /**
  39487. * Clone the current geometry into a new geometry
  39488. * @param id defines the unique ID of the new geometry
  39489. * @returns a new geometry object
  39490. */
  39491. Geometry.prototype.copy = function (id) {
  39492. var vertexData = new BABYLON.VertexData();
  39493. vertexData.indices = [];
  39494. var indices = this.getIndices();
  39495. if (indices) {
  39496. for (var index = 0; index < indices.length; index++) {
  39497. vertexData.indices.push(indices[index]);
  39498. }
  39499. }
  39500. var updatable = false;
  39501. var stopChecking = false;
  39502. var kind;
  39503. for (kind in this._vertexBuffers) {
  39504. // using slice() to make a copy of the array and not just reference it
  39505. var data = this.getVerticesData(kind);
  39506. if (data instanceof Float32Array) {
  39507. vertexData.set(new Float32Array(data), kind);
  39508. }
  39509. else {
  39510. vertexData.set(data.slice(0), kind);
  39511. }
  39512. if (!stopChecking) {
  39513. var vb = this.getVertexBuffer(kind);
  39514. if (vb) {
  39515. updatable = vb.isUpdatable();
  39516. stopChecking = !updatable;
  39517. }
  39518. }
  39519. }
  39520. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39521. geometry.delayLoadState = this.delayLoadState;
  39522. geometry.delayLoadingFile = this.delayLoadingFile;
  39523. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39524. for (kind in this._delayInfo) {
  39525. geometry._delayInfo = geometry._delayInfo || [];
  39526. geometry._delayInfo.push(kind);
  39527. }
  39528. // Bounding info
  39529. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39530. return geometry;
  39531. };
  39532. /**
  39533. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39534. * @return a JSON representation of the current geometry data (without the vertices data)
  39535. */
  39536. Geometry.prototype.serialize = function () {
  39537. var serializationObject = {};
  39538. serializationObject.id = this.id;
  39539. serializationObject.updatable = this._updatable;
  39540. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39541. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39542. }
  39543. return serializationObject;
  39544. };
  39545. Geometry.prototype.toNumberArray = function (origin) {
  39546. if (Array.isArray(origin)) {
  39547. return origin;
  39548. }
  39549. else {
  39550. return Array.prototype.slice.call(origin);
  39551. }
  39552. };
  39553. /**
  39554. * Serialize all vertices data into a JSON oject
  39555. * @returns a JSON representation of the current geometry data
  39556. */
  39557. Geometry.prototype.serializeVerticeData = function () {
  39558. var serializationObject = this.serialize();
  39559. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39560. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39561. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39562. serializationObject.positions._updatable = true;
  39563. }
  39564. }
  39565. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39566. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39567. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39568. serializationObject.normals._updatable = true;
  39569. }
  39570. }
  39571. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39572. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39573. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39574. serializationObject.tangets._updatable = true;
  39575. }
  39576. }
  39577. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39578. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39579. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39580. serializationObject.uvs._updatable = true;
  39581. }
  39582. }
  39583. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39584. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39585. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39586. serializationObject.uv2s._updatable = true;
  39587. }
  39588. }
  39589. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39590. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39591. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39592. serializationObject.uv3s._updatable = true;
  39593. }
  39594. }
  39595. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39596. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39597. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39598. serializationObject.uv4s._updatable = true;
  39599. }
  39600. }
  39601. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39602. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39603. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39604. serializationObject.uv5s._updatable = true;
  39605. }
  39606. }
  39607. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39608. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39609. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39610. serializationObject.uv6s._updatable = true;
  39611. }
  39612. }
  39613. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39614. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39615. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39616. serializationObject.colors._updatable = true;
  39617. }
  39618. }
  39619. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39620. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39621. serializationObject.matricesIndices._isExpanded = true;
  39622. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39623. serializationObject.matricesIndices._updatable = true;
  39624. }
  39625. }
  39626. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39627. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39628. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39629. serializationObject.matricesWeights._updatable = true;
  39630. }
  39631. }
  39632. serializationObject.indices = this.toNumberArray(this.getIndices());
  39633. return serializationObject;
  39634. };
  39635. // Statics
  39636. /**
  39637. * Extracts a clone of a mesh geometry
  39638. * @param mesh defines the source mesh
  39639. * @param id defines the unique ID of the new geometry object
  39640. * @returns the new geometry object
  39641. */
  39642. Geometry.ExtractFromMesh = function (mesh, id) {
  39643. var geometry = mesh._geometry;
  39644. if (!geometry) {
  39645. return null;
  39646. }
  39647. return geometry.copy(id);
  39648. };
  39649. /**
  39650. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39651. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39652. * Be aware Math.random() could cause collisions, but:
  39653. * "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"
  39654. * @returns a string containing a new GUID
  39655. */
  39656. Geometry.RandomId = function () {
  39657. return BABYLON.Tools.RandomId();
  39658. };
  39659. /** @hidden */
  39660. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39661. var scene = mesh.getScene();
  39662. // Geometry
  39663. var geometryId = parsedGeometry.geometryId;
  39664. if (geometryId) {
  39665. var geometry = scene.getGeometryByID(geometryId);
  39666. if (geometry) {
  39667. geometry.applyToMesh(mesh);
  39668. }
  39669. }
  39670. else if (parsedGeometry instanceof ArrayBuffer) {
  39671. var binaryInfo = mesh._binaryInfo;
  39672. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39673. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39674. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39675. }
  39676. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39677. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39678. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39679. }
  39680. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39681. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39682. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39683. }
  39684. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39685. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39686. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39687. }
  39688. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39689. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39690. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39691. }
  39692. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39693. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39694. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39695. }
  39696. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39697. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39698. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39699. }
  39700. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39701. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39702. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39703. }
  39704. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39705. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39706. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39707. }
  39708. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39709. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39710. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39711. }
  39712. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39713. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39714. var floatIndices = [];
  39715. for (var i = 0; i < matricesIndicesData.length; i++) {
  39716. var index = matricesIndicesData[i];
  39717. floatIndices.push(index & 0x000000FF);
  39718. floatIndices.push((index & 0x0000FF00) >> 8);
  39719. floatIndices.push((index & 0x00FF0000) >> 16);
  39720. floatIndices.push(index >> 24);
  39721. }
  39722. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39723. }
  39724. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39725. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39726. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39727. }
  39728. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39729. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39730. mesh.setIndices(indicesData, null);
  39731. }
  39732. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39733. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39734. mesh.subMeshes = [];
  39735. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39736. var materialIndex = subMeshesData[(i * 5) + 0];
  39737. var verticesStart = subMeshesData[(i * 5) + 1];
  39738. var verticesCount = subMeshesData[(i * 5) + 2];
  39739. var indexStart = subMeshesData[(i * 5) + 3];
  39740. var indexCount = subMeshesData[(i * 5) + 4];
  39741. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39742. }
  39743. }
  39744. }
  39745. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39746. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39747. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39748. if (parsedGeometry.tangents) {
  39749. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39750. }
  39751. if (parsedGeometry.uvs) {
  39752. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39753. }
  39754. if (parsedGeometry.uvs2) {
  39755. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39756. }
  39757. if (parsedGeometry.uvs3) {
  39758. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39759. }
  39760. if (parsedGeometry.uvs4) {
  39761. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39762. }
  39763. if (parsedGeometry.uvs5) {
  39764. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39765. }
  39766. if (parsedGeometry.uvs6) {
  39767. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39768. }
  39769. if (parsedGeometry.colors) {
  39770. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39771. }
  39772. if (parsedGeometry.matricesIndices) {
  39773. if (!parsedGeometry.matricesIndices._isExpanded) {
  39774. var floatIndices = [];
  39775. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39776. var matricesIndex = parsedGeometry.matricesIndices[i];
  39777. floatIndices.push(matricesIndex & 0x000000FF);
  39778. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39779. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39780. floatIndices.push(matricesIndex >> 24);
  39781. }
  39782. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39783. }
  39784. else {
  39785. delete parsedGeometry.matricesIndices._isExpanded;
  39786. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39787. }
  39788. }
  39789. if (parsedGeometry.matricesIndicesExtra) {
  39790. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39791. var floatIndices = [];
  39792. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39793. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39794. floatIndices.push(matricesIndex & 0x000000FF);
  39795. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39796. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39797. floatIndices.push(matricesIndex >> 24);
  39798. }
  39799. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39800. }
  39801. else {
  39802. delete parsedGeometry.matricesIndices._isExpanded;
  39803. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39804. }
  39805. }
  39806. if (parsedGeometry.matricesWeights) {
  39807. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39808. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39809. }
  39810. if (parsedGeometry.matricesWeightsExtra) {
  39811. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39812. }
  39813. mesh.setIndices(parsedGeometry.indices, null);
  39814. }
  39815. // SubMeshes
  39816. if (parsedGeometry.subMeshes) {
  39817. mesh.subMeshes = [];
  39818. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39819. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39820. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39821. }
  39822. }
  39823. // Flat shading
  39824. if (mesh._shouldGenerateFlatShading) {
  39825. mesh.convertToFlatShadedMesh();
  39826. delete mesh._shouldGenerateFlatShading;
  39827. }
  39828. // Update
  39829. mesh.computeWorldMatrix(true);
  39830. scene.onMeshImportedObservable.notifyObservers(mesh);
  39831. };
  39832. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39833. var epsilon = 1e-3;
  39834. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39835. return;
  39836. }
  39837. var noInfluenceBoneIndex = 0.0;
  39838. if (parsedGeometry.skeletonId > -1) {
  39839. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39840. if (!skeleton) {
  39841. return;
  39842. }
  39843. noInfluenceBoneIndex = skeleton.bones.length;
  39844. }
  39845. else {
  39846. return;
  39847. }
  39848. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39849. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39850. var matricesWeights = parsedGeometry.matricesWeights;
  39851. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39852. var influencers = parsedGeometry.numBoneInfluencer;
  39853. var size = matricesWeights.length;
  39854. for (var i = 0; i < size; i += 4) {
  39855. var weight = 0.0;
  39856. var firstZeroWeight = -1;
  39857. for (var j = 0; j < 4; j++) {
  39858. var w = matricesWeights[i + j];
  39859. weight += w;
  39860. if (w < epsilon && firstZeroWeight < 0) {
  39861. firstZeroWeight = j;
  39862. }
  39863. }
  39864. if (matricesWeightsExtra) {
  39865. for (var j = 0; j < 4; j++) {
  39866. var w = matricesWeightsExtra[i + j];
  39867. weight += w;
  39868. if (w < epsilon && firstZeroWeight < 0) {
  39869. firstZeroWeight = j + 4;
  39870. }
  39871. }
  39872. }
  39873. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39874. firstZeroWeight = influencers - 1;
  39875. }
  39876. if (weight > epsilon) {
  39877. var mweight = 1.0 / weight;
  39878. for (var j = 0; j < 4; j++) {
  39879. matricesWeights[i + j] *= mweight;
  39880. }
  39881. if (matricesWeightsExtra) {
  39882. for (var j = 0; j < 4; j++) {
  39883. matricesWeightsExtra[i + j] *= mweight;
  39884. }
  39885. }
  39886. }
  39887. else {
  39888. if (firstZeroWeight >= 4) {
  39889. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39890. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39891. }
  39892. else {
  39893. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39894. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39895. }
  39896. }
  39897. }
  39898. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39899. if (parsedGeometry.matricesWeightsExtra) {
  39900. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39901. }
  39902. };
  39903. /**
  39904. * Create a new geometry from persisted data (Using .babylon file format)
  39905. * @param parsedVertexData defines the persisted data
  39906. * @param scene defines the hosting scene
  39907. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39908. * @returns the new geometry object
  39909. */
  39910. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39911. if (scene.getGeometryByID(parsedVertexData.id)) {
  39912. return null; // null since geometry could be something else than a box...
  39913. }
  39914. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39915. if (BABYLON.Tags) {
  39916. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39917. }
  39918. if (parsedVertexData.delayLoadingFile) {
  39919. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39920. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39921. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39922. geometry._delayInfo = [];
  39923. if (parsedVertexData.hasUVs) {
  39924. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39925. }
  39926. if (parsedVertexData.hasUVs2) {
  39927. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39928. }
  39929. if (parsedVertexData.hasUVs3) {
  39930. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39931. }
  39932. if (parsedVertexData.hasUVs4) {
  39933. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39934. }
  39935. if (parsedVertexData.hasUVs5) {
  39936. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39937. }
  39938. if (parsedVertexData.hasUVs6) {
  39939. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39940. }
  39941. if (parsedVertexData.hasColors) {
  39942. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39943. }
  39944. if (parsedVertexData.hasMatricesIndices) {
  39945. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39946. }
  39947. if (parsedVertexData.hasMatricesWeights) {
  39948. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39949. }
  39950. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39951. }
  39952. else {
  39953. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39954. }
  39955. scene.pushGeometry(geometry, true);
  39956. return geometry;
  39957. };
  39958. return Geometry;
  39959. }());
  39960. BABYLON.Geometry = Geometry;
  39961. // Primitives
  39962. /// Abstract class
  39963. /**
  39964. * Abstract class used to provide common services for all typed geometries
  39965. * @hidden
  39966. */
  39967. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39968. __extends(_PrimitiveGeometry, _super);
  39969. /**
  39970. * Creates a new typed geometry
  39971. * @param id defines the unique ID of the geometry
  39972. * @param scene defines the hosting scene
  39973. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39974. * @param mesh defines the hosting mesh (can be null)
  39975. */
  39976. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39977. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39978. if (mesh === void 0) { mesh = null; }
  39979. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39980. _this._canBeRegenerated = _canBeRegenerated;
  39981. _this._beingRegenerated = true;
  39982. _this.regenerate();
  39983. _this._beingRegenerated = false;
  39984. return _this;
  39985. }
  39986. /**
  39987. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39988. * @returns true if the geometry can be regenerated
  39989. */
  39990. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39991. return this._canBeRegenerated;
  39992. };
  39993. /**
  39994. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39995. */
  39996. _PrimitiveGeometry.prototype.regenerate = function () {
  39997. if (!this._canBeRegenerated) {
  39998. return;
  39999. }
  40000. this._beingRegenerated = true;
  40001. this.setAllVerticesData(this._regenerateVertexData(), false);
  40002. this._beingRegenerated = false;
  40003. };
  40004. /**
  40005. * Clone the geometry
  40006. * @param id defines the unique ID of the new geometry
  40007. * @returns the new geometry
  40008. */
  40009. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40010. return _super.prototype.copy.call(this, id);
  40011. };
  40012. // overrides
  40013. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40014. if (!this._beingRegenerated) {
  40015. return;
  40016. }
  40017. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40018. };
  40019. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40020. if (!this._beingRegenerated) {
  40021. return;
  40022. }
  40023. _super.prototype.setVerticesData.call(this, kind, data, false);
  40024. };
  40025. // to override
  40026. /** @hidden */
  40027. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40028. throw new Error("Abstract method");
  40029. };
  40030. _PrimitiveGeometry.prototype.copy = function (id) {
  40031. throw new Error("Must be overriden in sub-classes.");
  40032. };
  40033. _PrimitiveGeometry.prototype.serialize = function () {
  40034. var serializationObject = _super.prototype.serialize.call(this);
  40035. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40036. return serializationObject;
  40037. };
  40038. return _PrimitiveGeometry;
  40039. }(Geometry));
  40040. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40041. /**
  40042. * Creates a ribbon geometry
  40043. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40044. */
  40045. var RibbonGeometry = /** @class */ (function (_super) {
  40046. __extends(RibbonGeometry, _super);
  40047. /**
  40048. * Creates a ribbon geometry
  40049. * @param id defines the unique ID of the geometry
  40050. * @param scene defines the hosting scene
  40051. * @param pathArray defines the array of paths to use
  40052. * @param closeArray defines if the last path and the first path must be joined
  40053. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40054. * @param offset defines the offset between points
  40055. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40056. * @param mesh defines the hosting mesh (can be null)
  40057. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40058. */
  40059. function RibbonGeometry(id, scene,
  40060. /**
  40061. * Defines the array of paths to use
  40062. */
  40063. pathArray,
  40064. /**
  40065. * Defines if the last and first points of each path in your pathArray must be joined
  40066. */
  40067. closeArray,
  40068. /**
  40069. * Defines if the last and first points of each path in your pathArray must be joined
  40070. */
  40071. closePath,
  40072. /**
  40073. * Defines the offset between points
  40074. */
  40075. offset, canBeRegenerated, mesh,
  40076. /**
  40077. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40078. */
  40079. side) {
  40080. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40081. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40082. _this.pathArray = pathArray;
  40083. _this.closeArray = closeArray;
  40084. _this.closePath = closePath;
  40085. _this.offset = offset;
  40086. _this.side = side;
  40087. return _this;
  40088. }
  40089. /** @hidden */
  40090. RibbonGeometry.prototype._regenerateVertexData = function () {
  40091. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40092. };
  40093. RibbonGeometry.prototype.copy = function (id) {
  40094. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40095. };
  40096. return RibbonGeometry;
  40097. }(_PrimitiveGeometry));
  40098. BABYLON.RibbonGeometry = RibbonGeometry;
  40099. /**
  40100. * Creates a box geometry
  40101. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40102. */
  40103. var BoxGeometry = /** @class */ (function (_super) {
  40104. __extends(BoxGeometry, _super);
  40105. /**
  40106. * Creates a box geometry
  40107. * @param id defines the unique ID of the geometry
  40108. * @param scene defines the hosting scene
  40109. * @param size defines the zise of the box (width, height and depth are the same)
  40110. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40111. * @param mesh defines the hosting mesh (can be null)
  40112. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40113. */
  40114. function BoxGeometry(id, scene,
  40115. /**
  40116. * Defines the zise of the box (width, height and depth are the same)
  40117. */
  40118. size, canBeRegenerated, mesh,
  40119. /**
  40120. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40121. */
  40122. side) {
  40123. if (mesh === void 0) { mesh = null; }
  40124. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40125. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40126. _this.size = size;
  40127. _this.side = side;
  40128. return _this;
  40129. }
  40130. /** @hidden */
  40131. BoxGeometry.prototype._regenerateVertexData = function () {
  40132. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40133. };
  40134. BoxGeometry.prototype.copy = function (id) {
  40135. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40136. };
  40137. BoxGeometry.prototype.serialize = function () {
  40138. var serializationObject = _super.prototype.serialize.call(this);
  40139. serializationObject.size = this.size;
  40140. return serializationObject;
  40141. };
  40142. BoxGeometry.Parse = function (parsedBox, scene) {
  40143. if (scene.getGeometryByID(parsedBox.id)) {
  40144. return null; // null since geometry could be something else than a box...
  40145. }
  40146. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40147. if (BABYLON.Tags) {
  40148. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40149. }
  40150. scene.pushGeometry(box, true);
  40151. return box;
  40152. };
  40153. return BoxGeometry;
  40154. }(_PrimitiveGeometry));
  40155. BABYLON.BoxGeometry = BoxGeometry;
  40156. /**
  40157. * Creates a sphere geometry
  40158. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40159. */
  40160. var SphereGeometry = /** @class */ (function (_super) {
  40161. __extends(SphereGeometry, _super);
  40162. /**
  40163. * Create a new sphere geometry
  40164. * @param id defines the unique ID of the geometry
  40165. * @param scene defines the hosting scene
  40166. * @param segments defines the number of segments to use to create the sphere
  40167. * @param diameter defines the diameter of the sphere
  40168. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40169. * @param mesh defines the hosting mesh (can be null)
  40170. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40171. */
  40172. function SphereGeometry(id, scene,
  40173. /**
  40174. * Defines the number of segments to use to create the sphere
  40175. */
  40176. segments,
  40177. /**
  40178. * Defines the diameter of the sphere
  40179. */
  40180. diameter, canBeRegenerated, mesh,
  40181. /**
  40182. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40183. */
  40184. side) {
  40185. if (mesh === void 0) { mesh = null; }
  40186. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40187. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40188. _this.segments = segments;
  40189. _this.diameter = diameter;
  40190. _this.side = side;
  40191. return _this;
  40192. }
  40193. /** @hidden */
  40194. SphereGeometry.prototype._regenerateVertexData = function () {
  40195. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40196. };
  40197. SphereGeometry.prototype.copy = function (id) {
  40198. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40199. };
  40200. SphereGeometry.prototype.serialize = function () {
  40201. var serializationObject = _super.prototype.serialize.call(this);
  40202. serializationObject.segments = this.segments;
  40203. serializationObject.diameter = this.diameter;
  40204. return serializationObject;
  40205. };
  40206. SphereGeometry.Parse = function (parsedSphere, scene) {
  40207. if (scene.getGeometryByID(parsedSphere.id)) {
  40208. return null; // null since geometry could be something else than a sphere...
  40209. }
  40210. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40211. if (BABYLON.Tags) {
  40212. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40213. }
  40214. scene.pushGeometry(sphere, true);
  40215. return sphere;
  40216. };
  40217. return SphereGeometry;
  40218. }(_PrimitiveGeometry));
  40219. BABYLON.SphereGeometry = SphereGeometry;
  40220. /**
  40221. * Creates a disc geometry
  40222. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40223. */
  40224. var DiscGeometry = /** @class */ (function (_super) {
  40225. __extends(DiscGeometry, _super);
  40226. /**
  40227. * Creates a new disc geometry
  40228. * @param id defines the unique ID of the geometry
  40229. * @param scene defines the hosting scene
  40230. * @param radius defines the radius of the disc
  40231. * @param tessellation defines the tesselation factor to apply to the disc
  40232. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40233. * @param mesh defines the hosting mesh (can be null)
  40234. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40235. */
  40236. function DiscGeometry(id, scene,
  40237. /**
  40238. * Defines the radius of the disc
  40239. */
  40240. radius,
  40241. /**
  40242. * Defines the tesselation factor to apply to the disc
  40243. */
  40244. tessellation, canBeRegenerated, mesh,
  40245. /**
  40246. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40247. */
  40248. side) {
  40249. if (mesh === void 0) { mesh = null; }
  40250. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40251. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40252. _this.radius = radius;
  40253. _this.tessellation = tessellation;
  40254. _this.side = side;
  40255. return _this;
  40256. }
  40257. /** @hidden */
  40258. DiscGeometry.prototype._regenerateVertexData = function () {
  40259. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40260. };
  40261. DiscGeometry.prototype.copy = function (id) {
  40262. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40263. };
  40264. return DiscGeometry;
  40265. }(_PrimitiveGeometry));
  40266. BABYLON.DiscGeometry = DiscGeometry;
  40267. /**
  40268. * Creates a new cylinder geometry
  40269. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40270. */
  40271. var CylinderGeometry = /** @class */ (function (_super) {
  40272. __extends(CylinderGeometry, _super);
  40273. /**
  40274. * Creates a new cylinder geometry
  40275. * @param id defines the unique ID of the geometry
  40276. * @param scene defines the hosting scene
  40277. * @param height defines the height of the cylinder
  40278. * @param diameterTop defines the diameter of the cylinder's top cap
  40279. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40280. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40281. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40282. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40283. * @param mesh defines the hosting mesh (can be null)
  40284. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40285. */
  40286. function CylinderGeometry(id, scene,
  40287. /**
  40288. * Defines the height of the cylinder
  40289. */
  40290. height,
  40291. /**
  40292. * Defines the diameter of the cylinder's top cap
  40293. */
  40294. diameterTop,
  40295. /**
  40296. * Defines the diameter of the cylinder's bottom cap
  40297. */
  40298. diameterBottom,
  40299. /**
  40300. * Defines the tessellation factor to apply to the cylinder
  40301. */
  40302. tessellation,
  40303. /**
  40304. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40305. */
  40306. subdivisions, canBeRegenerated, mesh,
  40307. /**
  40308. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40309. */
  40310. side) {
  40311. if (subdivisions === void 0) { subdivisions = 1; }
  40312. if (mesh === void 0) { mesh = null; }
  40313. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40314. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40315. _this.height = height;
  40316. _this.diameterTop = diameterTop;
  40317. _this.diameterBottom = diameterBottom;
  40318. _this.tessellation = tessellation;
  40319. _this.subdivisions = subdivisions;
  40320. _this.side = side;
  40321. return _this;
  40322. }
  40323. /** @hidden */
  40324. CylinderGeometry.prototype._regenerateVertexData = function () {
  40325. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40326. };
  40327. CylinderGeometry.prototype.copy = function (id) {
  40328. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40329. };
  40330. CylinderGeometry.prototype.serialize = function () {
  40331. var serializationObject = _super.prototype.serialize.call(this);
  40332. serializationObject.height = this.height;
  40333. serializationObject.diameterTop = this.diameterTop;
  40334. serializationObject.diameterBottom = this.diameterBottom;
  40335. serializationObject.tessellation = this.tessellation;
  40336. return serializationObject;
  40337. };
  40338. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40339. if (scene.getGeometryByID(parsedCylinder.id)) {
  40340. return null; // null since geometry could be something else than a cylinder...
  40341. }
  40342. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40343. if (BABYLON.Tags) {
  40344. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40345. }
  40346. scene.pushGeometry(cylinder, true);
  40347. return cylinder;
  40348. };
  40349. return CylinderGeometry;
  40350. }(_PrimitiveGeometry));
  40351. BABYLON.CylinderGeometry = CylinderGeometry;
  40352. /**
  40353. * Creates a new torus geometry
  40354. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40355. */
  40356. var TorusGeometry = /** @class */ (function (_super) {
  40357. __extends(TorusGeometry, _super);
  40358. /**
  40359. * Creates a new torus geometry
  40360. * @param id defines the unique ID of the geometry
  40361. * @param scene defines the hosting scene
  40362. * @param diameter defines the diameter of the torus
  40363. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40364. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40365. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40366. * @param mesh defines the hosting mesh (can be null)
  40367. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40368. */
  40369. function TorusGeometry(id, scene,
  40370. /**
  40371. * Defines the diameter of the torus
  40372. */
  40373. diameter,
  40374. /**
  40375. * Defines the thickness of the torus (ie. internal diameter)
  40376. */
  40377. thickness,
  40378. /**
  40379. * Defines the tesselation factor to apply to the torus
  40380. */
  40381. tessellation, canBeRegenerated, mesh,
  40382. /**
  40383. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40384. */
  40385. side) {
  40386. if (mesh === void 0) { mesh = null; }
  40387. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40388. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40389. _this.diameter = diameter;
  40390. _this.thickness = thickness;
  40391. _this.tessellation = tessellation;
  40392. _this.side = side;
  40393. return _this;
  40394. }
  40395. /** @hidden */
  40396. TorusGeometry.prototype._regenerateVertexData = function () {
  40397. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40398. };
  40399. TorusGeometry.prototype.copy = function (id) {
  40400. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40401. };
  40402. TorusGeometry.prototype.serialize = function () {
  40403. var serializationObject = _super.prototype.serialize.call(this);
  40404. serializationObject.diameter = this.diameter;
  40405. serializationObject.thickness = this.thickness;
  40406. serializationObject.tessellation = this.tessellation;
  40407. return serializationObject;
  40408. };
  40409. TorusGeometry.Parse = function (parsedTorus, scene) {
  40410. if (scene.getGeometryByID(parsedTorus.id)) {
  40411. return null; // null since geometry could be something else than a torus...
  40412. }
  40413. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40414. if (BABYLON.Tags) {
  40415. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40416. }
  40417. scene.pushGeometry(torus, true);
  40418. return torus;
  40419. };
  40420. return TorusGeometry;
  40421. }(_PrimitiveGeometry));
  40422. BABYLON.TorusGeometry = TorusGeometry;
  40423. /**
  40424. * Creates a new ground geometry
  40425. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40426. */
  40427. var GroundGeometry = /** @class */ (function (_super) {
  40428. __extends(GroundGeometry, _super);
  40429. /**
  40430. * Creates a new ground geometry
  40431. * @param id defines the unique ID of the geometry
  40432. * @param scene defines the hosting scene
  40433. * @param width defines the width of the ground
  40434. * @param height defines the height of the ground
  40435. * @param subdivisions defines the subdivisions to apply to the ground
  40436. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40437. * @param mesh defines the hosting mesh (can be null)
  40438. */
  40439. function GroundGeometry(id, scene,
  40440. /**
  40441. * Defines the width of the ground
  40442. */
  40443. width,
  40444. /**
  40445. * Defines the height of the ground
  40446. */
  40447. height,
  40448. /**
  40449. * Defines the subdivisions to apply to the ground
  40450. */
  40451. subdivisions, canBeRegenerated, mesh) {
  40452. if (mesh === void 0) { mesh = null; }
  40453. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40454. _this.width = width;
  40455. _this.height = height;
  40456. _this.subdivisions = subdivisions;
  40457. return _this;
  40458. }
  40459. /** @hidden */
  40460. GroundGeometry.prototype._regenerateVertexData = function () {
  40461. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40462. };
  40463. GroundGeometry.prototype.copy = function (id) {
  40464. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40465. };
  40466. GroundGeometry.prototype.serialize = function () {
  40467. var serializationObject = _super.prototype.serialize.call(this);
  40468. serializationObject.width = this.width;
  40469. serializationObject.height = this.height;
  40470. serializationObject.subdivisions = this.subdivisions;
  40471. return serializationObject;
  40472. };
  40473. GroundGeometry.Parse = function (parsedGround, scene) {
  40474. if (scene.getGeometryByID(parsedGround.id)) {
  40475. return null; // null since geometry could be something else than a ground...
  40476. }
  40477. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40478. if (BABYLON.Tags) {
  40479. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40480. }
  40481. scene.pushGeometry(ground, true);
  40482. return ground;
  40483. };
  40484. return GroundGeometry;
  40485. }(_PrimitiveGeometry));
  40486. BABYLON.GroundGeometry = GroundGeometry;
  40487. /**
  40488. * Creates a tiled ground geometry
  40489. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40490. */
  40491. var TiledGroundGeometry = /** @class */ (function (_super) {
  40492. __extends(TiledGroundGeometry, _super);
  40493. /**
  40494. * Creates a tiled ground geometry
  40495. * @param id defines the unique ID of the geometry
  40496. * @param scene defines the hosting scene
  40497. * @param xmin defines the minimum value on X axis
  40498. * @param zmin defines the minimum value on Z axis
  40499. * @param xmax defines the maximum value on X axis
  40500. * @param zmax defines the maximum value on Z axis
  40501. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40502. * @param precision defines the precision to use when computing the tiles
  40503. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40504. * @param mesh defines the hosting mesh (can be null)
  40505. */
  40506. function TiledGroundGeometry(id, scene,
  40507. /**
  40508. * Defines the minimum value on X axis
  40509. */
  40510. xmin,
  40511. /**
  40512. * Defines the minimum value on Z axis
  40513. */
  40514. zmin,
  40515. /**
  40516. * Defines the maximum value on X axis
  40517. */
  40518. xmax,
  40519. /**
  40520. * Defines the maximum value on Z axis
  40521. */
  40522. zmax,
  40523. /**
  40524. * Defines the subdivisions to apply to the ground
  40525. */
  40526. subdivisions,
  40527. /**
  40528. * Defines the precision to use when computing the tiles
  40529. */
  40530. precision, canBeRegenerated, mesh) {
  40531. if (mesh === void 0) { mesh = null; }
  40532. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40533. _this.xmin = xmin;
  40534. _this.zmin = zmin;
  40535. _this.xmax = xmax;
  40536. _this.zmax = zmax;
  40537. _this.subdivisions = subdivisions;
  40538. _this.precision = precision;
  40539. return _this;
  40540. }
  40541. /** @hidden */
  40542. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40543. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40544. };
  40545. TiledGroundGeometry.prototype.copy = function (id) {
  40546. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40547. };
  40548. return TiledGroundGeometry;
  40549. }(_PrimitiveGeometry));
  40550. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40551. /**
  40552. * Creates a plane geometry
  40553. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40554. */
  40555. var PlaneGeometry = /** @class */ (function (_super) {
  40556. __extends(PlaneGeometry, _super);
  40557. /**
  40558. * Creates a plane geometry
  40559. * @param id defines the unique ID of the geometry
  40560. * @param scene defines the hosting scene
  40561. * @param size defines the size of the plane (width === height)
  40562. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40563. * @param mesh defines the hosting mesh (can be null)
  40564. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40565. */
  40566. function PlaneGeometry(id, scene,
  40567. /**
  40568. * Defines the size of the plane (width === height)
  40569. */
  40570. size, canBeRegenerated, mesh,
  40571. /**
  40572. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40573. */
  40574. side) {
  40575. if (mesh === void 0) { mesh = null; }
  40576. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40577. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40578. _this.size = size;
  40579. _this.side = side;
  40580. return _this;
  40581. }
  40582. /** @hidden */
  40583. PlaneGeometry.prototype._regenerateVertexData = function () {
  40584. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40585. };
  40586. PlaneGeometry.prototype.copy = function (id) {
  40587. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40588. };
  40589. PlaneGeometry.prototype.serialize = function () {
  40590. var serializationObject = _super.prototype.serialize.call(this);
  40591. serializationObject.size = this.size;
  40592. return serializationObject;
  40593. };
  40594. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40595. if (scene.getGeometryByID(parsedPlane.id)) {
  40596. return null; // null since geometry could be something else than a ground...
  40597. }
  40598. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40599. if (BABYLON.Tags) {
  40600. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40601. }
  40602. scene.pushGeometry(plane, true);
  40603. return plane;
  40604. };
  40605. return PlaneGeometry;
  40606. }(_PrimitiveGeometry));
  40607. BABYLON.PlaneGeometry = PlaneGeometry;
  40608. /**
  40609. * Creates a torus knot geometry
  40610. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40611. */
  40612. var TorusKnotGeometry = /** @class */ (function (_super) {
  40613. __extends(TorusKnotGeometry, _super);
  40614. /**
  40615. * Creates a torus knot geometry
  40616. * @param id defines the unique ID of the geometry
  40617. * @param scene defines the hosting scene
  40618. * @param radius defines the radius of the torus knot
  40619. * @param tube defines the thickness of the torus knot tube
  40620. * @param radialSegments defines the number of radial segments
  40621. * @param tubularSegments defines the number of tubular segments
  40622. * @param p defines the first number of windings
  40623. * @param q defines the second number of windings
  40624. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40625. * @param mesh defines the hosting mesh (can be null)
  40626. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40627. */
  40628. function TorusKnotGeometry(id, scene,
  40629. /**
  40630. * Defines the radius of the torus knot
  40631. */
  40632. radius,
  40633. /**
  40634. * Defines the thickness of the torus knot tube
  40635. */
  40636. tube,
  40637. /**
  40638. * Defines the number of radial segments
  40639. */
  40640. radialSegments,
  40641. /**
  40642. * Defines the number of tubular segments
  40643. */
  40644. tubularSegments,
  40645. /**
  40646. * Defines the first number of windings
  40647. */
  40648. p,
  40649. /**
  40650. * Defines the second number of windings
  40651. */
  40652. q, canBeRegenerated, mesh,
  40653. /**
  40654. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40655. */
  40656. side) {
  40657. if (mesh === void 0) { mesh = null; }
  40658. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40659. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40660. _this.radius = radius;
  40661. _this.tube = tube;
  40662. _this.radialSegments = radialSegments;
  40663. _this.tubularSegments = tubularSegments;
  40664. _this.p = p;
  40665. _this.q = q;
  40666. _this.side = side;
  40667. return _this;
  40668. }
  40669. /** @hidden */
  40670. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40671. 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 });
  40672. };
  40673. TorusKnotGeometry.prototype.copy = function (id) {
  40674. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40675. };
  40676. TorusKnotGeometry.prototype.serialize = function () {
  40677. var serializationObject = _super.prototype.serialize.call(this);
  40678. serializationObject.radius = this.radius;
  40679. serializationObject.tube = this.tube;
  40680. serializationObject.radialSegments = this.radialSegments;
  40681. serializationObject.tubularSegments = this.tubularSegments;
  40682. serializationObject.p = this.p;
  40683. serializationObject.q = this.q;
  40684. return serializationObject;
  40685. };
  40686. ;
  40687. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40688. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40689. return null; // null since geometry could be something else than a ground...
  40690. }
  40691. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40692. if (BABYLON.Tags) {
  40693. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40694. }
  40695. scene.pushGeometry(torusKnot, true);
  40696. return torusKnot;
  40697. };
  40698. return TorusKnotGeometry;
  40699. }(_PrimitiveGeometry));
  40700. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40701. //}
  40702. })(BABYLON || (BABYLON = {}));
  40703. //# sourceMappingURL=babylon.geometry.js.map
  40704. var BABYLON;
  40705. (function (BABYLON) {
  40706. /**
  40707. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40708. */
  40709. var PerformanceMonitor = /** @class */ (function () {
  40710. /**
  40711. * constructor
  40712. * @param frameSampleSize The number of samples required to saturate the sliding window
  40713. */
  40714. function PerformanceMonitor(frameSampleSize) {
  40715. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40716. this._enabled = true;
  40717. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40718. }
  40719. /**
  40720. * Samples current frame
  40721. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40722. */
  40723. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40724. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40725. if (!this._enabled)
  40726. return;
  40727. if (this._lastFrameTimeMs != null) {
  40728. var dt = timeMs - this._lastFrameTimeMs;
  40729. this._rollingFrameTime.add(dt);
  40730. }
  40731. this._lastFrameTimeMs = timeMs;
  40732. };
  40733. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40734. /**
  40735. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40736. * @return Average frame time in milliseconds
  40737. */
  40738. get: function () {
  40739. return this._rollingFrameTime.average;
  40740. },
  40741. enumerable: true,
  40742. configurable: true
  40743. });
  40744. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40745. /**
  40746. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40747. * @return Frame time variance in milliseconds squared
  40748. */
  40749. get: function () {
  40750. return this._rollingFrameTime.variance;
  40751. },
  40752. enumerable: true,
  40753. configurable: true
  40754. });
  40755. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40756. /**
  40757. * Returns the frame time of the most recent frame
  40758. * @return Frame time in milliseconds
  40759. */
  40760. get: function () {
  40761. return this._rollingFrameTime.history(0);
  40762. },
  40763. enumerable: true,
  40764. configurable: true
  40765. });
  40766. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40767. /**
  40768. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40769. * @return Framerate in frames per second
  40770. */
  40771. get: function () {
  40772. return 1000.0 / this._rollingFrameTime.average;
  40773. },
  40774. enumerable: true,
  40775. configurable: true
  40776. });
  40777. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40778. /**
  40779. * Returns the average framerate in frames per second using the most recent frame time
  40780. * @return Framerate in frames per second
  40781. */
  40782. get: function () {
  40783. var history = this._rollingFrameTime.history(0);
  40784. if (history === 0) {
  40785. return 0;
  40786. }
  40787. return 1000.0 / history;
  40788. },
  40789. enumerable: true,
  40790. configurable: true
  40791. });
  40792. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40793. /**
  40794. * Returns true if enough samples have been taken to completely fill the sliding window
  40795. * @return true if saturated
  40796. */
  40797. get: function () {
  40798. return this._rollingFrameTime.isSaturated();
  40799. },
  40800. enumerable: true,
  40801. configurable: true
  40802. });
  40803. /**
  40804. * Enables contributions to the sliding window sample set
  40805. */
  40806. PerformanceMonitor.prototype.enable = function () {
  40807. this._enabled = true;
  40808. };
  40809. /**
  40810. * Disables contributions to the sliding window sample set
  40811. * Samples will not be interpolated over the disabled period
  40812. */
  40813. PerformanceMonitor.prototype.disable = function () {
  40814. this._enabled = false;
  40815. //clear last sample to avoid interpolating over the disabled period when next enabled
  40816. this._lastFrameTimeMs = null;
  40817. };
  40818. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40819. /**
  40820. * Returns true if sampling is enabled
  40821. * @return true if enabled
  40822. */
  40823. get: function () {
  40824. return this._enabled;
  40825. },
  40826. enumerable: true,
  40827. configurable: true
  40828. });
  40829. /**
  40830. * Resets performance monitor
  40831. */
  40832. PerformanceMonitor.prototype.reset = function () {
  40833. //clear last sample to avoid interpolating over the disabled period when next enabled
  40834. this._lastFrameTimeMs = null;
  40835. //wipe record
  40836. this._rollingFrameTime.reset();
  40837. };
  40838. return PerformanceMonitor;
  40839. }());
  40840. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40841. /**
  40842. * RollingAverage
  40843. *
  40844. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40845. */
  40846. var RollingAverage = /** @class */ (function () {
  40847. /**
  40848. * constructor
  40849. * @param length The number of samples required to saturate the sliding window
  40850. */
  40851. function RollingAverage(length) {
  40852. this._samples = new Array(length);
  40853. this.reset();
  40854. }
  40855. /**
  40856. * Adds a sample to the sample set
  40857. * @param v The sample value
  40858. */
  40859. RollingAverage.prototype.add = function (v) {
  40860. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40861. var delta;
  40862. //we need to check if we've already wrapped round
  40863. if (this.isSaturated()) {
  40864. //remove bottom of stack from mean
  40865. var bottomValue = this._samples[this._pos];
  40866. delta = bottomValue - this.average;
  40867. this.average -= delta / (this._sampleCount - 1);
  40868. this._m2 -= delta * (bottomValue - this.average);
  40869. }
  40870. else {
  40871. this._sampleCount++;
  40872. }
  40873. //add new value to mean
  40874. delta = v - this.average;
  40875. this.average += delta / (this._sampleCount);
  40876. this._m2 += delta * (v - this.average);
  40877. //set the new variance
  40878. this.variance = this._m2 / (this._sampleCount - 1);
  40879. this._samples[this._pos] = v;
  40880. this._pos++;
  40881. this._pos %= this._samples.length; //positive wrap around
  40882. };
  40883. /**
  40884. * Returns previously added values or null if outside of history or outside the sliding window domain
  40885. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40886. * @return Value previously recorded with add() or null if outside of range
  40887. */
  40888. RollingAverage.prototype.history = function (i) {
  40889. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40890. return 0;
  40891. }
  40892. var i0 = this._wrapPosition(this._pos - 1.0);
  40893. return this._samples[this._wrapPosition(i0 - i)];
  40894. };
  40895. /**
  40896. * Returns true if enough samples have been taken to completely fill the sliding window
  40897. * @return true if sample-set saturated
  40898. */
  40899. RollingAverage.prototype.isSaturated = function () {
  40900. return this._sampleCount >= this._samples.length;
  40901. };
  40902. /**
  40903. * Resets the rolling average (equivalent to 0 samples taken so far)
  40904. */
  40905. RollingAverage.prototype.reset = function () {
  40906. this.average = 0;
  40907. this.variance = 0;
  40908. this._sampleCount = 0;
  40909. this._pos = 0;
  40910. this._m2 = 0;
  40911. };
  40912. /**
  40913. * Wraps a value around the sample range boundaries
  40914. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40915. * @return Wrapped position in sample range
  40916. */
  40917. RollingAverage.prototype._wrapPosition = function (i) {
  40918. var max = this._samples.length;
  40919. return ((i % max) + max) % max;
  40920. };
  40921. return RollingAverage;
  40922. }());
  40923. BABYLON.RollingAverage = RollingAverage;
  40924. })(BABYLON || (BABYLON = {}));
  40925. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40926. var BABYLON;
  40927. (function (BABYLON) {
  40928. /**
  40929. * "Static Class" containing the most commonly used helper while dealing with material for
  40930. * rendering purpose.
  40931. *
  40932. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40933. *
  40934. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40935. */
  40936. var MaterialHelper = /** @class */ (function () {
  40937. function MaterialHelper() {
  40938. }
  40939. /**
  40940. * Bind the current view position to an effect.
  40941. * @param effect The effect to be bound
  40942. * @param scene The scene the eyes position is used from
  40943. */
  40944. MaterialHelper.BindEyePosition = function (effect, scene) {
  40945. if (scene._forcedViewPosition) {
  40946. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40947. return;
  40948. }
  40949. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40950. };
  40951. /**
  40952. * Helps preparing the defines values about the UVs in used in the effect.
  40953. * UVs are shared as much as we can accross chanels in the shaders.
  40954. * @param texture The texture we are preparing the UVs for
  40955. * @param defines The defines to update
  40956. * @param key The chanel key "diffuse", "specular"... used in the shader
  40957. */
  40958. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40959. defines._needUVs = true;
  40960. defines[key] = true;
  40961. if (texture.getTextureMatrix().isIdentity(true)) {
  40962. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40963. if (texture.coordinatesIndex === 0) {
  40964. defines["MAINUV1"] = true;
  40965. }
  40966. else {
  40967. defines["MAINUV2"] = true;
  40968. }
  40969. }
  40970. else {
  40971. defines[key + "DIRECTUV"] = 0;
  40972. }
  40973. };
  40974. /**
  40975. * Binds a texture matrix value to its corrsponding uniform
  40976. * @param texture The texture to bind the matrix for
  40977. * @param uniformBuffer The uniform buffer receivin the data
  40978. * @param key The chanel key "diffuse", "specular"... used in the shader
  40979. */
  40980. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40981. var matrix = texture.getTextureMatrix();
  40982. if (!matrix.isIdentity(true)) {
  40983. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40984. }
  40985. };
  40986. /**
  40987. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40988. * @param mesh defines the current mesh
  40989. * @param scene defines the current scene
  40990. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40991. * @param pointsCloud defines if point cloud rendering has to be turned on
  40992. * @param fogEnabled defines if fog has to be turned on
  40993. * @param alphaTest defines if alpha testing has to be turned on
  40994. * @param defines defines the current list of defines
  40995. */
  40996. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40997. if (defines._areMiscDirty) {
  40998. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40999. defines["POINTSIZE"] = pointsCloud;
  41000. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41001. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41002. defines["ALPHATEST"] = alphaTest;
  41003. }
  41004. };
  41005. /**
  41006. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41007. * @param scene defines the current scene
  41008. * @param engine defines the current engine
  41009. * @param defines specifies the list of active defines
  41010. * @param useInstances defines if instances have to be turned on
  41011. * @param useClipPlane defines if clip plane have to be turned on
  41012. */
  41013. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41014. if (useClipPlane === void 0) { useClipPlane = null; }
  41015. var changed = false;
  41016. var useClipPlane1 = false;
  41017. var useClipPlane2 = false;
  41018. var useClipPlane3 = false;
  41019. var useClipPlane4 = false;
  41020. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41021. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41022. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41023. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41024. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41025. defines["CLIPPLANE"] = useClipPlane1;
  41026. changed = true;
  41027. }
  41028. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41029. defines["CLIPPLANE2"] = useClipPlane2;
  41030. changed = true;
  41031. }
  41032. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41033. defines["CLIPPLANE3"] = useClipPlane3;
  41034. changed = true;
  41035. }
  41036. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41037. defines["CLIPPLANE4"] = useClipPlane4;
  41038. changed = true;
  41039. }
  41040. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41041. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41042. changed = true;
  41043. }
  41044. if (defines["INSTANCES"] !== useInstances) {
  41045. defines["INSTANCES"] = useInstances;
  41046. changed = true;
  41047. }
  41048. if (changed) {
  41049. defines.markAsUnprocessed();
  41050. }
  41051. };
  41052. /**
  41053. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41054. * @param mesh The mesh containing the geometry data we will draw
  41055. * @param defines The defines to update
  41056. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41057. * @param useBones Precise whether bones should be used or not (override mesh info)
  41058. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41059. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41060. * @returns false if defines are considered not dirty and have not been checked
  41061. */
  41062. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41063. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41064. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41065. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41066. return false;
  41067. }
  41068. defines._normals = defines._needNormals;
  41069. defines._uvs = defines._needUVs;
  41070. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41071. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41072. defines["TANGENT"] = true;
  41073. }
  41074. if (defines._needUVs) {
  41075. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41076. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41077. }
  41078. else {
  41079. defines["UV1"] = false;
  41080. defines["UV2"] = false;
  41081. }
  41082. if (useVertexColor) {
  41083. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41084. defines["VERTEXCOLOR"] = hasVertexColors;
  41085. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41086. }
  41087. if (useBones) {
  41088. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41089. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41090. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41091. }
  41092. else {
  41093. defines["NUM_BONE_INFLUENCERS"] = 0;
  41094. defines["BonesPerMesh"] = 0;
  41095. }
  41096. }
  41097. if (useMorphTargets) {
  41098. var manager = mesh.morphTargetManager;
  41099. if (manager) {
  41100. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41101. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41102. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41103. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41104. }
  41105. else {
  41106. defines["MORPHTARGETS_TANGENT"] = false;
  41107. defines["MORPHTARGETS_NORMAL"] = false;
  41108. defines["MORPHTARGETS"] = false;
  41109. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41110. }
  41111. }
  41112. return true;
  41113. };
  41114. /**
  41115. * Prepares the defines related to the light information passed in parameter
  41116. * @param scene The scene we are intending to draw
  41117. * @param mesh The mesh the effect is compiling for
  41118. * @param defines The defines to update
  41119. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41120. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41121. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41122. * @returns true if normals will be required for the rest of the effect
  41123. */
  41124. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41125. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41126. if (disableLighting === void 0) { disableLighting = false; }
  41127. if (!defines._areLightsDirty) {
  41128. return defines._needNormals;
  41129. }
  41130. var lightIndex = 0;
  41131. var needNormals = false;
  41132. var needRebuild = false;
  41133. var lightmapMode = false;
  41134. var shadowEnabled = false;
  41135. var specularEnabled = false;
  41136. if (scene.lightsEnabled && !disableLighting) {
  41137. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41138. var light = _a[_i];
  41139. needNormals = true;
  41140. if (defines["LIGHT" + lightIndex] === undefined) {
  41141. needRebuild = true;
  41142. }
  41143. defines["LIGHT" + lightIndex] = true;
  41144. defines["SPOTLIGHT" + lightIndex] = false;
  41145. defines["HEMILIGHT" + lightIndex] = false;
  41146. defines["POINTLIGHT" + lightIndex] = false;
  41147. defines["DIRLIGHT" + lightIndex] = false;
  41148. light.prepareLightSpecificDefines(defines, lightIndex);
  41149. // FallOff.
  41150. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41151. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41152. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41153. switch (light.falloffType) {
  41154. case BABYLON.Light.FALLOFF_GLTF:
  41155. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41156. break;
  41157. case BABYLON.Light.FALLOFF_PHYSICAL:
  41158. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41159. break;
  41160. case BABYLON.Light.FALLOFF_STANDARD:
  41161. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41162. break;
  41163. }
  41164. // Specular
  41165. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41166. specularEnabled = true;
  41167. }
  41168. // Shadows
  41169. defines["SHADOW" + lightIndex] = false;
  41170. defines["SHADOWPCF" + lightIndex] = false;
  41171. defines["SHADOWPCSS" + lightIndex] = false;
  41172. defines["SHADOWPOISSON" + lightIndex] = false;
  41173. defines["SHADOWESM" + lightIndex] = false;
  41174. defines["SHADOWCUBE" + lightIndex] = false;
  41175. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41176. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41177. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41178. var shadowGenerator = light.getShadowGenerator();
  41179. if (shadowGenerator) {
  41180. var shadowMap = shadowGenerator.getShadowMap();
  41181. if (shadowMap) {
  41182. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41183. shadowEnabled = true;
  41184. shadowGenerator.prepareDefines(defines, lightIndex);
  41185. }
  41186. }
  41187. }
  41188. }
  41189. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41190. lightmapMode = true;
  41191. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41192. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41193. }
  41194. else {
  41195. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41196. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41197. }
  41198. lightIndex++;
  41199. if (lightIndex === maxSimultaneousLights)
  41200. break;
  41201. }
  41202. }
  41203. defines["SPECULARTERM"] = specularEnabled;
  41204. defines["SHADOWS"] = shadowEnabled;
  41205. // Resetting all other lights if any
  41206. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41207. if (defines["LIGHT" + index] !== undefined) {
  41208. defines["LIGHT" + index] = false;
  41209. defines["HEMILIGHT" + lightIndex] = false;
  41210. defines["POINTLIGHT" + lightIndex] = false;
  41211. defines["DIRLIGHT" + lightIndex] = false;
  41212. defines["SPOTLIGHT" + lightIndex] = false;
  41213. defines["SHADOW" + lightIndex] = false;
  41214. }
  41215. }
  41216. var caps = scene.getEngine().getCaps();
  41217. if (defines["SHADOWFLOAT"] === undefined) {
  41218. needRebuild = true;
  41219. }
  41220. defines["SHADOWFLOAT"] = shadowEnabled &&
  41221. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41222. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41223. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41224. if (needRebuild) {
  41225. defines.rebuild();
  41226. }
  41227. return needNormals;
  41228. };
  41229. /**
  41230. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41231. * that won t be acctive due to defines being turned off.
  41232. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41233. * @param samplersList The samplers list
  41234. * @param defines The defines helping in the list generation
  41235. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41236. */
  41237. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41238. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41239. var uniformsList;
  41240. var uniformBuffersList = null;
  41241. if (uniformsListOrOptions.uniformsNames) {
  41242. var options = uniformsListOrOptions;
  41243. uniformsList = options.uniformsNames;
  41244. uniformBuffersList = options.uniformBuffersNames;
  41245. samplersList = options.samplers;
  41246. defines = options.defines;
  41247. maxSimultaneousLights = options.maxSimultaneousLights;
  41248. }
  41249. else {
  41250. uniformsList = uniformsListOrOptions;
  41251. if (!samplersList) {
  41252. samplersList = [];
  41253. }
  41254. }
  41255. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41256. if (!defines["LIGHT" + lightIndex]) {
  41257. break;
  41258. }
  41259. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41260. if (uniformBuffersList) {
  41261. uniformBuffersList.push("Light" + lightIndex);
  41262. }
  41263. samplersList.push("shadowSampler" + lightIndex);
  41264. samplersList.push("depthSampler" + lightIndex);
  41265. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41266. samplersList.push("projectionLightSampler" + lightIndex);
  41267. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41268. }
  41269. }
  41270. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41271. uniformsList.push("morphTargetInfluences");
  41272. }
  41273. };
  41274. /**
  41275. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41276. * @param defines The defines to update while falling back
  41277. * @param fallbacks The authorized effect fallbacks
  41278. * @param maxSimultaneousLights The maximum number of lights allowed
  41279. * @param rank the current rank of the Effect
  41280. * @returns The newly affected rank
  41281. */
  41282. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41283. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41284. if (rank === void 0) { rank = 0; }
  41285. var lightFallbackRank = 0;
  41286. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41287. if (!defines["LIGHT" + lightIndex]) {
  41288. break;
  41289. }
  41290. if (lightIndex > 0) {
  41291. lightFallbackRank = rank + lightIndex;
  41292. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41293. }
  41294. if (!defines["SHADOWS"]) {
  41295. if (defines["SHADOW" + lightIndex]) {
  41296. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41297. }
  41298. if (defines["SHADOWPCF" + lightIndex]) {
  41299. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41300. }
  41301. if (defines["SHADOWPCSS" + lightIndex]) {
  41302. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41303. }
  41304. if (defines["SHADOWPOISSON" + lightIndex]) {
  41305. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41306. }
  41307. if (defines["SHADOWESM" + lightIndex]) {
  41308. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41309. }
  41310. }
  41311. }
  41312. return lightFallbackRank++;
  41313. };
  41314. /**
  41315. * Prepares the list of attributes required for morph targets according to the effect defines.
  41316. * @param attribs The current list of supported attribs
  41317. * @param mesh The mesh to prepare the morph targets attributes for
  41318. * @param defines The current Defines of the effect
  41319. */
  41320. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41321. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41322. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41323. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41324. var manager = mesh.morphTargetManager;
  41325. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41326. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41327. for (var index = 0; index < influencers; index++) {
  41328. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41329. if (normal) {
  41330. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41331. }
  41332. if (tangent) {
  41333. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41334. }
  41335. if (attribs.length > maxAttributesCount) {
  41336. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41337. }
  41338. }
  41339. }
  41340. };
  41341. /**
  41342. * Prepares the list of attributes required for bones according to the effect defines.
  41343. * @param attribs The current list of supported attribs
  41344. * @param mesh The mesh to prepare the bones attributes for
  41345. * @param defines The current Defines of the effect
  41346. * @param fallbacks The current efffect fallback strategy
  41347. */
  41348. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41349. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41350. fallbacks.addCPUSkinningFallback(0, mesh);
  41351. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41352. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41353. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41354. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41355. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41356. }
  41357. }
  41358. };
  41359. /**
  41360. * Prepares the list of attributes required for instances according to the effect defines.
  41361. * @param attribs The current list of supported attribs
  41362. * @param defines The current Defines of the effect
  41363. */
  41364. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41365. if (defines["INSTANCES"]) {
  41366. attribs.push("world0");
  41367. attribs.push("world1");
  41368. attribs.push("world2");
  41369. attribs.push("world3");
  41370. }
  41371. };
  41372. /**
  41373. * Binds the light shadow information to the effect for the given mesh.
  41374. * @param light The light containing the generator
  41375. * @param scene The scene the lights belongs to
  41376. * @param mesh The mesh we are binding the information to render
  41377. * @param lightIndex The light index in the effect used to render the mesh
  41378. * @param effect The effect we are binding the data to
  41379. */
  41380. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41381. if (light.shadowEnabled && mesh.receiveShadows) {
  41382. var shadowGenerator = light.getShadowGenerator();
  41383. if (shadowGenerator) {
  41384. shadowGenerator.bindShadowLight(lightIndex, effect);
  41385. }
  41386. }
  41387. };
  41388. /**
  41389. * Binds the light information to the effect.
  41390. * @param light The light containing the generator
  41391. * @param effect The effect we are binding the data to
  41392. * @param lightIndex The light index in the effect used to render
  41393. */
  41394. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41395. light.transferToEffect(effect, lightIndex + "");
  41396. };
  41397. /**
  41398. * Binds the lights information from the scene to the effect for the given mesh.
  41399. * @param scene The scene the lights belongs to
  41400. * @param mesh The mesh we are binding the information to render
  41401. * @param effect The effect we are binding the data to
  41402. * @param defines The generated defines for the effect
  41403. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41404. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41405. */
  41406. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41407. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41408. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41409. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41410. for (var i = 0; i < len; i++) {
  41411. var light = mesh._lightSources[i];
  41412. var iAsString = i.toString();
  41413. var scaledIntensity = light.getScaledIntensity();
  41414. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41415. MaterialHelper.BindLightProperties(light, effect, i);
  41416. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41417. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41418. if (defines["SPECULARTERM"]) {
  41419. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41420. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41421. }
  41422. // Shadows
  41423. if (scene.shadowsEnabled) {
  41424. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41425. }
  41426. light._uniformBuffer.update();
  41427. }
  41428. };
  41429. /**
  41430. * Binds the fog information from the scene to the effect for the given mesh.
  41431. * @param scene The scene the lights belongs to
  41432. * @param mesh The mesh we are binding the information to render
  41433. * @param effect The effect we are binding the data to
  41434. * @param linearSpace Defines if the fog effect is applied in linear space
  41435. */
  41436. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  41437. if (linearSpace === void 0) { linearSpace = false; }
  41438. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41439. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41440. // Convert fog color to linear space if used in a linear space computed shader.
  41441. if (linearSpace) {
  41442. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  41443. effect.setColor3("vFogColor", this._tempFogColor);
  41444. }
  41445. else {
  41446. effect.setColor3("vFogColor", scene.fogColor);
  41447. }
  41448. }
  41449. };
  41450. /**
  41451. * Binds the bones information from the mesh to the effect.
  41452. * @param mesh The mesh we are binding the information to render
  41453. * @param effect The effect we are binding the data to
  41454. */
  41455. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41456. if (!effect || !mesh) {
  41457. return;
  41458. }
  41459. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41460. mesh.computeBonesUsingShaders = false;
  41461. }
  41462. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41463. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41464. if (matrices) {
  41465. effect.setMatrices("mBones", matrices);
  41466. }
  41467. }
  41468. };
  41469. /**
  41470. * Binds the morph targets information from the mesh to the effect.
  41471. * @param abstractMesh The mesh we are binding the information to render
  41472. * @param effect The effect we are binding the data to
  41473. */
  41474. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41475. var manager = abstractMesh.morphTargetManager;
  41476. if (!abstractMesh || !manager) {
  41477. return;
  41478. }
  41479. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41480. };
  41481. /**
  41482. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41483. * @param defines The generated defines used in the effect
  41484. * @param effect The effect we are binding the data to
  41485. * @param scene The scene we are willing to render with logarithmic scale for
  41486. */
  41487. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41488. if (defines["LOGARITHMICDEPTH"]) {
  41489. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41490. }
  41491. };
  41492. /**
  41493. * Binds the clip plane information from the scene to the effect.
  41494. * @param scene The scene the clip plane information are extracted from
  41495. * @param effect The effect we are binding the data to
  41496. */
  41497. MaterialHelper.BindClipPlane = function (effect, scene) {
  41498. if (scene.clipPlane) {
  41499. var clipPlane = scene.clipPlane;
  41500. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41501. }
  41502. if (scene.clipPlane2) {
  41503. var clipPlane = scene.clipPlane2;
  41504. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41505. }
  41506. if (scene.clipPlane3) {
  41507. var clipPlane = scene.clipPlane3;
  41508. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41509. }
  41510. if (scene.clipPlane4) {
  41511. var clipPlane = scene.clipPlane4;
  41512. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41513. }
  41514. };
  41515. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  41516. return MaterialHelper;
  41517. }());
  41518. BABYLON.MaterialHelper = MaterialHelper;
  41519. })(BABYLON || (BABYLON = {}));
  41520. //# sourceMappingURL=babylon.materialHelper.js.map
  41521. var BABYLON;
  41522. (function (BABYLON) {
  41523. var PushMaterial = /** @class */ (function (_super) {
  41524. __extends(PushMaterial, _super);
  41525. function PushMaterial(name, scene) {
  41526. var _this = _super.call(this, name, scene) || this;
  41527. _this._normalMatrix = new BABYLON.Matrix();
  41528. _this.storeEffectOnSubMeshes = true;
  41529. return _this;
  41530. }
  41531. PushMaterial.prototype.getEffect = function () {
  41532. return this._activeEffect;
  41533. };
  41534. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41535. if (!mesh) {
  41536. return false;
  41537. }
  41538. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41539. return true;
  41540. }
  41541. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41542. };
  41543. /**
  41544. * Binds the given world matrix to the active effect
  41545. *
  41546. * @param world the matrix to bind
  41547. */
  41548. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41549. this._activeEffect.setMatrix("world", world);
  41550. };
  41551. /**
  41552. * Binds the given normal matrix to the active effect
  41553. *
  41554. * @param normalMatrix the matrix to bind
  41555. */
  41556. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41557. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41558. };
  41559. PushMaterial.prototype.bind = function (world, mesh) {
  41560. if (!mesh) {
  41561. return;
  41562. }
  41563. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41564. };
  41565. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41566. if (effect === void 0) { effect = null; }
  41567. _super.prototype._afterBind.call(this, mesh);
  41568. this.getScene()._cachedEffect = effect;
  41569. };
  41570. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41571. if (visibility === void 0) { visibility = 1; }
  41572. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41573. };
  41574. return PushMaterial;
  41575. }(BABYLON.Material));
  41576. BABYLON.PushMaterial = PushMaterial;
  41577. })(BABYLON || (BABYLON = {}));
  41578. //# sourceMappingURL=babylon.pushMaterial.js.map
  41579. var BABYLON;
  41580. (function (BABYLON) {
  41581. /** @hidden */
  41582. var StandardMaterialDefines = /** @class */ (function (_super) {
  41583. __extends(StandardMaterialDefines, _super);
  41584. function StandardMaterialDefines() {
  41585. var _this = _super.call(this) || this;
  41586. _this.MAINUV1 = false;
  41587. _this.MAINUV2 = false;
  41588. _this.DIFFUSE = false;
  41589. _this.DIFFUSEDIRECTUV = 0;
  41590. _this.AMBIENT = false;
  41591. _this.AMBIENTDIRECTUV = 0;
  41592. _this.OPACITY = false;
  41593. _this.OPACITYDIRECTUV = 0;
  41594. _this.OPACITYRGB = false;
  41595. _this.REFLECTION = false;
  41596. _this.EMISSIVE = false;
  41597. _this.EMISSIVEDIRECTUV = 0;
  41598. _this.SPECULAR = false;
  41599. _this.SPECULARDIRECTUV = 0;
  41600. _this.BUMP = false;
  41601. _this.BUMPDIRECTUV = 0;
  41602. _this.PARALLAX = false;
  41603. _this.PARALLAXOCCLUSION = false;
  41604. _this.SPECULAROVERALPHA = false;
  41605. _this.CLIPPLANE = false;
  41606. _this.CLIPPLANE2 = false;
  41607. _this.CLIPPLANE3 = false;
  41608. _this.CLIPPLANE4 = false;
  41609. _this.ALPHATEST = false;
  41610. _this.DEPTHPREPASS = false;
  41611. _this.ALPHAFROMDIFFUSE = false;
  41612. _this.POINTSIZE = false;
  41613. _this.FOG = false;
  41614. _this.SPECULARTERM = false;
  41615. _this.DIFFUSEFRESNEL = false;
  41616. _this.OPACITYFRESNEL = false;
  41617. _this.REFLECTIONFRESNEL = false;
  41618. _this.REFRACTIONFRESNEL = false;
  41619. _this.EMISSIVEFRESNEL = false;
  41620. _this.FRESNEL = false;
  41621. _this.NORMAL = false;
  41622. _this.UV1 = false;
  41623. _this.UV2 = false;
  41624. _this.VERTEXCOLOR = false;
  41625. _this.VERTEXALPHA = false;
  41626. _this.NUM_BONE_INFLUENCERS = 0;
  41627. _this.BonesPerMesh = 0;
  41628. _this.INSTANCES = false;
  41629. _this.GLOSSINESS = false;
  41630. _this.ROUGHNESS = false;
  41631. _this.EMISSIVEASILLUMINATION = false;
  41632. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41633. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41634. _this.LIGHTMAP = false;
  41635. _this.LIGHTMAPDIRECTUV = 0;
  41636. _this.OBJECTSPACE_NORMALMAP = false;
  41637. _this.USELIGHTMAPASSHADOWMAP = false;
  41638. _this.REFLECTIONMAP_3D = false;
  41639. _this.REFLECTIONMAP_SPHERICAL = false;
  41640. _this.REFLECTIONMAP_PLANAR = false;
  41641. _this.REFLECTIONMAP_CUBIC = false;
  41642. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41643. _this.REFLECTIONMAP_PROJECTION = false;
  41644. _this.REFLECTIONMAP_SKYBOX = false;
  41645. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41646. _this.REFLECTIONMAP_EXPLICIT = false;
  41647. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41648. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41649. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41650. _this.INVERTCUBICMAP = false;
  41651. _this.LOGARITHMICDEPTH = false;
  41652. _this.REFRACTION = false;
  41653. _this.REFRACTIONMAP_3D = false;
  41654. _this.REFLECTIONOVERALPHA = false;
  41655. _this.TWOSIDEDLIGHTING = false;
  41656. _this.SHADOWFLOAT = false;
  41657. _this.MORPHTARGETS = false;
  41658. _this.MORPHTARGETS_NORMAL = false;
  41659. _this.MORPHTARGETS_TANGENT = false;
  41660. _this.NUM_MORPH_INFLUENCERS = 0;
  41661. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41662. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41663. _this.IMAGEPROCESSING = false;
  41664. _this.VIGNETTE = false;
  41665. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41666. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41667. _this.TONEMAPPING = false;
  41668. _this.TONEMAPPING_ACES = false;
  41669. _this.CONTRAST = false;
  41670. _this.COLORCURVES = false;
  41671. _this.COLORGRADING = false;
  41672. _this.COLORGRADING3D = false;
  41673. _this.SAMPLER3DGREENDEPTH = false;
  41674. _this.SAMPLER3DBGRMAP = false;
  41675. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41676. /**
  41677. * If the reflection texture on this material is in linear color space
  41678. * @hidden
  41679. */
  41680. _this.IS_REFLECTION_LINEAR = false;
  41681. /**
  41682. * If the refraction texture on this material is in linear color space
  41683. * @hidden
  41684. */
  41685. _this.IS_REFRACTION_LINEAR = false;
  41686. _this.EXPOSURE = false;
  41687. _this.rebuild();
  41688. return _this;
  41689. }
  41690. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41691. var modes = [
  41692. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41693. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41694. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41695. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41696. ];
  41697. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41698. var mode = modes_1[_i];
  41699. this[mode] = (mode === modeToEnable);
  41700. }
  41701. };
  41702. return StandardMaterialDefines;
  41703. }(BABYLON.MaterialDefines));
  41704. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41705. var StandardMaterial = /** @class */ (function (_super) {
  41706. __extends(StandardMaterial, _super);
  41707. function StandardMaterial(name, scene) {
  41708. var _this = _super.call(this, name, scene) || this;
  41709. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41710. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41711. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41712. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41713. _this.specularPower = 64;
  41714. _this._useAlphaFromDiffuseTexture = false;
  41715. _this._useEmissiveAsIllumination = false;
  41716. _this._linkEmissiveWithDiffuse = false;
  41717. _this._useSpecularOverAlpha = false;
  41718. _this._useReflectionOverAlpha = false;
  41719. _this._disableLighting = false;
  41720. _this._useObjectSpaceNormalMap = false;
  41721. _this._useParallax = false;
  41722. _this._useParallaxOcclusion = false;
  41723. _this.parallaxScaleBias = 0.05;
  41724. _this._roughness = 0;
  41725. _this.indexOfRefraction = 0.98;
  41726. _this.invertRefractionY = true;
  41727. /**
  41728. * Defines the alpha limits in alpha test mode
  41729. */
  41730. _this.alphaCutOff = 0.4;
  41731. _this._useLightmapAsShadowmap = false;
  41732. _this._useReflectionFresnelFromSpecular = false;
  41733. _this._useGlossinessFromSpecularMapAlpha = false;
  41734. _this._maxSimultaneousLights = 4;
  41735. /**
  41736. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41737. */
  41738. _this._invertNormalMapX = false;
  41739. /**
  41740. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41741. */
  41742. _this._invertNormalMapY = false;
  41743. /**
  41744. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41745. */
  41746. _this._twoSidedLighting = false;
  41747. _this._renderTargets = new BABYLON.SmartArray(16);
  41748. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41749. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41750. // Setup the default processing configuration to the scene.
  41751. _this._attachImageProcessingConfiguration(null);
  41752. _this.getRenderTargetTextures = function () {
  41753. _this._renderTargets.reset();
  41754. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41755. _this._renderTargets.push(_this._reflectionTexture);
  41756. }
  41757. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41758. _this._renderTargets.push(_this._refractionTexture);
  41759. }
  41760. return _this._renderTargets;
  41761. };
  41762. return _this;
  41763. }
  41764. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41765. /**
  41766. * Gets the image processing configuration used either in this material.
  41767. */
  41768. get: function () {
  41769. return this._imageProcessingConfiguration;
  41770. },
  41771. /**
  41772. * Sets the Default image processing configuration used either in the this material.
  41773. *
  41774. * If sets to null, the scene one is in use.
  41775. */
  41776. set: function (value) {
  41777. this._attachImageProcessingConfiguration(value);
  41778. // Ensure the effect will be rebuilt.
  41779. this._markAllSubMeshesAsTexturesDirty();
  41780. },
  41781. enumerable: true,
  41782. configurable: true
  41783. });
  41784. /**
  41785. * Attaches a new image processing configuration to the Standard Material.
  41786. * @param configuration
  41787. */
  41788. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41789. var _this = this;
  41790. if (configuration === this._imageProcessingConfiguration) {
  41791. return;
  41792. }
  41793. // Detaches observer.
  41794. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41795. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41796. }
  41797. // Pick the scene configuration if needed.
  41798. if (!configuration) {
  41799. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41800. }
  41801. else {
  41802. this._imageProcessingConfiguration = configuration;
  41803. }
  41804. // Attaches observer.
  41805. if (this._imageProcessingConfiguration) {
  41806. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41807. _this._markAllSubMeshesAsImageProcessingDirty();
  41808. });
  41809. }
  41810. };
  41811. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41812. /**
  41813. * Gets wether the color curves effect is enabled.
  41814. */
  41815. get: function () {
  41816. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41817. },
  41818. /**
  41819. * Sets wether the color curves effect is enabled.
  41820. */
  41821. set: function (value) {
  41822. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41823. },
  41824. enumerable: true,
  41825. configurable: true
  41826. });
  41827. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41828. /**
  41829. * Gets wether the color grading effect is enabled.
  41830. */
  41831. get: function () {
  41832. return this.imageProcessingConfiguration.colorGradingEnabled;
  41833. },
  41834. /**
  41835. * Gets wether the color grading effect is enabled.
  41836. */
  41837. set: function (value) {
  41838. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41839. },
  41840. enumerable: true,
  41841. configurable: true
  41842. });
  41843. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41844. /**
  41845. * Gets wether tonemapping is enabled or not.
  41846. */
  41847. get: function () {
  41848. return this._imageProcessingConfiguration.toneMappingEnabled;
  41849. },
  41850. /**
  41851. * Sets wether tonemapping is enabled or not
  41852. */
  41853. set: function (value) {
  41854. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41855. },
  41856. enumerable: true,
  41857. configurable: true
  41858. });
  41859. ;
  41860. ;
  41861. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41862. /**
  41863. * The camera exposure used on this material.
  41864. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41865. * This corresponds to a photographic exposure.
  41866. */
  41867. get: function () {
  41868. return this._imageProcessingConfiguration.exposure;
  41869. },
  41870. /**
  41871. * The camera exposure used on this material.
  41872. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41873. * This corresponds to a photographic exposure.
  41874. */
  41875. set: function (value) {
  41876. this._imageProcessingConfiguration.exposure = value;
  41877. },
  41878. enumerable: true,
  41879. configurable: true
  41880. });
  41881. ;
  41882. ;
  41883. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41884. /**
  41885. * Gets The camera contrast used on this material.
  41886. */
  41887. get: function () {
  41888. return this._imageProcessingConfiguration.contrast;
  41889. },
  41890. /**
  41891. * Sets The camera contrast used on this material.
  41892. */
  41893. set: function (value) {
  41894. this._imageProcessingConfiguration.contrast = value;
  41895. },
  41896. enumerable: true,
  41897. configurable: true
  41898. });
  41899. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41900. /**
  41901. * Gets the Color Grading 2D Lookup Texture.
  41902. */
  41903. get: function () {
  41904. return this._imageProcessingConfiguration.colorGradingTexture;
  41905. },
  41906. /**
  41907. * Sets the Color Grading 2D Lookup Texture.
  41908. */
  41909. set: function (value) {
  41910. this._imageProcessingConfiguration.colorGradingTexture = value;
  41911. },
  41912. enumerable: true,
  41913. configurable: true
  41914. });
  41915. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41916. /**
  41917. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41918. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41919. * 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;
  41920. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41921. */
  41922. get: function () {
  41923. return this._imageProcessingConfiguration.colorCurves;
  41924. },
  41925. /**
  41926. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41927. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41928. * 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;
  41929. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41930. */
  41931. set: function (value) {
  41932. this._imageProcessingConfiguration.colorCurves = value;
  41933. },
  41934. enumerable: true,
  41935. configurable: true
  41936. });
  41937. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41938. /**
  41939. * Gets a boolean indicating that current material needs to register RTT
  41940. */
  41941. get: function () {
  41942. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41943. return true;
  41944. }
  41945. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41946. return true;
  41947. }
  41948. return false;
  41949. },
  41950. enumerable: true,
  41951. configurable: true
  41952. });
  41953. StandardMaterial.prototype.getClassName = function () {
  41954. return "StandardMaterial";
  41955. };
  41956. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41957. get: function () {
  41958. return this._useLogarithmicDepth;
  41959. },
  41960. set: function (value) {
  41961. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41962. this._markAllSubMeshesAsMiscDirty();
  41963. },
  41964. enumerable: true,
  41965. configurable: true
  41966. });
  41967. StandardMaterial.prototype.needAlphaBlending = function () {
  41968. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41969. };
  41970. StandardMaterial.prototype.needAlphaTesting = function () {
  41971. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41972. };
  41973. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41974. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41975. };
  41976. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41977. return this._diffuseTexture;
  41978. };
  41979. /**
  41980. * Child classes can use it to update shaders
  41981. */
  41982. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41983. if (useInstances === void 0) { useInstances = false; }
  41984. if (subMesh.effect && this.isFrozen) {
  41985. if (this._wasPreviouslyReady) {
  41986. return true;
  41987. }
  41988. }
  41989. if (!subMesh._materialDefines) {
  41990. subMesh._materialDefines = new StandardMaterialDefines();
  41991. }
  41992. var scene = this.getScene();
  41993. var defines = subMesh._materialDefines;
  41994. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41995. if (defines._renderId === scene.getRenderId()) {
  41996. return true;
  41997. }
  41998. }
  41999. var engine = scene.getEngine();
  42000. // Lights
  42001. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42002. // Textures
  42003. if (defines._areTexturesDirty) {
  42004. defines._needUVs = false;
  42005. defines.MAINUV1 = false;
  42006. defines.MAINUV2 = false;
  42007. if (scene.texturesEnabled) {
  42008. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42009. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42010. return false;
  42011. }
  42012. else {
  42013. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42014. }
  42015. }
  42016. else {
  42017. defines.DIFFUSE = false;
  42018. }
  42019. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42020. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42021. return false;
  42022. }
  42023. else {
  42024. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42025. }
  42026. }
  42027. else {
  42028. defines.AMBIENT = false;
  42029. }
  42030. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42031. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42032. return false;
  42033. }
  42034. else {
  42035. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42036. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42037. }
  42038. }
  42039. else {
  42040. defines.OPACITY = false;
  42041. }
  42042. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42043. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42044. return false;
  42045. }
  42046. else {
  42047. defines._needNormals = true;
  42048. defines.REFLECTION = true;
  42049. defines.ROUGHNESS = (this._roughness > 0);
  42050. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42051. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42052. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42053. switch (this._reflectionTexture.coordinatesMode) {
  42054. case BABYLON.Texture.EXPLICIT_MODE:
  42055. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42056. break;
  42057. case BABYLON.Texture.PLANAR_MODE:
  42058. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42059. break;
  42060. case BABYLON.Texture.PROJECTION_MODE:
  42061. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42062. break;
  42063. case BABYLON.Texture.SKYBOX_MODE:
  42064. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42065. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42066. break;
  42067. case BABYLON.Texture.SPHERICAL_MODE:
  42068. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42069. break;
  42070. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42071. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42072. break;
  42073. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42074. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42075. break;
  42076. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42077. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42078. break;
  42079. case BABYLON.Texture.CUBIC_MODE:
  42080. case BABYLON.Texture.INVCUBIC_MODE:
  42081. default:
  42082. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42083. break;
  42084. }
  42085. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42086. }
  42087. }
  42088. else {
  42089. defines.REFLECTION = false;
  42090. }
  42091. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42092. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42093. return false;
  42094. }
  42095. else {
  42096. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42097. }
  42098. }
  42099. else {
  42100. defines.EMISSIVE = false;
  42101. }
  42102. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42103. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42104. return false;
  42105. }
  42106. else {
  42107. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42108. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42109. }
  42110. }
  42111. else {
  42112. defines.LIGHTMAP = false;
  42113. }
  42114. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42115. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42116. return false;
  42117. }
  42118. else {
  42119. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42120. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42121. }
  42122. }
  42123. else {
  42124. defines.SPECULAR = false;
  42125. }
  42126. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42127. // Bump texure can not be not blocking.
  42128. if (!this._bumpTexture.isReady()) {
  42129. return false;
  42130. }
  42131. else {
  42132. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42133. defines.PARALLAX = this._useParallax;
  42134. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42135. }
  42136. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42137. }
  42138. else {
  42139. defines.BUMP = false;
  42140. }
  42141. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42142. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42143. return false;
  42144. }
  42145. else {
  42146. defines._needUVs = true;
  42147. defines.REFRACTION = true;
  42148. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42149. }
  42150. }
  42151. else {
  42152. defines.REFRACTION = false;
  42153. }
  42154. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42155. }
  42156. else {
  42157. defines.DIFFUSE = false;
  42158. defines.AMBIENT = false;
  42159. defines.OPACITY = false;
  42160. defines.REFLECTION = false;
  42161. defines.EMISSIVE = false;
  42162. defines.LIGHTMAP = false;
  42163. defines.BUMP = false;
  42164. defines.REFRACTION = false;
  42165. }
  42166. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42167. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42168. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42169. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42170. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42171. }
  42172. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42173. if (!this._imageProcessingConfiguration.isReady()) {
  42174. return false;
  42175. }
  42176. this._imageProcessingConfiguration.prepareDefines(defines);
  42177. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42178. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42179. }
  42180. if (defines._areFresnelDirty) {
  42181. if (StandardMaterial.FresnelEnabled) {
  42182. // Fresnel
  42183. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42184. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42185. this._reflectionFresnelParameters) {
  42186. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42187. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42188. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42189. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42190. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42191. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42192. defines._needNormals = true;
  42193. defines.FRESNEL = true;
  42194. }
  42195. }
  42196. else {
  42197. defines.FRESNEL = false;
  42198. }
  42199. }
  42200. // Misc.
  42201. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42202. // Attribs
  42203. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42204. // Values that need to be evaluated on every frame
  42205. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42206. // Get correct effect
  42207. if (defines.isDirty) {
  42208. defines.markAsProcessed();
  42209. scene.resetCachedMaterial();
  42210. // Fallbacks
  42211. var fallbacks = new BABYLON.EffectFallbacks();
  42212. if (defines.REFLECTION) {
  42213. fallbacks.addFallback(0, "REFLECTION");
  42214. }
  42215. if (defines.SPECULAR) {
  42216. fallbacks.addFallback(0, "SPECULAR");
  42217. }
  42218. if (defines.BUMP) {
  42219. fallbacks.addFallback(0, "BUMP");
  42220. }
  42221. if (defines.PARALLAX) {
  42222. fallbacks.addFallback(1, "PARALLAX");
  42223. }
  42224. if (defines.PARALLAXOCCLUSION) {
  42225. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42226. }
  42227. if (defines.SPECULAROVERALPHA) {
  42228. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42229. }
  42230. if (defines.FOG) {
  42231. fallbacks.addFallback(1, "FOG");
  42232. }
  42233. if (defines.POINTSIZE) {
  42234. fallbacks.addFallback(0, "POINTSIZE");
  42235. }
  42236. if (defines.LOGARITHMICDEPTH) {
  42237. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42238. }
  42239. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42240. if (defines.SPECULARTERM) {
  42241. fallbacks.addFallback(0, "SPECULARTERM");
  42242. }
  42243. if (defines.DIFFUSEFRESNEL) {
  42244. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42245. }
  42246. if (defines.OPACITYFRESNEL) {
  42247. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42248. }
  42249. if (defines.REFLECTIONFRESNEL) {
  42250. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42251. }
  42252. if (defines.EMISSIVEFRESNEL) {
  42253. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42254. }
  42255. if (defines.FRESNEL) {
  42256. fallbacks.addFallback(4, "FRESNEL");
  42257. }
  42258. //Attributes
  42259. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42260. if (defines.NORMAL) {
  42261. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42262. }
  42263. if (defines.UV1) {
  42264. attribs.push(BABYLON.VertexBuffer.UVKind);
  42265. }
  42266. if (defines.UV2) {
  42267. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42268. }
  42269. if (defines.VERTEXCOLOR) {
  42270. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42271. }
  42272. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42273. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42274. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42275. var shaderName = "default";
  42276. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42277. "vFogInfos", "vFogColor", "pointSize",
  42278. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42279. "mBones",
  42280. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42281. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42282. "vReflectionPosition", "vReflectionSize",
  42283. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42284. ];
  42285. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42286. var uniformBuffers = ["Material", "Scene"];
  42287. if (BABYLON.ImageProcessingConfiguration) {
  42288. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42289. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42290. }
  42291. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42292. uniformsNames: uniforms,
  42293. uniformBuffersNames: uniformBuffers,
  42294. samplers: samplers,
  42295. defines: defines,
  42296. maxSimultaneousLights: this._maxSimultaneousLights
  42297. });
  42298. if (this.customShaderNameResolve) {
  42299. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42300. }
  42301. var join = defines.toString();
  42302. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42303. attributes: attribs,
  42304. uniformsNames: uniforms,
  42305. uniformBuffersNames: uniformBuffers,
  42306. samplers: samplers,
  42307. defines: join,
  42308. fallbacks: fallbacks,
  42309. onCompiled: this.onCompiled,
  42310. onError: this.onError,
  42311. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42312. }, engine), defines);
  42313. this.buildUniformLayout();
  42314. }
  42315. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42316. return false;
  42317. }
  42318. defines._renderId = scene.getRenderId();
  42319. this._wasPreviouslyReady = true;
  42320. return true;
  42321. };
  42322. StandardMaterial.prototype.buildUniformLayout = function () {
  42323. // Order is important !
  42324. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42325. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42326. this._uniformBuffer.addUniform("opacityParts", 4);
  42327. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42328. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42329. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42330. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42331. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42332. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42333. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42334. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42335. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42336. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42337. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42338. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42339. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42340. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42341. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42342. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42343. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42344. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42345. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42346. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42347. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42348. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42349. this._uniformBuffer.addUniform("specularMatrix", 16);
  42350. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42351. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42352. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42353. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42354. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42355. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42356. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42357. this._uniformBuffer.addUniform("pointSize", 1);
  42358. this._uniformBuffer.create();
  42359. };
  42360. StandardMaterial.prototype.unbind = function () {
  42361. if (this._activeEffect) {
  42362. var needFlag = false;
  42363. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42364. this._activeEffect.setTexture("reflection2DSampler", null);
  42365. needFlag = true;
  42366. }
  42367. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42368. this._activeEffect.setTexture("refraction2DSampler", null);
  42369. needFlag = true;
  42370. }
  42371. if (needFlag) {
  42372. this._markAllSubMeshesAsTexturesDirty();
  42373. }
  42374. }
  42375. _super.prototype.unbind.call(this);
  42376. };
  42377. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42378. var scene = this.getScene();
  42379. var defines = subMesh._materialDefines;
  42380. if (!defines) {
  42381. return;
  42382. }
  42383. var effect = subMesh.effect;
  42384. if (!effect) {
  42385. return;
  42386. }
  42387. this._activeEffect = effect;
  42388. // Matrices
  42389. this.bindOnlyWorldMatrix(world);
  42390. // Normal Matrix
  42391. if (defines.OBJECTSPACE_NORMALMAP) {
  42392. world.toNormalMatrix(this._normalMatrix);
  42393. this.bindOnlyNormalMatrix(this._normalMatrix);
  42394. }
  42395. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42396. // Bones
  42397. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42398. if (mustRebind) {
  42399. this._uniformBuffer.bindToEffect(effect, "Material");
  42400. this.bindViewProjection(effect);
  42401. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42402. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42403. // Fresnel
  42404. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42405. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42406. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42407. }
  42408. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42409. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42410. }
  42411. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42412. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42413. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42414. }
  42415. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42416. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42417. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42418. }
  42419. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42420. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42421. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42422. }
  42423. }
  42424. // Textures
  42425. if (scene.texturesEnabled) {
  42426. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42427. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42428. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42429. if (this._diffuseTexture.hasAlpha) {
  42430. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42431. }
  42432. }
  42433. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42434. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42435. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42436. }
  42437. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42438. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42439. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42440. }
  42441. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42442. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42443. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42444. if (this._reflectionTexture.boundingBoxSize) {
  42445. var cubeTexture = this._reflectionTexture;
  42446. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42447. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42448. }
  42449. }
  42450. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42451. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42452. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42453. }
  42454. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42455. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42456. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42457. }
  42458. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42459. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42460. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42461. }
  42462. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42463. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42464. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42465. if (scene._mirroredCameraPosition) {
  42466. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42467. }
  42468. else {
  42469. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42470. }
  42471. }
  42472. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42473. var depth = 1.0;
  42474. if (!this._refractionTexture.isCube) {
  42475. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42476. if (this._refractionTexture.depth) {
  42477. depth = this._refractionTexture.depth;
  42478. }
  42479. }
  42480. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42481. }
  42482. }
  42483. // Point size
  42484. if (this.pointsCloud) {
  42485. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42486. }
  42487. if (defines.SPECULARTERM) {
  42488. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42489. }
  42490. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42491. // Diffuse
  42492. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42493. }
  42494. // Textures
  42495. if (scene.texturesEnabled) {
  42496. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42497. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42498. }
  42499. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42500. effect.setTexture("ambientSampler", this._ambientTexture);
  42501. }
  42502. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42503. effect.setTexture("opacitySampler", this._opacityTexture);
  42504. }
  42505. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42506. if (this._reflectionTexture.isCube) {
  42507. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42508. }
  42509. else {
  42510. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42511. }
  42512. }
  42513. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42514. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42515. }
  42516. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42517. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42518. }
  42519. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42520. effect.setTexture("specularSampler", this._specularTexture);
  42521. }
  42522. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42523. effect.setTexture("bumpSampler", this._bumpTexture);
  42524. }
  42525. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42526. var depth = 1.0;
  42527. if (this._refractionTexture.isCube) {
  42528. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42529. }
  42530. else {
  42531. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42532. }
  42533. }
  42534. }
  42535. // Clip plane
  42536. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42537. // Colors
  42538. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42539. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42540. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42541. }
  42542. if (mustRebind || !this.isFrozen) {
  42543. // Lights
  42544. if (scene.lightsEnabled && !this._disableLighting) {
  42545. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42546. }
  42547. // View
  42548. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42549. this.bindView(effect);
  42550. }
  42551. // Fog
  42552. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42553. // Morph targets
  42554. if (defines.NUM_MORPH_INFLUENCERS) {
  42555. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42556. }
  42557. // Log. depth
  42558. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42559. // image processing
  42560. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42561. this._imageProcessingConfiguration.bind(this._activeEffect);
  42562. }
  42563. }
  42564. this._uniformBuffer.update();
  42565. this._afterBind(mesh, this._activeEffect);
  42566. };
  42567. StandardMaterial.prototype.getAnimatables = function () {
  42568. var results = [];
  42569. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42570. results.push(this._diffuseTexture);
  42571. }
  42572. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42573. results.push(this._ambientTexture);
  42574. }
  42575. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42576. results.push(this._opacityTexture);
  42577. }
  42578. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42579. results.push(this._reflectionTexture);
  42580. }
  42581. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42582. results.push(this._emissiveTexture);
  42583. }
  42584. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42585. results.push(this._specularTexture);
  42586. }
  42587. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42588. results.push(this._bumpTexture);
  42589. }
  42590. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42591. results.push(this._lightmapTexture);
  42592. }
  42593. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42594. results.push(this._refractionTexture);
  42595. }
  42596. return results;
  42597. };
  42598. StandardMaterial.prototype.getActiveTextures = function () {
  42599. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42600. if (this._diffuseTexture) {
  42601. activeTextures.push(this._diffuseTexture);
  42602. }
  42603. if (this._ambientTexture) {
  42604. activeTextures.push(this._ambientTexture);
  42605. }
  42606. if (this._opacityTexture) {
  42607. activeTextures.push(this._opacityTexture);
  42608. }
  42609. if (this._reflectionTexture) {
  42610. activeTextures.push(this._reflectionTexture);
  42611. }
  42612. if (this._emissiveTexture) {
  42613. activeTextures.push(this._emissiveTexture);
  42614. }
  42615. if (this._specularTexture) {
  42616. activeTextures.push(this._specularTexture);
  42617. }
  42618. if (this._bumpTexture) {
  42619. activeTextures.push(this._bumpTexture);
  42620. }
  42621. if (this._lightmapTexture) {
  42622. activeTextures.push(this._lightmapTexture);
  42623. }
  42624. if (this._refractionTexture) {
  42625. activeTextures.push(this._refractionTexture);
  42626. }
  42627. return activeTextures;
  42628. };
  42629. StandardMaterial.prototype.hasTexture = function (texture) {
  42630. if (_super.prototype.hasTexture.call(this, texture)) {
  42631. return true;
  42632. }
  42633. if (this._diffuseTexture === texture) {
  42634. return true;
  42635. }
  42636. if (this._ambientTexture === texture) {
  42637. return true;
  42638. }
  42639. if (this._opacityTexture === texture) {
  42640. return true;
  42641. }
  42642. if (this._reflectionTexture === texture) {
  42643. return true;
  42644. }
  42645. if (this._emissiveTexture === texture) {
  42646. return true;
  42647. }
  42648. if (this._specularTexture === texture) {
  42649. return true;
  42650. }
  42651. if (this._bumpTexture === texture) {
  42652. return true;
  42653. }
  42654. if (this._lightmapTexture === texture) {
  42655. return true;
  42656. }
  42657. if (this._refractionTexture === texture) {
  42658. return true;
  42659. }
  42660. return false;
  42661. };
  42662. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42663. if (forceDisposeTextures) {
  42664. if (this._diffuseTexture) {
  42665. this._diffuseTexture.dispose();
  42666. }
  42667. if (this._ambientTexture) {
  42668. this._ambientTexture.dispose();
  42669. }
  42670. if (this._opacityTexture) {
  42671. this._opacityTexture.dispose();
  42672. }
  42673. if (this._reflectionTexture) {
  42674. this._reflectionTexture.dispose();
  42675. }
  42676. if (this._emissiveTexture) {
  42677. this._emissiveTexture.dispose();
  42678. }
  42679. if (this._specularTexture) {
  42680. this._specularTexture.dispose();
  42681. }
  42682. if (this._bumpTexture) {
  42683. this._bumpTexture.dispose();
  42684. }
  42685. if (this._lightmapTexture) {
  42686. this._lightmapTexture.dispose();
  42687. }
  42688. if (this._refractionTexture) {
  42689. this._refractionTexture.dispose();
  42690. }
  42691. }
  42692. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42693. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42694. }
  42695. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42696. };
  42697. StandardMaterial.prototype.clone = function (name) {
  42698. var _this = this;
  42699. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42700. result.name = name;
  42701. result.id = name;
  42702. return result;
  42703. };
  42704. StandardMaterial.prototype.serialize = function () {
  42705. return BABYLON.SerializationHelper.Serialize(this);
  42706. };
  42707. // Statics
  42708. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42709. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42710. };
  42711. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42712. get: function () {
  42713. return StandardMaterial._DiffuseTextureEnabled;
  42714. },
  42715. set: function (value) {
  42716. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42717. return;
  42718. }
  42719. StandardMaterial._DiffuseTextureEnabled = value;
  42720. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42721. },
  42722. enumerable: true,
  42723. configurable: true
  42724. });
  42725. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42726. get: function () {
  42727. return StandardMaterial._AmbientTextureEnabled;
  42728. },
  42729. set: function (value) {
  42730. if (StandardMaterial._AmbientTextureEnabled === value) {
  42731. return;
  42732. }
  42733. StandardMaterial._AmbientTextureEnabled = value;
  42734. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42735. },
  42736. enumerable: true,
  42737. configurable: true
  42738. });
  42739. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42740. get: function () {
  42741. return StandardMaterial._OpacityTextureEnabled;
  42742. },
  42743. set: function (value) {
  42744. if (StandardMaterial._OpacityTextureEnabled === value) {
  42745. return;
  42746. }
  42747. StandardMaterial._OpacityTextureEnabled = value;
  42748. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42749. },
  42750. enumerable: true,
  42751. configurable: true
  42752. });
  42753. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42754. get: function () {
  42755. return StandardMaterial._ReflectionTextureEnabled;
  42756. },
  42757. set: function (value) {
  42758. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42759. return;
  42760. }
  42761. StandardMaterial._ReflectionTextureEnabled = value;
  42762. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42763. },
  42764. enumerable: true,
  42765. configurable: true
  42766. });
  42767. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42768. get: function () {
  42769. return StandardMaterial._EmissiveTextureEnabled;
  42770. },
  42771. set: function (value) {
  42772. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42773. return;
  42774. }
  42775. StandardMaterial._EmissiveTextureEnabled = value;
  42776. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42777. },
  42778. enumerable: true,
  42779. configurable: true
  42780. });
  42781. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42782. get: function () {
  42783. return StandardMaterial._SpecularTextureEnabled;
  42784. },
  42785. set: function (value) {
  42786. if (StandardMaterial._SpecularTextureEnabled === value) {
  42787. return;
  42788. }
  42789. StandardMaterial._SpecularTextureEnabled = value;
  42790. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42791. },
  42792. enumerable: true,
  42793. configurable: true
  42794. });
  42795. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42796. get: function () {
  42797. return StandardMaterial._BumpTextureEnabled;
  42798. },
  42799. set: function (value) {
  42800. if (StandardMaterial._BumpTextureEnabled === value) {
  42801. return;
  42802. }
  42803. StandardMaterial._BumpTextureEnabled = value;
  42804. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42805. },
  42806. enumerable: true,
  42807. configurable: true
  42808. });
  42809. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42810. get: function () {
  42811. return StandardMaterial._LightmapTextureEnabled;
  42812. },
  42813. set: function (value) {
  42814. if (StandardMaterial._LightmapTextureEnabled === value) {
  42815. return;
  42816. }
  42817. StandardMaterial._LightmapTextureEnabled = value;
  42818. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42819. },
  42820. enumerable: true,
  42821. configurable: true
  42822. });
  42823. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42824. get: function () {
  42825. return StandardMaterial._RefractionTextureEnabled;
  42826. },
  42827. set: function (value) {
  42828. if (StandardMaterial._RefractionTextureEnabled === value) {
  42829. return;
  42830. }
  42831. StandardMaterial._RefractionTextureEnabled = value;
  42832. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42833. },
  42834. enumerable: true,
  42835. configurable: true
  42836. });
  42837. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42838. get: function () {
  42839. return StandardMaterial._ColorGradingTextureEnabled;
  42840. },
  42841. set: function (value) {
  42842. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42843. return;
  42844. }
  42845. StandardMaterial._ColorGradingTextureEnabled = value;
  42846. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42847. },
  42848. enumerable: true,
  42849. configurable: true
  42850. });
  42851. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42852. get: function () {
  42853. return StandardMaterial._FresnelEnabled;
  42854. },
  42855. set: function (value) {
  42856. if (StandardMaterial._FresnelEnabled === value) {
  42857. return;
  42858. }
  42859. StandardMaterial._FresnelEnabled = value;
  42860. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42861. },
  42862. enumerable: true,
  42863. configurable: true
  42864. });
  42865. // Flags used to enable or disable a type of texture for all Standard Materials
  42866. StandardMaterial._DiffuseTextureEnabled = true;
  42867. StandardMaterial._AmbientTextureEnabled = true;
  42868. StandardMaterial._OpacityTextureEnabled = true;
  42869. StandardMaterial._ReflectionTextureEnabled = true;
  42870. StandardMaterial._EmissiveTextureEnabled = true;
  42871. StandardMaterial._SpecularTextureEnabled = true;
  42872. StandardMaterial._BumpTextureEnabled = true;
  42873. StandardMaterial._LightmapTextureEnabled = true;
  42874. StandardMaterial._RefractionTextureEnabled = true;
  42875. StandardMaterial._ColorGradingTextureEnabled = true;
  42876. StandardMaterial._FresnelEnabled = true;
  42877. __decorate([
  42878. BABYLON.serializeAsTexture("diffuseTexture")
  42879. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42880. __decorate([
  42881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42882. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42883. __decorate([
  42884. BABYLON.serializeAsTexture("ambientTexture")
  42885. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42886. __decorate([
  42887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42888. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42889. __decorate([
  42890. BABYLON.serializeAsTexture("opacityTexture")
  42891. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42892. __decorate([
  42893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42894. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42895. __decorate([
  42896. BABYLON.serializeAsTexture("reflectionTexture")
  42897. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42898. __decorate([
  42899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42900. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42901. __decorate([
  42902. BABYLON.serializeAsTexture("emissiveTexture")
  42903. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42904. __decorate([
  42905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42906. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42907. __decorate([
  42908. BABYLON.serializeAsTexture("specularTexture")
  42909. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42910. __decorate([
  42911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42912. ], StandardMaterial.prototype, "specularTexture", void 0);
  42913. __decorate([
  42914. BABYLON.serializeAsTexture("bumpTexture")
  42915. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42916. __decorate([
  42917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42918. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42919. __decorate([
  42920. BABYLON.serializeAsTexture("lightmapTexture")
  42921. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42922. __decorate([
  42923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42924. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42925. __decorate([
  42926. BABYLON.serializeAsTexture("refractionTexture")
  42927. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42928. __decorate([
  42929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42930. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42931. __decorate([
  42932. BABYLON.serializeAsColor3("ambient")
  42933. ], StandardMaterial.prototype, "ambientColor", void 0);
  42934. __decorate([
  42935. BABYLON.serializeAsColor3("diffuse")
  42936. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42937. __decorate([
  42938. BABYLON.serializeAsColor3("specular")
  42939. ], StandardMaterial.prototype, "specularColor", void 0);
  42940. __decorate([
  42941. BABYLON.serializeAsColor3("emissive")
  42942. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42943. __decorate([
  42944. BABYLON.serialize()
  42945. ], StandardMaterial.prototype, "specularPower", void 0);
  42946. __decorate([
  42947. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42948. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42949. __decorate([
  42950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42951. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42952. __decorate([
  42953. BABYLON.serialize("useEmissiveAsIllumination")
  42954. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42955. __decorate([
  42956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42957. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42958. __decorate([
  42959. BABYLON.serialize("linkEmissiveWithDiffuse")
  42960. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42961. __decorate([
  42962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42963. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42964. __decorate([
  42965. BABYLON.serialize("useSpecularOverAlpha")
  42966. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42967. __decorate([
  42968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42969. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42970. __decorate([
  42971. BABYLON.serialize("useReflectionOverAlpha")
  42972. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42973. __decorate([
  42974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42975. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42976. __decorate([
  42977. BABYLON.serialize("disableLighting")
  42978. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42979. __decorate([
  42980. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42981. ], StandardMaterial.prototype, "disableLighting", void 0);
  42982. __decorate([
  42983. BABYLON.serialize("useObjectSpaceNormalMap")
  42984. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42985. __decorate([
  42986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42987. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42988. __decorate([
  42989. BABYLON.serialize("useParallax")
  42990. ], StandardMaterial.prototype, "_useParallax", void 0);
  42991. __decorate([
  42992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42993. ], StandardMaterial.prototype, "useParallax", void 0);
  42994. __decorate([
  42995. BABYLON.serialize("useParallaxOcclusion")
  42996. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42997. __decorate([
  42998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42999. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43000. __decorate([
  43001. BABYLON.serialize()
  43002. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43003. __decorate([
  43004. BABYLON.serialize("roughness")
  43005. ], StandardMaterial.prototype, "_roughness", void 0);
  43006. __decorate([
  43007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43008. ], StandardMaterial.prototype, "roughness", void 0);
  43009. __decorate([
  43010. BABYLON.serialize()
  43011. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43012. __decorate([
  43013. BABYLON.serialize()
  43014. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43015. __decorate([
  43016. BABYLON.serialize()
  43017. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43018. __decorate([
  43019. BABYLON.serialize("useLightmapAsShadowmap")
  43020. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43021. __decorate([
  43022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43023. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43024. __decorate([
  43025. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43026. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43027. __decorate([
  43028. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43029. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43030. __decorate([
  43031. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43032. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43033. __decorate([
  43034. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43035. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43036. __decorate([
  43037. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43038. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43039. __decorate([
  43040. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43041. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43042. __decorate([
  43043. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43044. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43045. __decorate([
  43046. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43047. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43048. __decorate([
  43049. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43050. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43051. __decorate([
  43052. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43053. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43054. __decorate([
  43055. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43056. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43057. __decorate([
  43058. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43059. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43060. __decorate([
  43061. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43062. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43063. __decorate([
  43064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43065. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43066. __decorate([
  43067. BABYLON.serialize("maxSimultaneousLights")
  43068. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43069. __decorate([
  43070. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43071. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43072. __decorate([
  43073. BABYLON.serialize("invertNormalMapX")
  43074. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43075. __decorate([
  43076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43077. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43078. __decorate([
  43079. BABYLON.serialize("invertNormalMapY")
  43080. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43081. __decorate([
  43082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43083. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43084. __decorate([
  43085. BABYLON.serialize("twoSidedLighting")
  43086. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43087. __decorate([
  43088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43089. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43090. __decorate([
  43091. BABYLON.serialize()
  43092. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43093. return StandardMaterial;
  43094. }(BABYLON.PushMaterial));
  43095. BABYLON.StandardMaterial = StandardMaterial;
  43096. })(BABYLON || (BABYLON = {}));
  43097. //# sourceMappingURL=babylon.standardMaterial.js.map
  43098. var BABYLON;
  43099. (function (BABYLON) {
  43100. /**
  43101. * Class representing spherical polynomial coefficients to the 3rd degree
  43102. */
  43103. var SphericalPolynomial = /** @class */ (function () {
  43104. function SphericalPolynomial() {
  43105. /**
  43106. * The x coefficients of the spherical polynomial
  43107. */
  43108. this.x = BABYLON.Vector3.Zero();
  43109. /**
  43110. * The y coefficients of the spherical polynomial
  43111. */
  43112. this.y = BABYLON.Vector3.Zero();
  43113. /**
  43114. * The z coefficients of the spherical polynomial
  43115. */
  43116. this.z = BABYLON.Vector3.Zero();
  43117. /**
  43118. * The xx coefficients of the spherical polynomial
  43119. */
  43120. this.xx = BABYLON.Vector3.Zero();
  43121. /**
  43122. * The yy coefficients of the spherical polynomial
  43123. */
  43124. this.yy = BABYLON.Vector3.Zero();
  43125. /**
  43126. * The zz coefficients of the spherical polynomial
  43127. */
  43128. this.zz = BABYLON.Vector3.Zero();
  43129. /**
  43130. * The xy coefficients of the spherical polynomial
  43131. */
  43132. this.xy = BABYLON.Vector3.Zero();
  43133. /**
  43134. * The yz coefficients of the spherical polynomial
  43135. */
  43136. this.yz = BABYLON.Vector3.Zero();
  43137. /**
  43138. * The zx coefficients of the spherical polynomial
  43139. */
  43140. this.zx = BABYLON.Vector3.Zero();
  43141. }
  43142. /**
  43143. * Adds an ambient color to the spherical polynomial
  43144. * @param color the color to add
  43145. */
  43146. SphericalPolynomial.prototype.addAmbient = function (color) {
  43147. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43148. this.xx = this.xx.add(colorVector);
  43149. this.yy = this.yy.add(colorVector);
  43150. this.zz = this.zz.add(colorVector);
  43151. };
  43152. /**
  43153. * Scales the spherical polynomial by the given amount
  43154. * @param scale the amount to scale
  43155. */
  43156. SphericalPolynomial.prototype.scale = function (scale) {
  43157. this.x = this.x.scale(scale);
  43158. this.y = this.y.scale(scale);
  43159. this.z = this.z.scale(scale);
  43160. this.xx = this.xx.scale(scale);
  43161. this.yy = this.yy.scale(scale);
  43162. this.zz = this.zz.scale(scale);
  43163. this.yz = this.yz.scale(scale);
  43164. this.zx = this.zx.scale(scale);
  43165. this.xy = this.xy.scale(scale);
  43166. };
  43167. /**
  43168. * Gets the spherical polynomial from harmonics
  43169. * @param harmonics the spherical harmonics
  43170. * @returns the spherical polynomial
  43171. */
  43172. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43173. var result = new SphericalPolynomial();
  43174. result.x = harmonics.l11.scale(1.02333);
  43175. result.y = harmonics.l1_1.scale(1.02333);
  43176. result.z = harmonics.l10.scale(1.02333);
  43177. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43178. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43179. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43180. result.yz = harmonics.l2_1.scale(0.858086);
  43181. result.zx = harmonics.l21.scale(0.858086);
  43182. result.xy = harmonics.l2_2.scale(0.858086);
  43183. result.scale(1.0 / Math.PI);
  43184. return result;
  43185. };
  43186. /**
  43187. * Constructs a spherical polynomial from an array.
  43188. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43189. * @returns the spherical polynomial
  43190. */
  43191. SphericalPolynomial.FromArray = function (data) {
  43192. var sp = new SphericalPolynomial();
  43193. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43194. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43195. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43196. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43197. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43198. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43199. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43200. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43201. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43202. return sp;
  43203. };
  43204. return SphericalPolynomial;
  43205. }());
  43206. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43207. /**
  43208. * Class representing spherical harmonics coefficients to the 3rd degree
  43209. */
  43210. var SphericalHarmonics = /** @class */ (function () {
  43211. function SphericalHarmonics() {
  43212. /**
  43213. * The l0,0 coefficients of the spherical harmonics
  43214. */
  43215. this.l00 = BABYLON.Vector3.Zero();
  43216. /**
  43217. * The l1,-1 coefficients of the spherical harmonics
  43218. */
  43219. this.l1_1 = BABYLON.Vector3.Zero();
  43220. /**
  43221. * The l1,0 coefficients of the spherical harmonics
  43222. */
  43223. this.l10 = BABYLON.Vector3.Zero();
  43224. /**
  43225. * The l1,1 coefficients of the spherical harmonics
  43226. */
  43227. this.l11 = BABYLON.Vector3.Zero();
  43228. /**
  43229. * The l2,-2 coefficients of the spherical harmonics
  43230. */
  43231. this.l2_2 = BABYLON.Vector3.Zero();
  43232. /**
  43233. * The l2,-1 coefficients of the spherical harmonics
  43234. */
  43235. this.l2_1 = BABYLON.Vector3.Zero();
  43236. /**
  43237. * The l2,0 coefficients of the spherical harmonics
  43238. */
  43239. this.l20 = BABYLON.Vector3.Zero();
  43240. /**
  43241. * The l2,1 coefficients of the spherical harmonics
  43242. */
  43243. this.l21 = BABYLON.Vector3.Zero();
  43244. /**
  43245. * The l2,2 coefficients of the spherical harmonics
  43246. */
  43247. this.lL22 = BABYLON.Vector3.Zero();
  43248. }
  43249. /**
  43250. * Adds a light to the spherical harmonics
  43251. * @param direction the direction of the light
  43252. * @param color the color of the light
  43253. * @param deltaSolidAngle the delta solid angle of the light
  43254. */
  43255. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43256. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43257. var c = colorVector.scale(deltaSolidAngle);
  43258. this.l00 = this.l00.add(c.scale(0.282095));
  43259. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43260. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43261. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43262. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43263. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43264. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43265. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43266. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43267. };
  43268. /**
  43269. * Scales the spherical harmonics by the given amount
  43270. * @param scale the amount to scale
  43271. */
  43272. SphericalHarmonics.prototype.scale = function (scale) {
  43273. this.l00 = this.l00.scale(scale);
  43274. this.l1_1 = this.l1_1.scale(scale);
  43275. this.l10 = this.l10.scale(scale);
  43276. this.l11 = this.l11.scale(scale);
  43277. this.l2_2 = this.l2_2.scale(scale);
  43278. this.l2_1 = this.l2_1.scale(scale);
  43279. this.l20 = this.l20.scale(scale);
  43280. this.l21 = this.l21.scale(scale);
  43281. this.lL22 = this.lL22.scale(scale);
  43282. };
  43283. /**
  43284. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43285. *
  43286. * ```
  43287. * E_lm = A_l * L_lm
  43288. * ```
  43289. *
  43290. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43291. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43292. * the scaling factors are given in equation 9.
  43293. */
  43294. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43295. // Constant (Band 0)
  43296. this.l00 = this.l00.scale(3.141593);
  43297. // Linear (Band 1)
  43298. this.l1_1 = this.l1_1.scale(2.094395);
  43299. this.l10 = this.l10.scale(2.094395);
  43300. this.l11 = this.l11.scale(2.094395);
  43301. // Quadratic (Band 2)
  43302. this.l2_2 = this.l2_2.scale(0.785398);
  43303. this.l2_1 = this.l2_1.scale(0.785398);
  43304. this.l20 = this.l20.scale(0.785398);
  43305. this.l21 = this.l21.scale(0.785398);
  43306. this.lL22 = this.lL22.scale(0.785398);
  43307. };
  43308. /**
  43309. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43310. *
  43311. * ```
  43312. * L = (1/pi) * E * rho
  43313. * ```
  43314. *
  43315. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43316. */
  43317. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43318. this.scale(1.0 / Math.PI);
  43319. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43320. // (The pixel shader must apply albedo after texture fetches, etc).
  43321. };
  43322. /**
  43323. * Gets the spherical harmonics from polynomial
  43324. * @param polynomial the spherical polynomial
  43325. * @returns the spherical harmonics
  43326. */
  43327. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43328. var result = new SphericalHarmonics();
  43329. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43330. result.l1_1 = polynomial.y.scale(0.977204);
  43331. result.l10 = polynomial.z.scale(0.977204);
  43332. result.l11 = polynomial.x.scale(0.977204);
  43333. result.l2_2 = polynomial.xy.scale(1.16538);
  43334. result.l2_1 = polynomial.yz.scale(1.16538);
  43335. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43336. result.l21 = polynomial.zx.scale(1.16538);
  43337. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43338. result.scale(Math.PI);
  43339. return result;
  43340. };
  43341. /**
  43342. * Constructs a spherical harmonics from an array.
  43343. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43344. * @returns the spherical harmonics
  43345. */
  43346. SphericalHarmonics.FromArray = function (data) {
  43347. var sh = new SphericalHarmonics();
  43348. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43349. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43350. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43351. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43352. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43353. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43354. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43355. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43356. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43357. return sh;
  43358. };
  43359. return SphericalHarmonics;
  43360. }());
  43361. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43362. })(BABYLON || (BABYLON = {}));
  43363. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43364. var BABYLON;
  43365. (function (BABYLON) {
  43366. var FileFaceOrientation = /** @class */ (function () {
  43367. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43368. this.name = name;
  43369. this.worldAxisForNormal = worldAxisForNormal;
  43370. this.worldAxisForFileX = worldAxisForFileX;
  43371. this.worldAxisForFileY = worldAxisForFileY;
  43372. }
  43373. return FileFaceOrientation;
  43374. }());
  43375. ;
  43376. /**
  43377. * Helper class dealing with the extraction of spherical polynomial dataArray
  43378. * from a cube map.
  43379. */
  43380. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43381. function CubeMapToSphericalPolynomialTools() {
  43382. }
  43383. /**
  43384. * Converts a texture to the according Spherical Polynomial data.
  43385. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43386. *
  43387. * @param texture The texture to extract the information from.
  43388. * @return The Spherical Polynomial data.
  43389. */
  43390. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43391. if (!texture.isCube) {
  43392. // Only supports cube Textures currently.
  43393. return null;
  43394. }
  43395. var size = texture.getSize().width;
  43396. var right = texture.readPixels(0);
  43397. var left = texture.readPixels(1);
  43398. var up;
  43399. var down;
  43400. if (texture.isRenderTarget) {
  43401. up = texture.readPixels(3);
  43402. down = texture.readPixels(2);
  43403. }
  43404. else {
  43405. up = texture.readPixels(2);
  43406. down = texture.readPixels(3);
  43407. }
  43408. var front = texture.readPixels(4);
  43409. var back = texture.readPixels(5);
  43410. var gammaSpace = texture.gammaSpace;
  43411. // Always read as RGBA.
  43412. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43413. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43414. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43415. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43416. }
  43417. var cubeInfo = {
  43418. size: size,
  43419. right: right,
  43420. left: left,
  43421. up: up,
  43422. down: down,
  43423. front: front,
  43424. back: back,
  43425. format: format,
  43426. type: type,
  43427. gammaSpace: gammaSpace,
  43428. };
  43429. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43430. };
  43431. /**
  43432. * Converts a cubemap to the according Spherical Polynomial data.
  43433. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43434. *
  43435. * @param cubeInfo The Cube map to extract the information from.
  43436. * @return The Spherical Polynomial data.
  43437. */
  43438. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43439. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43440. var totalSolidAngle = 0.0;
  43441. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43442. var du = 2.0 / cubeInfo.size;
  43443. var dv = du;
  43444. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43445. var minUV = du * 0.5 - 1.0;
  43446. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43447. var fileFace = this.FileFaces[faceIndex];
  43448. var dataArray = cubeInfo[fileFace.name];
  43449. var v = minUV;
  43450. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43451. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43452. // Because SP is still linear, so summation is fine in that basis.
  43453. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43454. for (var y = 0; y < cubeInfo.size; y++) {
  43455. var u = minUV;
  43456. for (var x = 0; x < cubeInfo.size; x++) {
  43457. // World direction (not normalised)
  43458. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43459. worldDirection.normalize();
  43460. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43461. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43462. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43463. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43464. // Handle Integer types.
  43465. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43466. r /= 255;
  43467. g /= 255;
  43468. b /= 255;
  43469. }
  43470. // Handle Gamma space textures.
  43471. if (cubeInfo.gammaSpace) {
  43472. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43473. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43474. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43475. }
  43476. var color = new BABYLON.Color3(r, g, b);
  43477. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43478. totalSolidAngle += deltaSolidAngle;
  43479. u += du;
  43480. }
  43481. v += dv;
  43482. }
  43483. }
  43484. // Solid angle for entire sphere is 4*pi
  43485. var sphereSolidAngle = 4.0 * Math.PI;
  43486. // Adjust the solid angle to allow for how many faces we processed.
  43487. var facesProcessed = 6.0;
  43488. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43489. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43490. // This is needed because the numerical integration over the cube uses a
  43491. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43492. // and also to compensate for accumulative error due to float precision in the summation.
  43493. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43494. sphericalHarmonics.scale(correctionFactor);
  43495. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43496. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43497. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43498. };
  43499. CubeMapToSphericalPolynomialTools.FileFaces = [
  43500. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43501. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43502. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43503. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43504. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43505. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43506. ];
  43507. return CubeMapToSphericalPolynomialTools;
  43508. }());
  43509. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43510. })(BABYLON || (BABYLON = {}));
  43511. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43512. var BABYLON;
  43513. (function (BABYLON) {
  43514. /**
  43515. * Manages the defines for the PBR Material.
  43516. * @hiddenChildren
  43517. */
  43518. var PBRMaterialDefines = /** @class */ (function (_super) {
  43519. __extends(PBRMaterialDefines, _super);
  43520. /**
  43521. * Initializes the PBR Material defines.
  43522. */
  43523. function PBRMaterialDefines() {
  43524. var _this = _super.call(this) || this;
  43525. _this.PBR = true;
  43526. _this.MAINUV1 = false;
  43527. _this.MAINUV2 = false;
  43528. _this.UV1 = false;
  43529. _this.UV2 = false;
  43530. _this.ALBEDO = false;
  43531. _this.ALBEDODIRECTUV = 0;
  43532. _this.VERTEXCOLOR = false;
  43533. _this.AMBIENT = false;
  43534. _this.AMBIENTDIRECTUV = 0;
  43535. _this.AMBIENTINGRAYSCALE = false;
  43536. _this.OPACITY = false;
  43537. _this.VERTEXALPHA = false;
  43538. _this.OPACITYDIRECTUV = 0;
  43539. _this.OPACITYRGB = false;
  43540. _this.ALPHATEST = false;
  43541. _this.DEPTHPREPASS = false;
  43542. _this.ALPHABLEND = false;
  43543. _this.ALPHAFROMALBEDO = false;
  43544. _this.ALPHATESTVALUE = "0.5";
  43545. _this.SPECULAROVERALPHA = false;
  43546. _this.RADIANCEOVERALPHA = false;
  43547. _this.ALPHAFRESNEL = false;
  43548. _this.LINEARALPHAFRESNEL = false;
  43549. _this.PREMULTIPLYALPHA = false;
  43550. _this.EMISSIVE = false;
  43551. _this.EMISSIVEDIRECTUV = 0;
  43552. _this.REFLECTIVITY = false;
  43553. _this.REFLECTIVITYDIRECTUV = 0;
  43554. _this.SPECULARTERM = false;
  43555. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43556. _this.MICROSURFACEAUTOMATIC = false;
  43557. _this.LODBASEDMICROSFURACE = false;
  43558. _this.MICROSURFACEMAP = false;
  43559. _this.MICROSURFACEMAPDIRECTUV = 0;
  43560. _this.METALLICWORKFLOW = false;
  43561. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43562. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43563. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43564. _this.AOSTOREINMETALMAPRED = false;
  43565. _this.ENVIRONMENTBRDF = false;
  43566. _this.NORMAL = false;
  43567. _this.TANGENT = false;
  43568. _this.BUMP = false;
  43569. _this.BUMPDIRECTUV = 0;
  43570. _this.OBJECTSPACE_NORMALMAP = false;
  43571. _this.PARALLAX = false;
  43572. _this.PARALLAXOCCLUSION = false;
  43573. _this.NORMALXYSCALE = true;
  43574. _this.LIGHTMAP = false;
  43575. _this.LIGHTMAPDIRECTUV = 0;
  43576. _this.USELIGHTMAPASSHADOWMAP = false;
  43577. _this.GAMMALIGHTMAP = false;
  43578. _this.REFLECTION = false;
  43579. _this.REFLECTIONMAP_3D = false;
  43580. _this.REFLECTIONMAP_SPHERICAL = false;
  43581. _this.REFLECTIONMAP_PLANAR = false;
  43582. _this.REFLECTIONMAP_CUBIC = false;
  43583. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43584. _this.REFLECTIONMAP_PROJECTION = false;
  43585. _this.REFLECTIONMAP_SKYBOX = false;
  43586. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43587. _this.REFLECTIONMAP_EXPLICIT = false;
  43588. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43589. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43590. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43591. _this.INVERTCUBICMAP = false;
  43592. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43593. _this.USESPHERICALINVERTEX = false;
  43594. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43595. _this.LODINREFLECTIONALPHA = false;
  43596. _this.GAMMAREFLECTION = false;
  43597. _this.RGBDREFLECTION = false;
  43598. _this.RADIANCEOCCLUSION = false;
  43599. _this.HORIZONOCCLUSION = false;
  43600. _this.REFRACTION = false;
  43601. _this.REFRACTIONMAP_3D = false;
  43602. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43603. _this.LODINREFRACTIONALPHA = false;
  43604. _this.GAMMAREFRACTION = false;
  43605. _this.RGBDREFRACTION = false;
  43606. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43607. _this.INSTANCES = false;
  43608. _this.NUM_BONE_INFLUENCERS = 0;
  43609. _this.BonesPerMesh = 0;
  43610. _this.NONUNIFORMSCALING = false;
  43611. _this.MORPHTARGETS = false;
  43612. _this.MORPHTARGETS_NORMAL = false;
  43613. _this.MORPHTARGETS_TANGENT = false;
  43614. _this.NUM_MORPH_INFLUENCERS = 0;
  43615. _this.IMAGEPROCESSING = false;
  43616. _this.VIGNETTE = false;
  43617. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43618. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43619. _this.TONEMAPPING = false;
  43620. _this.TONEMAPPING_ACES = false;
  43621. _this.CONTRAST = false;
  43622. _this.COLORCURVES = false;
  43623. _this.COLORGRADING = false;
  43624. _this.COLORGRADING3D = false;
  43625. _this.SAMPLER3DGREENDEPTH = false;
  43626. _this.SAMPLER3DBGRMAP = false;
  43627. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43628. _this.EXPOSURE = false;
  43629. _this.USEPHYSICALLIGHTFALLOFF = false;
  43630. _this.USEGLTFLIGHTFALLOFF = false;
  43631. _this.TWOSIDEDLIGHTING = false;
  43632. _this.SHADOWFLOAT = false;
  43633. _this.CLIPPLANE = false;
  43634. _this.CLIPPLANE2 = false;
  43635. _this.CLIPPLANE3 = false;
  43636. _this.CLIPPLANE4 = false;
  43637. _this.POINTSIZE = false;
  43638. _this.FOG = false;
  43639. _this.LOGARITHMICDEPTH = false;
  43640. _this.FORCENORMALFORWARD = false;
  43641. _this.SPECULARAA = false;
  43642. _this.UNLIT = false;
  43643. _this.rebuild();
  43644. return _this;
  43645. }
  43646. /**
  43647. * Resets the PBR Material defines.
  43648. */
  43649. PBRMaterialDefines.prototype.reset = function () {
  43650. _super.prototype.reset.call(this);
  43651. this.ALPHATESTVALUE = "0.5";
  43652. this.PBR = true;
  43653. };
  43654. return PBRMaterialDefines;
  43655. }(BABYLON.MaterialDefines));
  43656. /**
  43657. * The Physically based material base class of BJS.
  43658. *
  43659. * This offers the main features of a standard PBR material.
  43660. * For more information, please refer to the documentation :
  43661. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43662. */
  43663. var PBRBaseMaterial = /** @class */ (function (_super) {
  43664. __extends(PBRBaseMaterial, _super);
  43665. /**
  43666. * Instantiates a new PBRMaterial instance.
  43667. *
  43668. * @param name The material name
  43669. * @param scene The scene the material will be use in.
  43670. */
  43671. function PBRBaseMaterial(name, scene) {
  43672. var _this = _super.call(this, name, scene) || this;
  43673. /**
  43674. * Intensity of the direct lights e.g. the four lights available in your scene.
  43675. * This impacts both the direct diffuse and specular highlights.
  43676. */
  43677. _this._directIntensity = 1.0;
  43678. /**
  43679. * Intensity of the emissive part of the material.
  43680. * This helps controlling the emissive effect without modifying the emissive color.
  43681. */
  43682. _this._emissiveIntensity = 1.0;
  43683. /**
  43684. * Intensity of the environment e.g. how much the environment will light the object
  43685. * either through harmonics for rough material or through the refelction for shiny ones.
  43686. */
  43687. _this._environmentIntensity = 1.0;
  43688. /**
  43689. * This is a special control allowing the reduction of the specular highlights coming from the
  43690. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43691. */
  43692. _this._specularIntensity = 1.0;
  43693. /**
  43694. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43695. */
  43696. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43697. /**
  43698. * Debug Control allowing disabling the bump map on this material.
  43699. */
  43700. _this._disableBumpMap = false;
  43701. /**
  43702. * AKA Occlusion Texture Intensity in other nomenclature.
  43703. */
  43704. _this._ambientTextureStrength = 1.0;
  43705. /**
  43706. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43707. * 1 means it completely occludes it
  43708. * 0 mean it has no impact
  43709. */
  43710. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43711. /**
  43712. * The color of a material in ambient lighting.
  43713. */
  43714. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43715. /**
  43716. * AKA Diffuse Color in other nomenclature.
  43717. */
  43718. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43719. /**
  43720. * AKA Specular Color in other nomenclature.
  43721. */
  43722. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43723. /**
  43724. * The color applied when light is reflected from a material.
  43725. */
  43726. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43727. /**
  43728. * The color applied when light is emitted from a material.
  43729. */
  43730. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43731. /**
  43732. * AKA Glossiness in other nomenclature.
  43733. */
  43734. _this._microSurface = 0.9;
  43735. /**
  43736. * source material index of refraction (IOR)' / 'destination material IOR.
  43737. */
  43738. _this._indexOfRefraction = 0.66;
  43739. /**
  43740. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43741. */
  43742. _this._invertRefractionY = false;
  43743. /**
  43744. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43745. * Materials half opaque for instance using refraction could benefit from this control.
  43746. */
  43747. _this._linkRefractionWithTransparency = false;
  43748. /**
  43749. * Specifies that the material will use the light map as a show map.
  43750. */
  43751. _this._useLightmapAsShadowmap = false;
  43752. /**
  43753. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43754. * makes the reflect vector face the model (under horizon).
  43755. */
  43756. _this._useHorizonOcclusion = true;
  43757. /**
  43758. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43759. * too much the area relying on ambient texture to define their ambient occlusion.
  43760. */
  43761. _this._useRadianceOcclusion = true;
  43762. /**
  43763. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43764. */
  43765. _this._useAlphaFromAlbedoTexture = false;
  43766. /**
  43767. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43768. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43769. */
  43770. _this._useSpecularOverAlpha = true;
  43771. /**
  43772. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43773. */
  43774. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43775. /**
  43776. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43777. */
  43778. _this._useRoughnessFromMetallicTextureAlpha = true;
  43779. /**
  43780. * Specifies if the metallic texture contains the roughness information in its green channel.
  43781. */
  43782. _this._useRoughnessFromMetallicTextureGreen = false;
  43783. /**
  43784. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43785. */
  43786. _this._useMetallnessFromMetallicTextureBlue = false;
  43787. /**
  43788. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43789. */
  43790. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43791. /**
  43792. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43793. */
  43794. _this._useAmbientInGrayScale = false;
  43795. /**
  43796. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43797. * The material will try to infer what glossiness each pixel should be.
  43798. */
  43799. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43800. /**
  43801. * Defines the falloff type used in this material.
  43802. * It by default is Physical.
  43803. */
  43804. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43805. /**
  43806. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43807. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43808. */
  43809. _this._useRadianceOverAlpha = true;
  43810. /**
  43811. * Allows using an object space normal map (instead of tangent space).
  43812. */
  43813. _this._useObjectSpaceNormalMap = false;
  43814. /**
  43815. * Allows using the bump map in parallax mode.
  43816. */
  43817. _this._useParallax = false;
  43818. /**
  43819. * Allows using the bump map in parallax occlusion mode.
  43820. */
  43821. _this._useParallaxOcclusion = false;
  43822. /**
  43823. * Controls the scale bias of the parallax mode.
  43824. */
  43825. _this._parallaxScaleBias = 0.05;
  43826. /**
  43827. * If sets to true, disables all the lights affecting the material.
  43828. */
  43829. _this._disableLighting = false;
  43830. /**
  43831. * Number of Simultaneous lights allowed on the material.
  43832. */
  43833. _this._maxSimultaneousLights = 4;
  43834. /**
  43835. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43836. */
  43837. _this._invertNormalMapX = false;
  43838. /**
  43839. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43840. */
  43841. _this._invertNormalMapY = false;
  43842. /**
  43843. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43844. */
  43845. _this._twoSidedLighting = false;
  43846. /**
  43847. * Defines the alpha limits in alpha test mode.
  43848. */
  43849. _this._alphaCutOff = 0.4;
  43850. /**
  43851. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43852. */
  43853. _this._forceAlphaTest = false;
  43854. /**
  43855. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43856. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43857. */
  43858. _this._useAlphaFresnel = false;
  43859. /**
  43860. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43861. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43862. */
  43863. _this._useLinearAlphaFresnel = false;
  43864. /**
  43865. * The transparency mode of the material.
  43866. */
  43867. _this._transparencyMode = null;
  43868. /**
  43869. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43870. * from cos thetav and roughness:
  43871. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43872. */
  43873. _this._environmentBRDFTexture = null;
  43874. /**
  43875. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43876. */
  43877. _this._forceIrradianceInFragment = false;
  43878. /**
  43879. * Force normal to face away from face.
  43880. */
  43881. _this._forceNormalForward = false;
  43882. /**
  43883. * Enables specular anti aliasing in the PBR shader.
  43884. * It will both interacts on the Geometry for analytical and IBL lighting.
  43885. * It also prefilter the roughness map based on the bump values.
  43886. */
  43887. _this._enableSpecularAntiAliasing = false;
  43888. /**
  43889. * Stores the available render targets.
  43890. */
  43891. _this._renderTargets = new BABYLON.SmartArray(16);
  43892. /**
  43893. * Sets the global ambient color for the material used in lighting calculations.
  43894. */
  43895. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43896. /**
  43897. * If set to true, no lighting calculations will be applied.
  43898. */
  43899. _this._unlit = false;
  43900. // Setup the default processing configuration to the scene.
  43901. _this._attachImageProcessingConfiguration(null);
  43902. _this.getRenderTargetTextures = function () {
  43903. _this._renderTargets.reset();
  43904. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43905. _this._renderTargets.push(_this._reflectionTexture);
  43906. }
  43907. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43908. _this._renderTargets.push(_this._refractionTexture);
  43909. }
  43910. return _this._renderTargets;
  43911. };
  43912. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43913. return _this;
  43914. }
  43915. /**
  43916. * Attaches a new image processing configuration to the PBR Material.
  43917. * @param configuration
  43918. */
  43919. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43920. var _this = this;
  43921. if (configuration === this._imageProcessingConfiguration) {
  43922. return;
  43923. }
  43924. // Detaches observer.
  43925. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43926. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43927. }
  43928. // Pick the scene configuration if needed.
  43929. if (!configuration) {
  43930. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43931. }
  43932. else {
  43933. this._imageProcessingConfiguration = configuration;
  43934. }
  43935. // Attaches observer.
  43936. if (this._imageProcessingConfiguration) {
  43937. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43938. _this._markAllSubMeshesAsImageProcessingDirty();
  43939. });
  43940. }
  43941. };
  43942. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43943. /**
  43944. * Gets a boolean indicating that current material needs to register RTT
  43945. */
  43946. get: function () {
  43947. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43948. return true;
  43949. }
  43950. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43951. return true;
  43952. }
  43953. return false;
  43954. },
  43955. enumerable: true,
  43956. configurable: true
  43957. });
  43958. /**
  43959. * Gets the name of the material class.
  43960. */
  43961. PBRBaseMaterial.prototype.getClassName = function () {
  43962. return "PBRBaseMaterial";
  43963. };
  43964. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43965. /**
  43966. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43967. */
  43968. get: function () {
  43969. return this._useLogarithmicDepth;
  43970. },
  43971. /**
  43972. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43973. */
  43974. set: function (value) {
  43975. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43976. },
  43977. enumerable: true,
  43978. configurable: true
  43979. });
  43980. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43981. /**
  43982. * Gets the current transparency mode.
  43983. */
  43984. get: function () {
  43985. return this._transparencyMode;
  43986. },
  43987. /**
  43988. * Sets the transparency mode of the material.
  43989. *
  43990. * | Value | Type | Description |
  43991. * | ----- | ----------------------------------- | ----------- |
  43992. * | 0 | OPAQUE | |
  43993. * | 1 | ALPHATEST | |
  43994. * | 2 | ALPHABLEND | |
  43995. * | 3 | ALPHATESTANDBLEND | |
  43996. *
  43997. */
  43998. set: function (value) {
  43999. if (this._transparencyMode === value) {
  44000. return;
  44001. }
  44002. this._transparencyMode = value;
  44003. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44004. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44005. },
  44006. enumerable: true,
  44007. configurable: true
  44008. });
  44009. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44010. /**
  44011. * Returns true if alpha blending should be disabled.
  44012. */
  44013. get: function () {
  44014. return (this._linkRefractionWithTransparency ||
  44015. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44016. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44017. },
  44018. enumerable: true,
  44019. configurable: true
  44020. });
  44021. /**
  44022. * Specifies whether or not this material should be rendered in alpha blend mode.
  44023. */
  44024. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44025. if (this._disableAlphaBlending) {
  44026. return false;
  44027. }
  44028. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44029. };
  44030. /**
  44031. * Specifies if the mesh will require alpha blending.
  44032. * @param mesh - BJS mesh.
  44033. */
  44034. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44035. if (this._disableAlphaBlending) {
  44036. return false;
  44037. }
  44038. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44039. };
  44040. /**
  44041. * Specifies whether or not this material should be rendered in alpha test mode.
  44042. */
  44043. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44044. if (this._forceAlphaTest) {
  44045. return true;
  44046. }
  44047. if (this._linkRefractionWithTransparency) {
  44048. return false;
  44049. }
  44050. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44051. };
  44052. /**
  44053. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44054. */
  44055. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44056. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44057. };
  44058. /**
  44059. * Gets the texture used for the alpha test.
  44060. */
  44061. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44062. return this._albedoTexture;
  44063. };
  44064. /**
  44065. * Specifies that the submesh is ready to be used.
  44066. * @param mesh - BJS mesh.
  44067. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44068. * @param useInstances - Specifies that instances should be used.
  44069. * @returns - boolean indicating that the submesh is ready or not.
  44070. */
  44071. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44072. if (subMesh.effect && this.isFrozen) {
  44073. if (this._wasPreviouslyReady) {
  44074. return true;
  44075. }
  44076. }
  44077. if (!subMesh._materialDefines) {
  44078. subMesh._materialDefines = new PBRMaterialDefines();
  44079. }
  44080. var defines = subMesh._materialDefines;
  44081. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44082. if (defines._renderId === this.getScene().getRenderId()) {
  44083. return true;
  44084. }
  44085. }
  44086. var scene = this.getScene();
  44087. var engine = scene.getEngine();
  44088. if (defines._areTexturesDirty) {
  44089. if (scene.texturesEnabled) {
  44090. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44091. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44092. return false;
  44093. }
  44094. }
  44095. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44096. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44097. return false;
  44098. }
  44099. }
  44100. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44101. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44102. return false;
  44103. }
  44104. }
  44105. var reflectionTexture = this._getReflectionTexture();
  44106. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44107. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44108. return false;
  44109. }
  44110. }
  44111. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44112. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44113. return false;
  44114. }
  44115. }
  44116. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44117. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44118. return false;
  44119. }
  44120. }
  44121. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44122. if (this._metallicTexture) {
  44123. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44124. return false;
  44125. }
  44126. }
  44127. else if (this._reflectivityTexture) {
  44128. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44129. return false;
  44130. }
  44131. }
  44132. if (this._microSurfaceTexture) {
  44133. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44134. return false;
  44135. }
  44136. }
  44137. }
  44138. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44139. // Bump texture cannot be not blocking.
  44140. if (!this._bumpTexture.isReady()) {
  44141. return false;
  44142. }
  44143. }
  44144. var refractionTexture = this._getRefractionTexture();
  44145. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44146. if (!refractionTexture.isReadyOrNotBlocking()) {
  44147. return false;
  44148. }
  44149. }
  44150. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44151. // This is blocking.
  44152. if (!this._environmentBRDFTexture.isReady()) {
  44153. return false;
  44154. }
  44155. }
  44156. }
  44157. }
  44158. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44159. if (!this._imageProcessingConfiguration.isReady()) {
  44160. return false;
  44161. }
  44162. }
  44163. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44164. mesh.createNormals(true);
  44165. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44166. }
  44167. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44168. if (effect) {
  44169. scene.resetCachedMaterial();
  44170. subMesh.setEffect(effect, defines);
  44171. this.buildUniformLayout();
  44172. }
  44173. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44174. return false;
  44175. }
  44176. defines._renderId = scene.getRenderId();
  44177. this._wasPreviouslyReady = true;
  44178. return true;
  44179. };
  44180. /**
  44181. * Specifies if the material uses metallic roughness workflow.
  44182. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44183. */
  44184. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44185. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44186. return true;
  44187. }
  44188. return false;
  44189. };
  44190. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44191. if (onCompiled === void 0) { onCompiled = null; }
  44192. if (onError === void 0) { onError = null; }
  44193. if (useInstances === void 0) { useInstances = null; }
  44194. if (useClipPlane === void 0) { useClipPlane = null; }
  44195. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44196. if (!defines.isDirty) {
  44197. return null;
  44198. }
  44199. defines.markAsProcessed();
  44200. var scene = this.getScene();
  44201. var engine = scene.getEngine();
  44202. // Fallbacks
  44203. var fallbacks = new BABYLON.EffectFallbacks();
  44204. var fallbackRank = 0;
  44205. if (defines.USESPHERICALINVERTEX) {
  44206. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44207. }
  44208. if (defines.FOG) {
  44209. fallbacks.addFallback(fallbackRank, "FOG");
  44210. }
  44211. if (defines.SPECULARAA) {
  44212. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44213. }
  44214. if (defines.POINTSIZE) {
  44215. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44216. }
  44217. if (defines.LOGARITHMICDEPTH) {
  44218. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44219. }
  44220. if (defines.PARALLAX) {
  44221. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44222. }
  44223. if (defines.PARALLAXOCCLUSION) {
  44224. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44225. }
  44226. if (defines.ENVIRONMENTBRDF) {
  44227. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44228. }
  44229. if (defines.TANGENT) {
  44230. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44231. }
  44232. if (defines.BUMP) {
  44233. fallbacks.addFallback(fallbackRank++, "BUMP");
  44234. }
  44235. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44236. if (defines.SPECULARTERM) {
  44237. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44238. }
  44239. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44240. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44241. }
  44242. if (defines.LIGHTMAP) {
  44243. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44244. }
  44245. if (defines.NORMAL) {
  44246. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44247. }
  44248. if (defines.AMBIENT) {
  44249. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44250. }
  44251. if (defines.EMISSIVE) {
  44252. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44253. }
  44254. if (defines.VERTEXCOLOR) {
  44255. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44256. }
  44257. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44258. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44259. }
  44260. if (defines.MORPHTARGETS) {
  44261. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44262. }
  44263. //Attributes
  44264. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44265. if (defines.NORMAL) {
  44266. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44267. }
  44268. if (defines.TANGENT) {
  44269. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44270. }
  44271. if (defines.UV1) {
  44272. attribs.push(BABYLON.VertexBuffer.UVKind);
  44273. }
  44274. if (defines.UV2) {
  44275. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44276. }
  44277. if (defines.VERTEXCOLOR) {
  44278. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44279. }
  44280. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44281. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44282. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44283. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44284. "vFogInfos", "vFogColor", "pointSize",
  44285. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44286. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44287. "mBones",
  44288. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44289. "vLightingIntensity",
  44290. "logarithmicDepthConstant",
  44291. "vSphericalX", "vSphericalY", "vSphericalZ",
  44292. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44293. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44294. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44295. "vTangentSpaceParams"
  44296. ];
  44297. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44298. "bumpSampler", "lightmapSampler", "opacitySampler",
  44299. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44300. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44301. "microSurfaceSampler", "environmentBrdfSampler"];
  44302. var uniformBuffers = ["Material", "Scene"];
  44303. if (BABYLON.ImageProcessingConfiguration) {
  44304. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44305. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44306. }
  44307. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44308. uniformsNames: uniforms,
  44309. uniformBuffersNames: uniformBuffers,
  44310. samplers: samplers,
  44311. defines: defines,
  44312. maxSimultaneousLights: this._maxSimultaneousLights
  44313. });
  44314. var join = defines.toString();
  44315. return engine.createEffect("pbr", {
  44316. attributes: attribs,
  44317. uniformsNames: uniforms,
  44318. uniformBuffersNames: uniformBuffers,
  44319. samplers: samplers,
  44320. defines: join,
  44321. fallbacks: fallbacks,
  44322. onCompiled: onCompiled,
  44323. onError: onError,
  44324. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44325. }, engine);
  44326. };
  44327. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44328. if (useInstances === void 0) { useInstances = null; }
  44329. if (useClipPlane === void 0) { useClipPlane = null; }
  44330. var scene = this.getScene();
  44331. var engine = scene.getEngine();
  44332. // Lights
  44333. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44334. defines._needNormals = true;
  44335. // Textures
  44336. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44337. if (defines._areTexturesDirty) {
  44338. defines._needUVs = false;
  44339. if (scene.texturesEnabled) {
  44340. if (scene.getEngine().getCaps().textureLOD) {
  44341. defines.LODBASEDMICROSFURACE = true;
  44342. }
  44343. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44344. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44345. }
  44346. else {
  44347. defines.ALBEDO = false;
  44348. }
  44349. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44350. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44351. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44352. }
  44353. else {
  44354. defines.AMBIENT = false;
  44355. }
  44356. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44357. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44358. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44359. }
  44360. else {
  44361. defines.OPACITY = false;
  44362. }
  44363. var reflectionTexture = this._getReflectionTexture();
  44364. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44365. defines.REFLECTION = true;
  44366. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44367. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44368. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44369. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44370. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44371. defines.INVERTCUBICMAP = true;
  44372. }
  44373. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44374. switch (reflectionTexture.coordinatesMode) {
  44375. case BABYLON.Texture.EXPLICIT_MODE:
  44376. defines.REFLECTIONMAP_EXPLICIT = true;
  44377. break;
  44378. case BABYLON.Texture.PLANAR_MODE:
  44379. defines.REFLECTIONMAP_PLANAR = true;
  44380. break;
  44381. case BABYLON.Texture.PROJECTION_MODE:
  44382. defines.REFLECTIONMAP_PROJECTION = true;
  44383. break;
  44384. case BABYLON.Texture.SKYBOX_MODE:
  44385. defines.REFLECTIONMAP_SKYBOX = true;
  44386. break;
  44387. case BABYLON.Texture.SPHERICAL_MODE:
  44388. defines.REFLECTIONMAP_SPHERICAL = true;
  44389. break;
  44390. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44391. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44392. break;
  44393. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44394. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44395. break;
  44396. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44397. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44398. break;
  44399. case BABYLON.Texture.CUBIC_MODE:
  44400. case BABYLON.Texture.INVCUBIC_MODE:
  44401. default:
  44402. defines.REFLECTIONMAP_CUBIC = true;
  44403. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44404. break;
  44405. }
  44406. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44407. if (reflectionTexture.sphericalPolynomial) {
  44408. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44409. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44410. defines.USESPHERICALINVERTEX = false;
  44411. }
  44412. else {
  44413. defines.USESPHERICALINVERTEX = true;
  44414. }
  44415. }
  44416. }
  44417. else {
  44418. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44419. }
  44420. }
  44421. else {
  44422. defines.REFLECTION = false;
  44423. defines.REFLECTIONMAP_3D = false;
  44424. defines.REFLECTIONMAP_SPHERICAL = false;
  44425. defines.REFLECTIONMAP_PLANAR = false;
  44426. defines.REFLECTIONMAP_CUBIC = false;
  44427. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44428. defines.REFLECTIONMAP_PROJECTION = false;
  44429. defines.REFLECTIONMAP_SKYBOX = false;
  44430. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44431. defines.REFLECTIONMAP_EXPLICIT = false;
  44432. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44433. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44434. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44435. defines.INVERTCUBICMAP = false;
  44436. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44437. defines.USESPHERICALINVERTEX = false;
  44438. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44439. defines.LODINREFLECTIONALPHA = false;
  44440. defines.GAMMAREFLECTION = false;
  44441. defines.RGBDREFLECTION = false;
  44442. }
  44443. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44444. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44445. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44446. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44447. }
  44448. else {
  44449. defines.LIGHTMAP = false;
  44450. }
  44451. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44452. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44453. }
  44454. else {
  44455. defines.EMISSIVE = false;
  44456. }
  44457. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44458. if (this._metallicTexture) {
  44459. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44460. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44461. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44462. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44463. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44464. }
  44465. else if (this._reflectivityTexture) {
  44466. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44467. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44468. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44469. }
  44470. else {
  44471. defines.REFLECTIVITY = false;
  44472. }
  44473. if (this._microSurfaceTexture) {
  44474. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44475. }
  44476. else {
  44477. defines.MICROSURFACEMAP = false;
  44478. }
  44479. }
  44480. else {
  44481. defines.REFLECTIVITY = false;
  44482. defines.MICROSURFACEMAP = false;
  44483. }
  44484. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44485. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44486. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44487. defines.PARALLAX = true;
  44488. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44489. }
  44490. else {
  44491. defines.PARALLAX = false;
  44492. }
  44493. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44494. }
  44495. else {
  44496. defines.BUMP = false;
  44497. }
  44498. var refractionTexture = this._getRefractionTexture();
  44499. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44500. defines.REFRACTION = true;
  44501. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44502. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44503. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44504. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44505. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44506. if (this._linkRefractionWithTransparency) {
  44507. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44508. }
  44509. }
  44510. else {
  44511. defines.REFRACTION = false;
  44512. }
  44513. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44514. defines.ENVIRONMENTBRDF = true;
  44515. }
  44516. else {
  44517. defines.ENVIRONMENTBRDF = false;
  44518. }
  44519. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44520. defines.ALPHAFROMALBEDO = true;
  44521. }
  44522. else {
  44523. defines.ALPHAFROMALBEDO = false;
  44524. }
  44525. }
  44526. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44527. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44528. defines.USEPHYSICALLIGHTFALLOFF = false;
  44529. defines.USEGLTFLIGHTFALLOFF = false;
  44530. }
  44531. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44532. defines.USEPHYSICALLIGHTFALLOFF = false;
  44533. defines.USEGLTFLIGHTFALLOFF = true;
  44534. }
  44535. else {
  44536. defines.USEPHYSICALLIGHTFALLOFF = true;
  44537. defines.USEGLTFLIGHTFALLOFF = false;
  44538. }
  44539. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44540. if (!this.backFaceCulling && this._twoSidedLighting) {
  44541. defines.TWOSIDEDLIGHTING = true;
  44542. }
  44543. else {
  44544. defines.TWOSIDEDLIGHTING = false;
  44545. }
  44546. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44547. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44548. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44549. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44550. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44551. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44552. }
  44553. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44554. this._imageProcessingConfiguration.prepareDefines(defines);
  44555. }
  44556. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44557. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44558. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44559. // Misc.
  44560. if (defines._areMiscDirty) {
  44561. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44562. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44563. }
  44564. // Values that need to be evaluated on every frame
  44565. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44566. // Attribs
  44567. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44568. };
  44569. /**
  44570. * Force shader compilation
  44571. */
  44572. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44573. var _this = this;
  44574. var localOptions = __assign({ clipPlane: false }, options);
  44575. var defines = new PBRMaterialDefines();
  44576. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44577. if (effect.isReady()) {
  44578. if (onCompiled) {
  44579. onCompiled(this);
  44580. }
  44581. }
  44582. else {
  44583. effect.onCompileObservable.add(function () {
  44584. if (onCompiled) {
  44585. onCompiled(_this);
  44586. }
  44587. });
  44588. }
  44589. };
  44590. /**
  44591. * Initializes the uniform buffer layout for the shader.
  44592. */
  44593. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44594. // Order is important !
  44595. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44596. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44597. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44598. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44599. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44600. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44601. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44602. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44603. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44604. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44605. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44606. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44607. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44608. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44609. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44610. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44611. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44612. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44613. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44614. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44615. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44616. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44617. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44618. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44619. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44620. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44621. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44622. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44623. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44624. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44625. this._uniformBuffer.addUniform("pointSize", 1);
  44626. this._uniformBuffer.create();
  44627. };
  44628. /**
  44629. * Unbinds the textures.
  44630. */
  44631. PBRBaseMaterial.prototype.unbind = function () {
  44632. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44633. this._uniformBuffer.setTexture("reflectionSampler", null);
  44634. }
  44635. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44636. this._uniformBuffer.setTexture("refractionSampler", null);
  44637. }
  44638. _super.prototype.unbind.call(this);
  44639. };
  44640. /**
  44641. * Binds the submesh data.
  44642. * @param world - The world matrix.
  44643. * @param mesh - The BJS mesh.
  44644. * @param subMesh - A submesh of the BJS mesh.
  44645. */
  44646. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44647. var scene = this.getScene();
  44648. var defines = subMesh._materialDefines;
  44649. if (!defines) {
  44650. return;
  44651. }
  44652. var effect = subMesh.effect;
  44653. if (!effect) {
  44654. return;
  44655. }
  44656. this._activeEffect = effect;
  44657. // Matrices
  44658. this.bindOnlyWorldMatrix(world);
  44659. // Normal Matrix
  44660. if (defines.OBJECTSPACE_NORMALMAP) {
  44661. world.toNormalMatrix(this._normalMatrix);
  44662. this.bindOnlyNormalMatrix(this._normalMatrix);
  44663. }
  44664. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44665. // Bones
  44666. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44667. var reflectionTexture = null;
  44668. if (mustRebind) {
  44669. this._uniformBuffer.bindToEffect(effect, "Material");
  44670. this.bindViewProjection(effect);
  44671. reflectionTexture = this._getReflectionTexture();
  44672. var refractionTexture = this._getRefractionTexture();
  44673. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44674. // Texture uniforms
  44675. if (scene.texturesEnabled) {
  44676. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44677. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44678. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44679. }
  44680. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44681. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44682. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44683. }
  44684. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44685. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44686. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44687. }
  44688. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44689. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44690. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44691. if (reflectionTexture.boundingBoxSize) {
  44692. var cubeTexture = reflectionTexture;
  44693. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44694. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44695. }
  44696. var polynomials = reflectionTexture.sphericalPolynomial;
  44697. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44698. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44699. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44700. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44701. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44702. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44703. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44704. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44705. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44706. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44707. }
  44708. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44709. }
  44710. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44711. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44712. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44713. }
  44714. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44715. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44716. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44717. }
  44718. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44719. if (this._metallicTexture) {
  44720. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44721. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44722. }
  44723. else if (this._reflectivityTexture) {
  44724. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44725. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44726. }
  44727. if (this._microSurfaceTexture) {
  44728. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44729. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44730. }
  44731. }
  44732. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44733. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44734. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44735. if (scene._mirroredCameraPosition) {
  44736. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44737. }
  44738. else {
  44739. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44740. }
  44741. }
  44742. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44743. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44744. var depth = 1.0;
  44745. if (!refractionTexture.isCube) {
  44746. if (refractionTexture.depth) {
  44747. depth = refractionTexture.depth;
  44748. }
  44749. }
  44750. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44751. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44752. }
  44753. }
  44754. // Point size
  44755. if (this.pointsCloud) {
  44756. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44757. }
  44758. // Colors
  44759. if (defines.METALLICWORKFLOW) {
  44760. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44761. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44762. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44763. }
  44764. else {
  44765. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44766. }
  44767. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44768. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44769. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44770. // Misc
  44771. this._lightingInfos.x = this._directIntensity;
  44772. this._lightingInfos.y = this._emissiveIntensity;
  44773. this._lightingInfos.z = this._environmentIntensity;
  44774. this._lightingInfos.w = this._specularIntensity;
  44775. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44776. }
  44777. // Textures
  44778. if (scene.texturesEnabled) {
  44779. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44780. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44781. }
  44782. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44783. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44784. }
  44785. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44786. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44787. }
  44788. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44789. if (defines.LODBASEDMICROSFURACE) {
  44790. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44791. }
  44792. else {
  44793. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44794. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44795. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44796. }
  44797. }
  44798. if (defines.ENVIRONMENTBRDF) {
  44799. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44800. }
  44801. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44802. if (defines.LODBASEDMICROSFURACE) {
  44803. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44804. }
  44805. else {
  44806. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44807. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44808. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44809. }
  44810. }
  44811. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44812. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44813. }
  44814. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44815. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44816. }
  44817. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44818. if (this._metallicTexture) {
  44819. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44820. }
  44821. else if (this._reflectivityTexture) {
  44822. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44823. }
  44824. if (this._microSurfaceTexture) {
  44825. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44826. }
  44827. }
  44828. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44829. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44830. }
  44831. }
  44832. // Clip plane
  44833. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44834. // Colors
  44835. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44836. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44837. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44838. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44839. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44840. }
  44841. if (mustRebind || !this.isFrozen) {
  44842. // Lights
  44843. if (scene.lightsEnabled && !this._disableLighting) {
  44844. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44845. }
  44846. // View
  44847. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44848. this.bindView(effect);
  44849. }
  44850. // Fog
  44851. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  44852. // Morph targets
  44853. if (defines.NUM_MORPH_INFLUENCERS) {
  44854. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44855. }
  44856. // image processing
  44857. this._imageProcessingConfiguration.bind(this._activeEffect);
  44858. // Log. depth
  44859. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44860. }
  44861. this._uniformBuffer.update();
  44862. this._afterBind(mesh, this._activeEffect);
  44863. };
  44864. /**
  44865. * Returns the animatable textures.
  44866. * @returns - Array of animatable textures.
  44867. */
  44868. PBRBaseMaterial.prototype.getAnimatables = function () {
  44869. var results = [];
  44870. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44871. results.push(this._albedoTexture);
  44872. }
  44873. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44874. results.push(this._ambientTexture);
  44875. }
  44876. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44877. results.push(this._opacityTexture);
  44878. }
  44879. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44880. results.push(this._reflectionTexture);
  44881. }
  44882. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44883. results.push(this._emissiveTexture);
  44884. }
  44885. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44886. results.push(this._metallicTexture);
  44887. }
  44888. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44889. results.push(this._reflectivityTexture);
  44890. }
  44891. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44892. results.push(this._bumpTexture);
  44893. }
  44894. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44895. results.push(this._lightmapTexture);
  44896. }
  44897. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44898. results.push(this._refractionTexture);
  44899. }
  44900. return results;
  44901. };
  44902. /**
  44903. * Returns the texture used for reflections.
  44904. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44905. */
  44906. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44907. if (this._reflectionTexture) {
  44908. return this._reflectionTexture;
  44909. }
  44910. return this.getScene().environmentTexture;
  44911. };
  44912. /**
  44913. * Returns the texture used for refraction or null if none is used.
  44914. * @returns - Refection texture if present. If no refraction texture and refraction
  44915. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44916. */
  44917. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44918. if (this._refractionTexture) {
  44919. return this._refractionTexture;
  44920. }
  44921. if (this._linkRefractionWithTransparency) {
  44922. return this.getScene().environmentTexture;
  44923. }
  44924. return null;
  44925. };
  44926. /**
  44927. * Disposes the resources of the material.
  44928. * @param forceDisposeEffect - Forces the disposal of effects.
  44929. * @param forceDisposeTextures - Forces the disposal of all textures.
  44930. */
  44931. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44932. if (forceDisposeTextures) {
  44933. if (this._albedoTexture) {
  44934. this._albedoTexture.dispose();
  44935. }
  44936. if (this._ambientTexture) {
  44937. this._ambientTexture.dispose();
  44938. }
  44939. if (this._opacityTexture) {
  44940. this._opacityTexture.dispose();
  44941. }
  44942. if (this._reflectionTexture) {
  44943. this._reflectionTexture.dispose();
  44944. }
  44945. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44946. this._environmentBRDFTexture.dispose();
  44947. }
  44948. if (this._emissiveTexture) {
  44949. this._emissiveTexture.dispose();
  44950. }
  44951. if (this._metallicTexture) {
  44952. this._metallicTexture.dispose();
  44953. }
  44954. if (this._reflectivityTexture) {
  44955. this._reflectivityTexture.dispose();
  44956. }
  44957. if (this._bumpTexture) {
  44958. this._bumpTexture.dispose();
  44959. }
  44960. if (this._lightmapTexture) {
  44961. this._lightmapTexture.dispose();
  44962. }
  44963. if (this._refractionTexture) {
  44964. this._refractionTexture.dispose();
  44965. }
  44966. }
  44967. this._renderTargets.dispose();
  44968. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44969. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44970. }
  44971. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44972. };
  44973. /**
  44974. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44975. */
  44976. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44977. /**
  44978. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44979. * to enhance interoperability with other engines.
  44980. */
  44981. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44982. /**
  44983. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44984. * to enhance interoperability with other materials.
  44985. */
  44986. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44987. /**
  44988. * Stores the reflectivity values based on metallic roughness workflow.
  44989. */
  44990. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44991. __decorate([
  44992. BABYLON.serializeAsImageProcessingConfiguration()
  44993. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44994. __decorate([
  44995. BABYLON.serialize()
  44996. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44997. __decorate([
  44998. BABYLON.serialize()
  44999. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45000. return PBRBaseMaterial;
  45001. }(BABYLON.PushMaterial));
  45002. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45003. })(BABYLON || (BABYLON = {}));
  45004. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45005. var BABYLON;
  45006. (function (BABYLON) {
  45007. /**
  45008. * The Physically based simple base material of BJS.
  45009. *
  45010. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45011. * It is used as the base class for both the specGloss and metalRough conventions.
  45012. */
  45013. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45014. __extends(PBRBaseSimpleMaterial, _super);
  45015. /**
  45016. * Instantiates a new PBRMaterial instance.
  45017. *
  45018. * @param name The material name
  45019. * @param scene The scene the material will be use in.
  45020. */
  45021. function PBRBaseSimpleMaterial(name, scene) {
  45022. var _this = _super.call(this, name, scene) || this;
  45023. /**
  45024. * Number of Simultaneous lights allowed on the material.
  45025. */
  45026. _this.maxSimultaneousLights = 4;
  45027. /**
  45028. * If sets to true, disables all the lights affecting the material.
  45029. */
  45030. _this.disableLighting = false;
  45031. /**
  45032. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45033. */
  45034. _this.invertNormalMapX = false;
  45035. /**
  45036. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45037. */
  45038. _this.invertNormalMapY = false;
  45039. /**
  45040. * Emissivie color used to self-illuminate the model.
  45041. */
  45042. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45043. /**
  45044. * Occlusion Channel Strenght.
  45045. */
  45046. _this.occlusionStrength = 1.0;
  45047. _this.useLightmapAsShadowmap = false;
  45048. _this._useAlphaFromAlbedoTexture = true;
  45049. _this._useAmbientInGrayScale = true;
  45050. return _this;
  45051. }
  45052. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45053. /**
  45054. * Gets the current double sided mode.
  45055. */
  45056. get: function () {
  45057. return this._twoSidedLighting;
  45058. },
  45059. /**
  45060. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45061. */
  45062. set: function (value) {
  45063. if (this._twoSidedLighting === value) {
  45064. return;
  45065. }
  45066. this._twoSidedLighting = value;
  45067. this.backFaceCulling = !value;
  45068. this._markAllSubMeshesAsTexturesDirty();
  45069. },
  45070. enumerable: true,
  45071. configurable: true
  45072. });
  45073. /**
  45074. * Return the active textures of the material.
  45075. */
  45076. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45077. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45078. if (this.environmentTexture) {
  45079. activeTextures.push(this.environmentTexture);
  45080. }
  45081. if (this.normalTexture) {
  45082. activeTextures.push(this.normalTexture);
  45083. }
  45084. if (this.emissiveTexture) {
  45085. activeTextures.push(this.emissiveTexture);
  45086. }
  45087. if (this.occlusionTexture) {
  45088. activeTextures.push(this.occlusionTexture);
  45089. }
  45090. if (this.lightmapTexture) {
  45091. activeTextures.push(this.lightmapTexture);
  45092. }
  45093. return activeTextures;
  45094. };
  45095. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45096. if (_super.prototype.hasTexture.call(this, texture)) {
  45097. return true;
  45098. }
  45099. if (this.lightmapTexture === texture) {
  45100. return true;
  45101. }
  45102. return false;
  45103. };
  45104. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45105. return "PBRBaseSimpleMaterial";
  45106. };
  45107. __decorate([
  45108. BABYLON.serialize(),
  45109. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45110. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45111. __decorate([
  45112. BABYLON.serialize(),
  45113. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45114. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45115. __decorate([
  45116. BABYLON.serializeAsTexture(),
  45117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45118. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45119. __decorate([
  45120. BABYLON.serialize(),
  45121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45122. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45123. __decorate([
  45124. BABYLON.serialize(),
  45125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45126. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45127. __decorate([
  45128. BABYLON.serializeAsTexture(),
  45129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45130. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45131. __decorate([
  45132. BABYLON.serializeAsColor3("emissive"),
  45133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45134. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45135. __decorate([
  45136. BABYLON.serializeAsTexture(),
  45137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45138. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45139. __decorate([
  45140. BABYLON.serialize(),
  45141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45142. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45143. __decorate([
  45144. BABYLON.serializeAsTexture(),
  45145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45146. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45147. __decorate([
  45148. BABYLON.serialize(),
  45149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45150. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45151. __decorate([
  45152. BABYLON.serialize()
  45153. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45154. __decorate([
  45155. BABYLON.serializeAsTexture(),
  45156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45157. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45158. __decorate([
  45159. BABYLON.serialize(),
  45160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45161. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45162. return PBRBaseSimpleMaterial;
  45163. }(BABYLON.PBRBaseMaterial));
  45164. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45165. })(BABYLON || (BABYLON = {}));
  45166. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45167. var BABYLON;
  45168. (function (BABYLON) {
  45169. /**
  45170. * The Physically based material of BJS.
  45171. *
  45172. * This offers the main features of a standard PBR material.
  45173. * For more information, please refer to the documentation :
  45174. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45175. */
  45176. var PBRMaterial = /** @class */ (function (_super) {
  45177. __extends(PBRMaterial, _super);
  45178. /**
  45179. * Instantiates a new PBRMaterial instance.
  45180. *
  45181. * @param name The material name
  45182. * @param scene The scene the material will be use in.
  45183. */
  45184. function PBRMaterial(name, scene) {
  45185. var _this = _super.call(this, name, scene) || this;
  45186. /**
  45187. * Intensity of the direct lights e.g. the four lights available in your scene.
  45188. * This impacts both the direct diffuse and specular highlights.
  45189. */
  45190. _this.directIntensity = 1.0;
  45191. /**
  45192. * Intensity of the emissive part of the material.
  45193. * This helps controlling the emissive effect without modifying the emissive color.
  45194. */
  45195. _this.emissiveIntensity = 1.0;
  45196. /**
  45197. * Intensity of the environment e.g. how much the environment will light the object
  45198. * either through harmonics for rough material or through the refelction for shiny ones.
  45199. */
  45200. _this.environmentIntensity = 1.0;
  45201. /**
  45202. * This is a special control allowing the reduction of the specular highlights coming from the
  45203. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45204. */
  45205. _this.specularIntensity = 1.0;
  45206. /**
  45207. * Debug Control allowing disabling the bump map on this material.
  45208. */
  45209. _this.disableBumpMap = false;
  45210. /**
  45211. * AKA Occlusion Texture Intensity in other nomenclature.
  45212. */
  45213. _this.ambientTextureStrength = 1.0;
  45214. /**
  45215. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45216. * 1 means it completely occludes it
  45217. * 0 mean it has no impact
  45218. */
  45219. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45220. /**
  45221. * The color of a material in ambient lighting.
  45222. */
  45223. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45224. /**
  45225. * AKA Diffuse Color in other nomenclature.
  45226. */
  45227. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45228. /**
  45229. * AKA Specular Color in other nomenclature.
  45230. */
  45231. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45232. /**
  45233. * The color reflected from the material.
  45234. */
  45235. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45236. /**
  45237. * The color emitted from the material.
  45238. */
  45239. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45240. /**
  45241. * AKA Glossiness in other nomenclature.
  45242. */
  45243. _this.microSurface = 1.0;
  45244. /**
  45245. * source material index of refraction (IOR)' / 'destination material IOR.
  45246. */
  45247. _this.indexOfRefraction = 0.66;
  45248. /**
  45249. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45250. */
  45251. _this.invertRefractionY = false;
  45252. /**
  45253. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45254. * Materials half opaque for instance using refraction could benefit from this control.
  45255. */
  45256. _this.linkRefractionWithTransparency = false;
  45257. _this.useLightmapAsShadowmap = false;
  45258. /**
  45259. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45260. */
  45261. _this.useAlphaFromAlbedoTexture = false;
  45262. /**
  45263. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45264. */
  45265. _this.forceAlphaTest = false;
  45266. /**
  45267. * Defines the alpha limits in alpha test mode.
  45268. */
  45269. _this.alphaCutOff = 0.4;
  45270. /**
  45271. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45272. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45273. */
  45274. _this.useSpecularOverAlpha = true;
  45275. /**
  45276. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45277. */
  45278. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45279. /**
  45280. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45281. */
  45282. _this.useRoughnessFromMetallicTextureAlpha = true;
  45283. /**
  45284. * Specifies if the metallic texture contains the roughness information in its green channel.
  45285. */
  45286. _this.useRoughnessFromMetallicTextureGreen = false;
  45287. /**
  45288. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45289. */
  45290. _this.useMetallnessFromMetallicTextureBlue = false;
  45291. /**
  45292. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45293. */
  45294. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45295. /**
  45296. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45297. */
  45298. _this.useAmbientInGrayScale = false;
  45299. /**
  45300. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45301. * The material will try to infer what glossiness each pixel should be.
  45302. */
  45303. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45304. /**
  45305. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45306. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45307. */
  45308. _this.useRadianceOverAlpha = true;
  45309. /**
  45310. * Allows using an object space normal map (instead of tangent space).
  45311. */
  45312. _this.useObjectSpaceNormalMap = false;
  45313. /**
  45314. * Allows using the bump map in parallax mode.
  45315. */
  45316. _this.useParallax = false;
  45317. /**
  45318. * Allows using the bump map in parallax occlusion mode.
  45319. */
  45320. _this.useParallaxOcclusion = false;
  45321. /**
  45322. * Controls the scale bias of the parallax mode.
  45323. */
  45324. _this.parallaxScaleBias = 0.05;
  45325. /**
  45326. * If sets to true, disables all the lights affecting the material.
  45327. */
  45328. _this.disableLighting = false;
  45329. /**
  45330. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45331. */
  45332. _this.forceIrradianceInFragment = false;
  45333. /**
  45334. * Number of Simultaneous lights allowed on the material.
  45335. */
  45336. _this.maxSimultaneousLights = 4;
  45337. /**
  45338. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45339. */
  45340. _this.invertNormalMapX = false;
  45341. /**
  45342. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45343. */
  45344. _this.invertNormalMapY = false;
  45345. /**
  45346. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45347. */
  45348. _this.twoSidedLighting = false;
  45349. /**
  45350. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45351. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45352. */
  45353. _this.useAlphaFresnel = false;
  45354. /**
  45355. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45356. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45357. */
  45358. _this.useLinearAlphaFresnel = false;
  45359. /**
  45360. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45361. * And/Or occlude the blended part.
  45362. */
  45363. _this.environmentBRDFTexture = null;
  45364. /**
  45365. * Force normal to face away from face.
  45366. */
  45367. _this.forceNormalForward = false;
  45368. /**
  45369. * Enables specular anti aliasing in the PBR shader.
  45370. * It will both interacts on the Geometry for analytical and IBL lighting.
  45371. * It also prefilter the roughness map based on the bump values.
  45372. */
  45373. _this.enableSpecularAntiAliasing = false;
  45374. /**
  45375. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45376. * makes the reflect vector face the model (under horizon).
  45377. */
  45378. _this.useHorizonOcclusion = true;
  45379. /**
  45380. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45381. * too much the area relying on ambient texture to define their ambient occlusion.
  45382. */
  45383. _this.useRadianceOcclusion = true;
  45384. /**
  45385. * If set to true, no lighting calculations will be applied.
  45386. */
  45387. _this.unlit = false;
  45388. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45389. return _this;
  45390. }
  45391. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45392. /**
  45393. * BJS is using an harcoded light falloff based on a manually sets up range.
  45394. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45395. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45396. */
  45397. get: function () {
  45398. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45399. },
  45400. /**
  45401. * BJS is using an harcoded light falloff based on a manually sets up range.
  45402. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45403. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45404. */
  45405. set: function (value) {
  45406. if (value !== this.usePhysicalLightFalloff) {
  45407. // Ensure the effect will be rebuilt.
  45408. this._markAllSubMeshesAsTexturesDirty();
  45409. if (value) {
  45410. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45411. }
  45412. else {
  45413. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45414. }
  45415. }
  45416. },
  45417. enumerable: true,
  45418. configurable: true
  45419. });
  45420. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45421. /**
  45422. * In order to support the falloff compatibility with gltf, a special mode has been added
  45423. * to reproduce the gltf light falloff.
  45424. */
  45425. get: function () {
  45426. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45427. },
  45428. /**
  45429. * In order to support the falloff compatibility with gltf, a special mode has been added
  45430. * to reproduce the gltf light falloff.
  45431. */
  45432. set: function (value) {
  45433. if (value !== this.useGLTFLightFalloff) {
  45434. // Ensure the effect will be rebuilt.
  45435. this._markAllSubMeshesAsTexturesDirty();
  45436. if (value) {
  45437. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45438. }
  45439. else {
  45440. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45441. }
  45442. }
  45443. },
  45444. enumerable: true,
  45445. configurable: true
  45446. });
  45447. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45448. /**
  45449. * Gets the image processing configuration used either in this material.
  45450. */
  45451. get: function () {
  45452. return this._imageProcessingConfiguration;
  45453. },
  45454. /**
  45455. * Sets the Default image processing configuration used either in the this material.
  45456. *
  45457. * If sets to null, the scene one is in use.
  45458. */
  45459. set: function (value) {
  45460. this._attachImageProcessingConfiguration(value);
  45461. // Ensure the effect will be rebuilt.
  45462. this._markAllSubMeshesAsTexturesDirty();
  45463. },
  45464. enumerable: true,
  45465. configurable: true
  45466. });
  45467. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45468. /**
  45469. * Gets wether the color curves effect is enabled.
  45470. */
  45471. get: function () {
  45472. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45473. },
  45474. /**
  45475. * Sets wether the color curves effect is enabled.
  45476. */
  45477. set: function (value) {
  45478. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45479. },
  45480. enumerable: true,
  45481. configurable: true
  45482. });
  45483. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45484. /**
  45485. * Gets wether the color grading effect is enabled.
  45486. */
  45487. get: function () {
  45488. return this.imageProcessingConfiguration.colorGradingEnabled;
  45489. },
  45490. /**
  45491. * Gets wether the color grading effect is enabled.
  45492. */
  45493. set: function (value) {
  45494. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45495. },
  45496. enumerable: true,
  45497. configurable: true
  45498. });
  45499. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45500. /**
  45501. * Gets wether tonemapping is enabled or not.
  45502. */
  45503. get: function () {
  45504. return this._imageProcessingConfiguration.toneMappingEnabled;
  45505. },
  45506. /**
  45507. * Sets wether tonemapping is enabled or not
  45508. */
  45509. set: function (value) {
  45510. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45511. },
  45512. enumerable: true,
  45513. configurable: true
  45514. });
  45515. ;
  45516. ;
  45517. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45518. /**
  45519. * The camera exposure used on this material.
  45520. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45521. * This corresponds to a photographic exposure.
  45522. */
  45523. get: function () {
  45524. return this._imageProcessingConfiguration.exposure;
  45525. },
  45526. /**
  45527. * The camera exposure used on this material.
  45528. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45529. * This corresponds to a photographic exposure.
  45530. */
  45531. set: function (value) {
  45532. this._imageProcessingConfiguration.exposure = value;
  45533. },
  45534. enumerable: true,
  45535. configurable: true
  45536. });
  45537. ;
  45538. ;
  45539. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45540. /**
  45541. * Gets The camera contrast used on this material.
  45542. */
  45543. get: function () {
  45544. return this._imageProcessingConfiguration.contrast;
  45545. },
  45546. /**
  45547. * Sets The camera contrast used on this material.
  45548. */
  45549. set: function (value) {
  45550. this._imageProcessingConfiguration.contrast = value;
  45551. },
  45552. enumerable: true,
  45553. configurable: true
  45554. });
  45555. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45556. /**
  45557. * Gets the Color Grading 2D Lookup Texture.
  45558. */
  45559. get: function () {
  45560. return this._imageProcessingConfiguration.colorGradingTexture;
  45561. },
  45562. /**
  45563. * Sets the Color Grading 2D Lookup Texture.
  45564. */
  45565. set: function (value) {
  45566. this._imageProcessingConfiguration.colorGradingTexture = value;
  45567. },
  45568. enumerable: true,
  45569. configurable: true
  45570. });
  45571. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45572. /**
  45573. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45574. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45575. * 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;
  45576. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45577. */
  45578. get: function () {
  45579. return this._imageProcessingConfiguration.colorCurves;
  45580. },
  45581. /**
  45582. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45583. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45584. * 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;
  45585. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45586. */
  45587. set: function (value) {
  45588. this._imageProcessingConfiguration.colorCurves = value;
  45589. },
  45590. enumerable: true,
  45591. configurable: true
  45592. });
  45593. /**
  45594. * Returns the name of this material class.
  45595. */
  45596. PBRMaterial.prototype.getClassName = function () {
  45597. return "PBRMaterial";
  45598. };
  45599. /**
  45600. * Returns an array of the actively used textures.
  45601. * @returns - Array of BaseTextures
  45602. */
  45603. PBRMaterial.prototype.getActiveTextures = function () {
  45604. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45605. if (this._albedoTexture) {
  45606. activeTextures.push(this._albedoTexture);
  45607. }
  45608. if (this._ambientTexture) {
  45609. activeTextures.push(this._ambientTexture);
  45610. }
  45611. if (this._opacityTexture) {
  45612. activeTextures.push(this._opacityTexture);
  45613. }
  45614. if (this._reflectionTexture) {
  45615. activeTextures.push(this._reflectionTexture);
  45616. }
  45617. if (this._emissiveTexture) {
  45618. activeTextures.push(this._emissiveTexture);
  45619. }
  45620. if (this._reflectivityTexture) {
  45621. activeTextures.push(this._reflectivityTexture);
  45622. }
  45623. if (this._metallicTexture) {
  45624. activeTextures.push(this._metallicTexture);
  45625. }
  45626. if (this._microSurfaceTexture) {
  45627. activeTextures.push(this._microSurfaceTexture);
  45628. }
  45629. if (this._bumpTexture) {
  45630. activeTextures.push(this._bumpTexture);
  45631. }
  45632. if (this._lightmapTexture) {
  45633. activeTextures.push(this._lightmapTexture);
  45634. }
  45635. if (this._refractionTexture) {
  45636. activeTextures.push(this._refractionTexture);
  45637. }
  45638. return activeTextures;
  45639. };
  45640. /**
  45641. * Checks to see if a texture is used in the material.
  45642. * @param texture - Base texture to use.
  45643. * @returns - Boolean specifying if a texture is used in the material.
  45644. */
  45645. PBRMaterial.prototype.hasTexture = function (texture) {
  45646. if (_super.prototype.hasTexture.call(this, texture)) {
  45647. return true;
  45648. }
  45649. if (this._albedoTexture === texture) {
  45650. return true;
  45651. }
  45652. if (this._ambientTexture === texture) {
  45653. return true;
  45654. }
  45655. if (this._opacityTexture === texture) {
  45656. return true;
  45657. }
  45658. if (this._reflectionTexture === texture) {
  45659. return true;
  45660. }
  45661. if (this._reflectivityTexture === texture) {
  45662. return true;
  45663. }
  45664. if (this._metallicTexture === texture) {
  45665. return true;
  45666. }
  45667. if (this._microSurfaceTexture === texture) {
  45668. return true;
  45669. }
  45670. if (this._bumpTexture === texture) {
  45671. return true;
  45672. }
  45673. if (this._lightmapTexture === texture) {
  45674. return true;
  45675. }
  45676. if (this._refractionTexture === texture) {
  45677. return true;
  45678. }
  45679. return false;
  45680. };
  45681. /**
  45682. * Makes a duplicate of the current material.
  45683. * @param name - name to use for the new material.
  45684. */
  45685. PBRMaterial.prototype.clone = function (name) {
  45686. var _this = this;
  45687. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45688. clone.id = name;
  45689. clone.name = name;
  45690. return clone;
  45691. };
  45692. /**
  45693. * Serializes this PBR Material.
  45694. * @returns - An object with the serialized material.
  45695. */
  45696. PBRMaterial.prototype.serialize = function () {
  45697. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45698. serializationObject.customType = "BABYLON.PBRMaterial";
  45699. return serializationObject;
  45700. };
  45701. // Statics
  45702. /**
  45703. * Parses a PBR Material from a serialized object.
  45704. * @param source - Serialized object.
  45705. * @param scene - BJS scene instance.
  45706. * @param rootUrl - url for the scene object
  45707. * @returns - PBRMaterial
  45708. */
  45709. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45710. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45711. };
  45712. /**
  45713. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45714. */
  45715. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45716. /**
  45717. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45718. */
  45719. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45720. /**
  45721. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45722. */
  45723. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45724. /**
  45725. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45726. * They are also discarded below the alpha cutoff threshold to improve performances.
  45727. */
  45728. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45729. /**
  45730. * Defines the default value of how much AO map is occluding the analytical lights
  45731. * (point spot...).
  45732. */
  45733. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45734. __decorate([
  45735. BABYLON.serialize(),
  45736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45737. ], PBRMaterial.prototype, "directIntensity", void 0);
  45738. __decorate([
  45739. BABYLON.serialize(),
  45740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45741. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45742. __decorate([
  45743. BABYLON.serialize(),
  45744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45745. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45746. __decorate([
  45747. BABYLON.serialize(),
  45748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45749. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45750. __decorate([
  45751. BABYLON.serialize(),
  45752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45753. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45754. __decorate([
  45755. BABYLON.serializeAsTexture(),
  45756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45757. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45758. __decorate([
  45759. BABYLON.serializeAsTexture(),
  45760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45761. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45762. __decorate([
  45763. BABYLON.serialize(),
  45764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45765. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45766. __decorate([
  45767. BABYLON.serialize(),
  45768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45769. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45770. __decorate([
  45771. BABYLON.serializeAsTexture(),
  45772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45773. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45774. __decorate([
  45775. BABYLON.serializeAsTexture(),
  45776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45777. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45778. __decorate([
  45779. BABYLON.serializeAsTexture(),
  45780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45781. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45782. __decorate([
  45783. BABYLON.serializeAsTexture(),
  45784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45785. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45786. __decorate([
  45787. BABYLON.serializeAsTexture(),
  45788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45789. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45790. __decorate([
  45791. BABYLON.serialize(),
  45792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45793. ], PBRMaterial.prototype, "metallic", void 0);
  45794. __decorate([
  45795. BABYLON.serialize(),
  45796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45797. ], PBRMaterial.prototype, "roughness", void 0);
  45798. __decorate([
  45799. BABYLON.serializeAsTexture(),
  45800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45801. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45802. __decorate([
  45803. BABYLON.serializeAsTexture(),
  45804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45805. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45806. __decorate([
  45807. BABYLON.serializeAsTexture(),
  45808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45809. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45810. __decorate([
  45811. BABYLON.serializeAsTexture(),
  45812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45813. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45814. __decorate([
  45815. BABYLON.serializeAsColor3("ambient"),
  45816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45817. ], PBRMaterial.prototype, "ambientColor", void 0);
  45818. __decorate([
  45819. BABYLON.serializeAsColor3("albedo"),
  45820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45821. ], PBRMaterial.prototype, "albedoColor", void 0);
  45822. __decorate([
  45823. BABYLON.serializeAsColor3("reflectivity"),
  45824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45825. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45826. __decorate([
  45827. BABYLON.serializeAsColor3("reflection"),
  45828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45829. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45830. __decorate([
  45831. BABYLON.serializeAsColor3("emissive"),
  45832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45833. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45834. __decorate([
  45835. BABYLON.serialize(),
  45836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45837. ], PBRMaterial.prototype, "microSurface", void 0);
  45838. __decorate([
  45839. BABYLON.serialize(),
  45840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45841. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45842. __decorate([
  45843. BABYLON.serialize(),
  45844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45845. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45846. __decorate([
  45847. BABYLON.serialize(),
  45848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45849. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45850. __decorate([
  45851. BABYLON.serialize(),
  45852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45853. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45854. __decorate([
  45855. BABYLON.serialize(),
  45856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45857. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45858. __decorate([
  45859. BABYLON.serialize(),
  45860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45861. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45862. __decorate([
  45863. BABYLON.serialize(),
  45864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45865. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45866. __decorate([
  45867. BABYLON.serialize(),
  45868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45869. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45870. __decorate([
  45871. BABYLON.serialize(),
  45872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45873. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45874. __decorate([
  45875. BABYLON.serialize(),
  45876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45877. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45878. __decorate([
  45879. BABYLON.serialize(),
  45880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45881. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45882. __decorate([
  45883. BABYLON.serialize(),
  45884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45885. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45886. __decorate([
  45887. BABYLON.serialize(),
  45888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45889. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45890. __decorate([
  45891. BABYLON.serialize(),
  45892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45893. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45894. __decorate([
  45895. BABYLON.serialize(),
  45896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45897. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45898. __decorate([
  45899. BABYLON.serialize()
  45900. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45901. __decorate([
  45902. BABYLON.serialize()
  45903. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45904. __decorate([
  45905. BABYLON.serialize(),
  45906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45907. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45908. __decorate([
  45909. BABYLON.serialize(),
  45910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45911. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45912. __decorate([
  45913. BABYLON.serialize(),
  45914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45915. ], PBRMaterial.prototype, "useParallax", void 0);
  45916. __decorate([
  45917. BABYLON.serialize(),
  45918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45919. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45920. __decorate([
  45921. BABYLON.serialize(),
  45922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45923. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45924. __decorate([
  45925. BABYLON.serialize(),
  45926. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45927. ], PBRMaterial.prototype, "disableLighting", void 0);
  45928. __decorate([
  45929. BABYLON.serialize(),
  45930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45931. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45932. __decorate([
  45933. BABYLON.serialize(),
  45934. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45935. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45936. __decorate([
  45937. BABYLON.serialize(),
  45938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45939. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45940. __decorate([
  45941. BABYLON.serialize(),
  45942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45943. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45944. __decorate([
  45945. BABYLON.serialize(),
  45946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45947. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45948. __decorate([
  45949. BABYLON.serialize(),
  45950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45951. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45952. __decorate([
  45953. BABYLON.serialize(),
  45954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45955. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45956. __decorate([
  45957. BABYLON.serializeAsTexture(),
  45958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45959. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45960. __decorate([
  45961. BABYLON.serialize(),
  45962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45963. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45964. __decorate([
  45965. BABYLON.serialize(),
  45966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45967. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45968. __decorate([
  45969. BABYLON.serialize(),
  45970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45971. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45972. __decorate([
  45973. BABYLON.serialize(),
  45974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45975. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45976. __decorate([
  45977. BABYLON.serialize(),
  45978. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45979. ], PBRMaterial.prototype, "unlit", void 0);
  45980. return PBRMaterial;
  45981. }(BABYLON.PBRBaseMaterial));
  45982. BABYLON.PBRMaterial = PBRMaterial;
  45983. })(BABYLON || (BABYLON = {}));
  45984. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45985. var BABYLON;
  45986. (function (BABYLON) {
  45987. /**
  45988. * The PBR material of BJS following the metal roughness convention.
  45989. *
  45990. * This fits to the PBR convention in the GLTF definition:
  45991. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45992. */
  45993. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45994. __extends(PBRMetallicRoughnessMaterial, _super);
  45995. /**
  45996. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45997. *
  45998. * @param name The material name
  45999. * @param scene The scene the material will be use in.
  46000. */
  46001. function PBRMetallicRoughnessMaterial(name, scene) {
  46002. var _this = _super.call(this, name, scene) || this;
  46003. _this._useRoughnessFromMetallicTextureAlpha = false;
  46004. _this._useRoughnessFromMetallicTextureGreen = true;
  46005. _this._useMetallnessFromMetallicTextureBlue = true;
  46006. _this.metallic = 1.0;
  46007. _this.roughness = 1.0;
  46008. return _this;
  46009. }
  46010. /**
  46011. * Return the currrent class name of the material.
  46012. */
  46013. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46014. return "PBRMetallicRoughnessMaterial";
  46015. };
  46016. /**
  46017. * Return the active textures of the material.
  46018. */
  46019. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46020. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46021. if (this.baseTexture) {
  46022. activeTextures.push(this.baseTexture);
  46023. }
  46024. if (this.metallicRoughnessTexture) {
  46025. activeTextures.push(this.metallicRoughnessTexture);
  46026. }
  46027. return activeTextures;
  46028. };
  46029. /**
  46030. * Checks to see if a texture is used in the material.
  46031. * @param texture - Base texture to use.
  46032. * @returns - Boolean specifying if a texture is used in the material.
  46033. */
  46034. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46035. if (_super.prototype.hasTexture.call(this, texture)) {
  46036. return true;
  46037. }
  46038. if (this.baseTexture === texture) {
  46039. return true;
  46040. }
  46041. if (this.metallicRoughnessTexture === texture) {
  46042. return true;
  46043. }
  46044. return false;
  46045. };
  46046. /**
  46047. * Makes a duplicate of the current material.
  46048. * @param name - name to use for the new material.
  46049. */
  46050. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46051. var _this = this;
  46052. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46053. clone.id = name;
  46054. clone.name = name;
  46055. return clone;
  46056. };
  46057. /**
  46058. * Serialize the material to a parsable JSON object.
  46059. */
  46060. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46061. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46062. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46063. return serializationObject;
  46064. };
  46065. /**
  46066. * Parses a JSON object correponding to the serialize function.
  46067. */
  46068. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46069. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46070. };
  46071. __decorate([
  46072. BABYLON.serializeAsColor3(),
  46073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46074. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46075. __decorate([
  46076. BABYLON.serializeAsTexture(),
  46077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46078. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46079. __decorate([
  46080. BABYLON.serialize(),
  46081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46082. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46083. __decorate([
  46084. BABYLON.serialize(),
  46085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46086. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46087. __decorate([
  46088. BABYLON.serializeAsTexture(),
  46089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46090. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46091. return PBRMetallicRoughnessMaterial;
  46092. }(BABYLON.PBRBaseSimpleMaterial));
  46093. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46094. })(BABYLON || (BABYLON = {}));
  46095. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46096. var BABYLON;
  46097. (function (BABYLON) {
  46098. /**
  46099. * The PBR material of BJS following the specular glossiness convention.
  46100. *
  46101. * This fits to the PBR convention in the GLTF definition:
  46102. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46103. */
  46104. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46105. __extends(PBRSpecularGlossinessMaterial, _super);
  46106. /**
  46107. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46108. *
  46109. * @param name The material name
  46110. * @param scene The scene the material will be use in.
  46111. */
  46112. function PBRSpecularGlossinessMaterial(name, scene) {
  46113. var _this = _super.call(this, name, scene) || this;
  46114. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46115. return _this;
  46116. }
  46117. /**
  46118. * Return the currrent class name of the material.
  46119. */
  46120. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46121. return "PBRSpecularGlossinessMaterial";
  46122. };
  46123. /**
  46124. * Return the active textures of the material.
  46125. */
  46126. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46127. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46128. if (this.diffuseTexture) {
  46129. activeTextures.push(this.diffuseTexture);
  46130. }
  46131. if (this.specularGlossinessTexture) {
  46132. activeTextures.push(this.specularGlossinessTexture);
  46133. }
  46134. return activeTextures;
  46135. };
  46136. /**
  46137. * Checks to see if a texture is used in the material.
  46138. * @param texture - Base texture to use.
  46139. * @returns - Boolean specifying if a texture is used in the material.
  46140. */
  46141. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46142. if (_super.prototype.hasTexture.call(this, texture)) {
  46143. return true;
  46144. }
  46145. if (this.diffuseTexture === texture) {
  46146. return true;
  46147. }
  46148. if (this.specularGlossinessTexture === texture) {
  46149. return true;
  46150. }
  46151. return false;
  46152. };
  46153. /**
  46154. * Makes a duplicate of the current material.
  46155. * @param name - name to use for the new material.
  46156. */
  46157. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46158. var _this = this;
  46159. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46160. clone.id = name;
  46161. clone.name = name;
  46162. return clone;
  46163. };
  46164. /**
  46165. * Serialize the material to a parsable JSON object.
  46166. */
  46167. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46168. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46169. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46170. return serializationObject;
  46171. };
  46172. /**
  46173. * Parses a JSON object correponding to the serialize function.
  46174. */
  46175. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46176. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46177. };
  46178. __decorate([
  46179. BABYLON.serializeAsColor3("diffuse"),
  46180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46181. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46182. __decorate([
  46183. BABYLON.serializeAsTexture(),
  46184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46185. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46186. __decorate([
  46187. BABYLON.serializeAsColor3("specular"),
  46188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46189. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46190. __decorate([
  46191. BABYLON.serialize(),
  46192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46193. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46194. __decorate([
  46195. BABYLON.serializeAsTexture(),
  46196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46197. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46198. return PBRSpecularGlossinessMaterial;
  46199. }(BABYLON.PBRBaseSimpleMaterial));
  46200. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46201. })(BABYLON || (BABYLON = {}));
  46202. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46203. var BABYLON;
  46204. (function (BABYLON) {
  46205. /**
  46206. * This is a list of all the different input types that are available in the application.
  46207. * Fo instance: ArcRotateCameraGamepadInput...
  46208. */
  46209. BABYLON.CameraInputTypes = {};
  46210. /**
  46211. * This represents the input manager used within a camera.
  46212. * It helps dealing with all the different kind of input attached to a camera.
  46213. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46214. */
  46215. var CameraInputsManager = /** @class */ (function () {
  46216. /**
  46217. * Instantiate a new Camera Input Manager.
  46218. * @param camera Defines the camera the input manager blongs to
  46219. */
  46220. function CameraInputsManager(camera) {
  46221. this.attached = {};
  46222. this.camera = camera;
  46223. this.checkInputs = function () { };
  46224. }
  46225. /**
  46226. * Add an input method to a camera
  46227. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46228. * @param input camera input method
  46229. */
  46230. CameraInputsManager.prototype.add = function (input) {
  46231. var type = input.getSimpleName();
  46232. if (this.attached[type]) {
  46233. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46234. return;
  46235. }
  46236. this.attached[type] = input;
  46237. input.camera = this.camera;
  46238. //for checkInputs, we are dynamically creating a function
  46239. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46240. if (input.checkInputs) {
  46241. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46242. }
  46243. if (this.attachedElement) {
  46244. input.attachControl(this.attachedElement);
  46245. }
  46246. };
  46247. /**
  46248. * Remove a specific input method from a camera
  46249. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46250. * @param inputToRemove camera input method
  46251. */
  46252. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46253. for (var cam in this.attached) {
  46254. var input = this.attached[cam];
  46255. if (input === inputToRemove) {
  46256. input.detachControl(this.attachedElement);
  46257. input.camera = null;
  46258. delete this.attached[cam];
  46259. this.rebuildInputCheck();
  46260. }
  46261. }
  46262. };
  46263. /**
  46264. * Remove a specific input type from a camera
  46265. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  46266. * @param inputType the type of the input to remove
  46267. */
  46268. CameraInputsManager.prototype.removeByType = function (inputType) {
  46269. for (var cam in this.attached) {
  46270. var input = this.attached[cam];
  46271. if (input.getClassName() === inputType) {
  46272. input.detachControl(this.attachedElement);
  46273. input.camera = null;
  46274. delete this.attached[cam];
  46275. this.rebuildInputCheck();
  46276. }
  46277. }
  46278. };
  46279. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46280. var current = this.checkInputs;
  46281. return function () {
  46282. current();
  46283. fn();
  46284. };
  46285. };
  46286. /**
  46287. * Attach the input controls to the currently attached dom element to listen the events from.
  46288. * @param input Defines the input to attach
  46289. */
  46290. CameraInputsManager.prototype.attachInput = function (input) {
  46291. if (this.attachedElement) {
  46292. input.attachControl(this.attachedElement, this.noPreventDefault);
  46293. }
  46294. };
  46295. /**
  46296. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  46297. * @param element Defines the dom element to collect the events from
  46298. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46299. */
  46300. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46301. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46302. if (this.attachedElement) {
  46303. return;
  46304. }
  46305. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46306. this.attachedElement = element;
  46307. this.noPreventDefault = noPreventDefault;
  46308. for (var cam in this.attached) {
  46309. this.attached[cam].attachControl(element, noPreventDefault);
  46310. }
  46311. };
  46312. /**
  46313. * Detach the current manager inputs controls from a specific dom element.
  46314. * @param element Defines the dom element to collect the events from
  46315. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  46316. */
  46317. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46318. if (disconnect === void 0) { disconnect = false; }
  46319. if (this.attachedElement !== element) {
  46320. return;
  46321. }
  46322. for (var cam in this.attached) {
  46323. this.attached[cam].detachControl(element);
  46324. if (disconnect) {
  46325. this.attached[cam].camera = null;
  46326. }
  46327. }
  46328. this.attachedElement = null;
  46329. };
  46330. /**
  46331. * Rebuild the dynamic inputCheck function from the current list of
  46332. * defined inputs in the manager.
  46333. */
  46334. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46335. this.checkInputs = function () { };
  46336. for (var cam in this.attached) {
  46337. var input = this.attached[cam];
  46338. if (input.checkInputs) {
  46339. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46340. }
  46341. }
  46342. };
  46343. /**
  46344. * Remove all attached input methods from a camera
  46345. */
  46346. CameraInputsManager.prototype.clear = function () {
  46347. if (this.attachedElement) {
  46348. this.detachElement(this.attachedElement, true);
  46349. }
  46350. this.attached = {};
  46351. this.attachedElement = null;
  46352. this.checkInputs = function () { };
  46353. };
  46354. /**
  46355. * Serialize the current input manager attached to a camera.
  46356. * This ensures than once parsed,
  46357. * the input associated to the camera will be identical to the current ones
  46358. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  46359. */
  46360. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46361. var inputs = {};
  46362. for (var cam in this.attached) {
  46363. var input = this.attached[cam];
  46364. var res = BABYLON.SerializationHelper.Serialize(input);
  46365. inputs[input.getClassName()] = res;
  46366. }
  46367. serializedCamera.inputsmgr = inputs;
  46368. };
  46369. /**
  46370. * Parses an input manager serialized JSON to restore the previous list of inputs
  46371. * and states associated to a camera.
  46372. * @param parsedCamera Defines the JSON to parse
  46373. */
  46374. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46375. var parsedInputs = parsedCamera.inputsmgr;
  46376. if (parsedInputs) {
  46377. this.clear();
  46378. for (var n in parsedInputs) {
  46379. var construct = BABYLON.CameraInputTypes[n];
  46380. if (construct) {
  46381. var parsedinput = parsedInputs[n];
  46382. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46383. this.add(input);
  46384. }
  46385. }
  46386. }
  46387. else {
  46388. //2016-03-08 this part is for managing backward compatibility
  46389. for (var n in this.attached) {
  46390. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46391. if (construct) {
  46392. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46393. this.remove(this.attached[n]);
  46394. this.add(input);
  46395. }
  46396. }
  46397. }
  46398. };
  46399. return CameraInputsManager;
  46400. }());
  46401. BABYLON.CameraInputsManager = CameraInputsManager;
  46402. })(BABYLON || (BABYLON = {}));
  46403. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46404. var BABYLON;
  46405. (function (BABYLON) {
  46406. /**
  46407. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  46408. * This is the base of the follow, arc rotate cameras and Free camera
  46409. * @see http://doc.babylonjs.com/features/cameras
  46410. */
  46411. var TargetCamera = /** @class */ (function (_super) {
  46412. __extends(TargetCamera, _super);
  46413. /**
  46414. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  46415. * This is the base of the follow, arc rotate cameras and Free camera
  46416. * @see http://doc.babylonjs.com/features/cameras
  46417. * @param name Defines the name of the camera in the scene
  46418. * @param position Defines the start position of the camera in the scene
  46419. * @param scene Defines the scene the camera belongs to
  46420. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  46421. */
  46422. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46423. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46424. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46425. /**
  46426. * Define the current direction the camera is moving to
  46427. */
  46428. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46429. /**
  46430. * Define the current rotation the camera is rotating to
  46431. */
  46432. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46433. /**
  46434. * Define the current rotation of the camera
  46435. */
  46436. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46437. /**
  46438. * Define the current speed of the camera
  46439. */
  46440. _this.speed = 2.0;
  46441. /**
  46442. * Add cconstraint to the camera to prevent it to move freely in all directions and
  46443. * around all axis.
  46444. */
  46445. _this.noRotationConstraint = false;
  46446. /**
  46447. * Define the current target of the camera as an object or a position.
  46448. */
  46449. _this.lockedTarget = null;
  46450. /** @hidden */
  46451. _this._currentTarget = BABYLON.Vector3.Zero();
  46452. /** @hidden */
  46453. _this._viewMatrix = BABYLON.Matrix.Zero();
  46454. /** @hidden */
  46455. _this._camMatrix = BABYLON.Matrix.Zero();
  46456. /** @hidden */
  46457. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46458. /** @hidden */
  46459. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46460. /** @hidden */
  46461. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46462. /** @hidden */
  46463. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46464. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46465. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46466. _this._defaultUp = BABYLON.Vector3.Up();
  46467. _this._cachedRotationZ = 0;
  46468. return _this;
  46469. }
  46470. /**
  46471. * Gets the position in front of the camera at a given distance.
  46472. * @param distance The distance from the camera we want the position to be
  46473. * @returns the position
  46474. */
  46475. TargetCamera.prototype.getFrontPosition = function (distance) {
  46476. this.getWorldMatrix();
  46477. var direction = this.getTarget().subtract(this.position);
  46478. direction.normalize();
  46479. direction.scaleInPlace(distance);
  46480. return this.globalPosition.add(direction);
  46481. };
  46482. /** @hidden */
  46483. TargetCamera.prototype._getLockedTargetPosition = function () {
  46484. if (!this.lockedTarget) {
  46485. return null;
  46486. }
  46487. if (this.lockedTarget.absolutePosition) {
  46488. this.lockedTarget.computeWorldMatrix();
  46489. }
  46490. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46491. };
  46492. /**
  46493. * Store current camera state of the camera (fov, position, rotation, etc..)
  46494. * @returns the camera
  46495. */
  46496. TargetCamera.prototype.storeState = function () {
  46497. this._storedPosition = this.position.clone();
  46498. this._storedRotation = this.rotation.clone();
  46499. if (this.rotationQuaternion) {
  46500. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46501. }
  46502. return _super.prototype.storeState.call(this);
  46503. };
  46504. /**
  46505. * Restored camera state. You must call storeState() first
  46506. * @returns whether it was successful or not
  46507. * @hidden
  46508. */
  46509. TargetCamera.prototype._restoreStateValues = function () {
  46510. if (!_super.prototype._restoreStateValues.call(this)) {
  46511. return false;
  46512. }
  46513. this.position = this._storedPosition.clone();
  46514. this.rotation = this._storedRotation.clone();
  46515. if (this.rotationQuaternion) {
  46516. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46517. }
  46518. this.cameraDirection.copyFromFloats(0, 0, 0);
  46519. this.cameraRotation.copyFromFloats(0, 0);
  46520. return true;
  46521. };
  46522. /** @hidden */
  46523. TargetCamera.prototype._initCache = function () {
  46524. _super.prototype._initCache.call(this);
  46525. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46526. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46527. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46528. };
  46529. /** @hidden */
  46530. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46531. if (!ignoreParentClass) {
  46532. _super.prototype._updateCache.call(this);
  46533. }
  46534. var lockedTargetPosition = this._getLockedTargetPosition();
  46535. if (!lockedTargetPosition) {
  46536. this._cache.lockedTarget = null;
  46537. }
  46538. else {
  46539. if (!this._cache.lockedTarget) {
  46540. this._cache.lockedTarget = lockedTargetPosition.clone();
  46541. }
  46542. else {
  46543. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46544. }
  46545. }
  46546. this._cache.rotation.copyFrom(this.rotation);
  46547. if (this.rotationQuaternion)
  46548. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46549. };
  46550. // Synchronized
  46551. /** @hidden */
  46552. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46553. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46554. return false;
  46555. }
  46556. var lockedTargetPosition = this._getLockedTargetPosition();
  46557. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46558. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46559. };
  46560. // Methods
  46561. /** @hidden */
  46562. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46563. var engine = this.getEngine();
  46564. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46565. };
  46566. // Target
  46567. /** @hidden */
  46568. TargetCamera.prototype.setTarget = function (target) {
  46569. this.upVector.normalize();
  46570. if (this.position.z === target.z) {
  46571. this.position.z += BABYLON.Epsilon;
  46572. }
  46573. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46574. this._camMatrix.invert();
  46575. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46576. var vDir = target.subtract(this.position);
  46577. if (vDir.x >= 0.0) {
  46578. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46579. }
  46580. else {
  46581. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46582. }
  46583. this.rotation.z = 0;
  46584. if (isNaN(this.rotation.x)) {
  46585. this.rotation.x = 0;
  46586. }
  46587. if (isNaN(this.rotation.y)) {
  46588. this.rotation.y = 0;
  46589. }
  46590. if (isNaN(this.rotation.z)) {
  46591. this.rotation.z = 0;
  46592. }
  46593. if (this.rotationQuaternion) {
  46594. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46595. }
  46596. };
  46597. /**
  46598. * Return the current target position of the camera. This value is expressed in local space.
  46599. * @returns the target position
  46600. */
  46601. TargetCamera.prototype.getTarget = function () {
  46602. return this._currentTarget;
  46603. };
  46604. /** @hidden */
  46605. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46606. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46607. };
  46608. /** @hidden */
  46609. TargetCamera.prototype._updatePosition = function () {
  46610. if (this.parent) {
  46611. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46612. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46613. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46614. return;
  46615. }
  46616. this.position.addInPlace(this.cameraDirection);
  46617. };
  46618. /** @hidden */
  46619. TargetCamera.prototype._checkInputs = function () {
  46620. var needToMove = this._decideIfNeedsToMove();
  46621. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46622. // Move
  46623. if (needToMove) {
  46624. this._updatePosition();
  46625. }
  46626. // Rotate
  46627. if (needToRotate) {
  46628. this.rotation.x += this.cameraRotation.x;
  46629. this.rotation.y += this.cameraRotation.y;
  46630. //rotate, if quaternion is set and rotation was used
  46631. if (this.rotationQuaternion) {
  46632. var len = this.rotation.lengthSquared();
  46633. if (len) {
  46634. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46635. }
  46636. }
  46637. if (!this.noRotationConstraint) {
  46638. var limit = (Math.PI / 2) * 0.95;
  46639. if (this.rotation.x > limit)
  46640. this.rotation.x = limit;
  46641. if (this.rotation.x < -limit)
  46642. this.rotation.x = -limit;
  46643. }
  46644. }
  46645. // Inertia
  46646. if (needToMove) {
  46647. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46648. this.cameraDirection.x = 0;
  46649. }
  46650. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46651. this.cameraDirection.y = 0;
  46652. }
  46653. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46654. this.cameraDirection.z = 0;
  46655. }
  46656. this.cameraDirection.scaleInPlace(this.inertia);
  46657. }
  46658. if (needToRotate) {
  46659. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46660. this.cameraRotation.x = 0;
  46661. }
  46662. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46663. this.cameraRotation.y = 0;
  46664. }
  46665. this.cameraRotation.scaleInPlace(this.inertia);
  46666. }
  46667. _super.prototype._checkInputs.call(this);
  46668. };
  46669. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46670. if (this.rotationQuaternion) {
  46671. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46672. }
  46673. else {
  46674. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46675. }
  46676. };
  46677. /**
  46678. * 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)
  46679. * @returns the current camera
  46680. */
  46681. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46682. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46683. return this;
  46684. };
  46685. /** @hidden */
  46686. TargetCamera.prototype._getViewMatrix = function () {
  46687. if (this.lockedTarget) {
  46688. this.setTarget(this._getLockedTargetPosition());
  46689. }
  46690. // Compute
  46691. this._updateCameraRotationMatrix();
  46692. // Apply the changed rotation to the upVector.
  46693. if (this._cachedRotationZ != this.rotation.z) {
  46694. this._rotateUpVectorWithCameraRotationMatrix();
  46695. this._cachedRotationZ = this.rotation.z;
  46696. }
  46697. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46698. // Computing target and final matrix
  46699. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46700. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46701. return this._viewMatrix;
  46702. };
  46703. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46704. if (this.parent) {
  46705. var parentWorldMatrix = this.parent.getWorldMatrix();
  46706. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46707. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46708. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46709. this._markSyncedWithParent();
  46710. }
  46711. else {
  46712. this._globalPosition.copyFrom(position);
  46713. this._globalCurrentTarget.copyFrom(target);
  46714. this._globalCurrentUpVector.copyFrom(up);
  46715. }
  46716. if (this.getScene().useRightHandedSystem) {
  46717. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46718. }
  46719. else {
  46720. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46721. }
  46722. };
  46723. /**
  46724. * @hidden
  46725. */
  46726. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46727. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46728. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46729. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46730. if (!this.rotationQuaternion) {
  46731. this.rotationQuaternion = new BABYLON.Quaternion();
  46732. }
  46733. rigCamera._cameraRigParams = {};
  46734. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46735. }
  46736. return rigCamera;
  46737. }
  46738. return null;
  46739. };
  46740. /**
  46741. * @hidden
  46742. */
  46743. TargetCamera.prototype._updateRigCameras = function () {
  46744. var camLeft = this._rigCameras[0];
  46745. var camRight = this._rigCameras[1];
  46746. switch (this.cameraRigMode) {
  46747. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46748. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46749. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46750. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46751. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46752. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46753. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46754. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46755. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46756. camLeft.setTarget(this.getTarget());
  46757. camRight.setTarget(this.getTarget());
  46758. break;
  46759. case BABYLON.Camera.RIG_MODE_VR:
  46760. if (camLeft.rotationQuaternion) {
  46761. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46762. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46763. }
  46764. else {
  46765. camLeft.rotation.copyFrom(this.rotation);
  46766. camRight.rotation.copyFrom(this.rotation);
  46767. }
  46768. camLeft.position.copyFrom(this.position);
  46769. camRight.position.copyFrom(this.position);
  46770. break;
  46771. }
  46772. _super.prototype._updateRigCameras.call(this);
  46773. };
  46774. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46775. if (!this._rigCamTransformMatrix) {
  46776. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46777. }
  46778. var target = this.getTarget();
  46779. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46780. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46781. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46782. };
  46783. /**
  46784. * Gets the current object class name.
  46785. * @return the class name
  46786. */
  46787. TargetCamera.prototype.getClassName = function () {
  46788. return "TargetCamera";
  46789. };
  46790. __decorate([
  46791. BABYLON.serializeAsVector3()
  46792. ], TargetCamera.prototype, "rotation", void 0);
  46793. __decorate([
  46794. BABYLON.serialize()
  46795. ], TargetCamera.prototype, "speed", void 0);
  46796. __decorate([
  46797. BABYLON.serializeAsMeshReference("lockedTargetId")
  46798. ], TargetCamera.prototype, "lockedTarget", void 0);
  46799. return TargetCamera;
  46800. }(BABYLON.Camera));
  46801. BABYLON.TargetCamera = TargetCamera;
  46802. })(BABYLON || (BABYLON = {}));
  46803. //# sourceMappingURL=babylon.targetCamera.js.map
  46804. var BABYLON;
  46805. (function (BABYLON) {
  46806. /**
  46807. * Manage the mouse inputs to control the movement of a free camera.
  46808. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46809. */
  46810. var FreeCameraMouseInput = /** @class */ (function () {
  46811. /**
  46812. * Manage the mouse inputs to control the movement of a free camera.
  46813. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46814. * @param touchEnabled Defines if touch is enabled or not
  46815. */
  46816. function FreeCameraMouseInput(
  46817. /**
  46818. * Define if touch is enabled in the mouse input
  46819. */
  46820. touchEnabled) {
  46821. if (touchEnabled === void 0) { touchEnabled = true; }
  46822. this.touchEnabled = touchEnabled;
  46823. /**
  46824. * Defines the buttons associated with the input to handle camera move.
  46825. */
  46826. this.buttons = [0, 1, 2];
  46827. /**
  46828. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  46829. */
  46830. this.angularSensibility = 2000.0;
  46831. this.previousPosition = null;
  46832. }
  46833. /**
  46834. * Attach the input controls to a specific dom element to get the input from.
  46835. * @param element Defines the element the controls should be listened from
  46836. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46837. */
  46838. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46839. var _this = this;
  46840. var engine = this.camera.getEngine();
  46841. if (!this._pointerInput) {
  46842. this._pointerInput = function (p, s) {
  46843. var evt = p.event;
  46844. if (engine.isInVRExclusivePointerMode) {
  46845. return;
  46846. }
  46847. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46848. return;
  46849. }
  46850. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46851. return;
  46852. }
  46853. var srcElement = (evt.srcElement || evt.target);
  46854. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46855. try {
  46856. srcElement.setPointerCapture(evt.pointerId);
  46857. }
  46858. catch (e) {
  46859. //Nothing to do with the error. Execution will continue.
  46860. }
  46861. _this.previousPosition = {
  46862. x: evt.clientX,
  46863. y: evt.clientY
  46864. };
  46865. if (!noPreventDefault) {
  46866. evt.preventDefault();
  46867. element.focus();
  46868. }
  46869. }
  46870. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46871. try {
  46872. srcElement.releasePointerCapture(evt.pointerId);
  46873. }
  46874. catch (e) {
  46875. //Nothing to do with the error.
  46876. }
  46877. _this.previousPosition = null;
  46878. if (!noPreventDefault) {
  46879. evt.preventDefault();
  46880. }
  46881. }
  46882. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46883. if (!_this.previousPosition || engine.isPointerLock) {
  46884. return;
  46885. }
  46886. var offsetX = evt.clientX - _this.previousPosition.x;
  46887. if (_this.camera.getScene().useRightHandedSystem)
  46888. offsetX *= -1;
  46889. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46890. offsetX *= -1;
  46891. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46892. var offsetY = evt.clientY - _this.previousPosition.y;
  46893. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46894. _this.previousPosition = {
  46895. x: evt.clientX,
  46896. y: evt.clientY
  46897. };
  46898. if (!noPreventDefault) {
  46899. evt.preventDefault();
  46900. }
  46901. }
  46902. };
  46903. }
  46904. this._onMouseMove = function (evt) {
  46905. if (!engine.isPointerLock) {
  46906. return;
  46907. }
  46908. if (engine.isInVRExclusivePointerMode) {
  46909. return;
  46910. }
  46911. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46912. if (_this.camera.getScene().useRightHandedSystem)
  46913. offsetX *= -1;
  46914. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46915. offsetX *= -1;
  46916. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46917. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46918. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46919. _this.previousPosition = null;
  46920. if (!noPreventDefault) {
  46921. evt.preventDefault();
  46922. }
  46923. };
  46924. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46925. element.addEventListener("mousemove", this._onMouseMove, false);
  46926. };
  46927. /**
  46928. * Detach the current controls from the specified dom element.
  46929. * @param element Defines the element to stop listening the inputs from
  46930. */
  46931. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46932. if (this._observer && element) {
  46933. this.camera.getScene().onPointerObservable.remove(this._observer);
  46934. if (this._onMouseMove) {
  46935. element.removeEventListener("mousemove", this._onMouseMove);
  46936. }
  46937. this._observer = null;
  46938. this._onMouseMove = null;
  46939. this.previousPosition = null;
  46940. }
  46941. };
  46942. /**
  46943. * Gets the class name of the current intput.
  46944. * @returns the class name
  46945. */
  46946. FreeCameraMouseInput.prototype.getClassName = function () {
  46947. return "FreeCameraMouseInput";
  46948. };
  46949. /**
  46950. * Get the friendly name associated with the input class.
  46951. * @returns the input friendly name
  46952. */
  46953. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46954. return "mouse";
  46955. };
  46956. __decorate([
  46957. BABYLON.serialize()
  46958. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46959. __decorate([
  46960. BABYLON.serialize()
  46961. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46962. return FreeCameraMouseInput;
  46963. }());
  46964. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46965. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46966. })(BABYLON || (BABYLON = {}));
  46967. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46968. var BABYLON;
  46969. (function (BABYLON) {
  46970. /**
  46971. * Manage the keyboard inputs to control the movement of a free camera.
  46972. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46973. */
  46974. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46975. function FreeCameraKeyboardMoveInput() {
  46976. /**
  46977. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  46978. */
  46979. this.keysUp = [38];
  46980. /**
  46981. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  46982. */
  46983. this.keysDown = [40];
  46984. /**
  46985. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  46986. */
  46987. this.keysLeft = [37];
  46988. /**
  46989. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  46990. */
  46991. this.keysRight = [39];
  46992. this._keys = new Array();
  46993. }
  46994. /**
  46995. * Attach the input controls to a specific dom element to get the input from.
  46996. * @param element Defines the element the controls should be listened from
  46997. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46998. */
  46999. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47000. var _this = this;
  47001. if (this._onCanvasBlurObserver) {
  47002. return;
  47003. }
  47004. this._scene = this.camera.getScene();
  47005. this._engine = this._scene.getEngine();
  47006. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47007. _this._keys = [];
  47008. });
  47009. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47010. var evt = info.event;
  47011. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47012. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47013. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47014. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47015. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47016. var index = _this._keys.indexOf(evt.keyCode);
  47017. if (index === -1) {
  47018. _this._keys.push(evt.keyCode);
  47019. }
  47020. if (!noPreventDefault) {
  47021. evt.preventDefault();
  47022. }
  47023. }
  47024. }
  47025. else {
  47026. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47027. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47028. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47029. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47030. var index = _this._keys.indexOf(evt.keyCode);
  47031. if (index >= 0) {
  47032. _this._keys.splice(index, 1);
  47033. }
  47034. if (!noPreventDefault) {
  47035. evt.preventDefault();
  47036. }
  47037. }
  47038. }
  47039. });
  47040. };
  47041. /**
  47042. * Detach the current controls from the specified dom element.
  47043. * @param element Defines the element to stop listening the inputs from
  47044. */
  47045. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47046. if (this._scene) {
  47047. if (this._onKeyboardObserver) {
  47048. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47049. }
  47050. if (this._onCanvasBlurObserver) {
  47051. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47052. }
  47053. this._onKeyboardObserver = null;
  47054. this._onCanvasBlurObserver = null;
  47055. }
  47056. this._keys = [];
  47057. };
  47058. /**
  47059. * Update the current camera state depending on the inputs that have been used this frame.
  47060. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47061. */
  47062. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47063. if (this._onKeyboardObserver) {
  47064. var camera = this.camera;
  47065. // Keyboard
  47066. for (var index = 0; index < this._keys.length; index++) {
  47067. var keyCode = this._keys[index];
  47068. var speed = camera._computeLocalCameraSpeed();
  47069. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47070. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47071. }
  47072. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47073. camera._localDirection.copyFromFloats(0, 0, speed);
  47074. }
  47075. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47076. camera._localDirection.copyFromFloats(speed, 0, 0);
  47077. }
  47078. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47079. camera._localDirection.copyFromFloats(0, 0, -speed);
  47080. }
  47081. if (camera.getScene().useRightHandedSystem) {
  47082. camera._localDirection.z *= -1;
  47083. }
  47084. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47085. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47086. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47087. }
  47088. }
  47089. };
  47090. /**
  47091. * Gets the class name of the current intput.
  47092. * @returns the class name
  47093. */
  47094. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47095. return "FreeCameraKeyboardMoveInput";
  47096. };
  47097. /** @hidden */
  47098. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47099. this._keys = [];
  47100. };
  47101. /**
  47102. * Get the friendly name associated with the input class.
  47103. * @returns the input friendly name
  47104. */
  47105. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47106. return "keyboard";
  47107. };
  47108. __decorate([
  47109. BABYLON.serialize()
  47110. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47111. __decorate([
  47112. BABYLON.serialize()
  47113. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47114. __decorate([
  47115. BABYLON.serialize()
  47116. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47117. __decorate([
  47118. BABYLON.serialize()
  47119. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47120. return FreeCameraKeyboardMoveInput;
  47121. }());
  47122. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47123. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47124. })(BABYLON || (BABYLON = {}));
  47125. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47126. var BABYLON;
  47127. (function (BABYLON) {
  47128. /**
  47129. * Default Inputs manager for the FreeCamera.
  47130. * It groups all the default supported inputs for ease of use.
  47131. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47132. */
  47133. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47134. __extends(FreeCameraInputsManager, _super);
  47135. /**
  47136. * Instantiates a new FreeCameraInputsManager.
  47137. * @param camera Defines the camera the inputs belong to
  47138. */
  47139. function FreeCameraInputsManager(camera) {
  47140. return _super.call(this, camera) || this;
  47141. }
  47142. /**
  47143. * Add keyboard input support to the input manager.
  47144. * @returns the current input manager
  47145. */
  47146. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47147. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47148. return this;
  47149. };
  47150. /**
  47151. * Add mouse input support to the input manager.
  47152. * @returns the current input manager
  47153. */
  47154. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47155. if (touchEnabled === void 0) { touchEnabled = true; }
  47156. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47157. return this;
  47158. };
  47159. /**
  47160. * Add orientation input support to the input manager.
  47161. * @returns the current input manager
  47162. */
  47163. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47164. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47165. return this;
  47166. };
  47167. /**
  47168. * Add touch input support to the input manager.
  47169. * @returns the current input manager
  47170. */
  47171. FreeCameraInputsManager.prototype.addTouch = function () {
  47172. this.add(new BABYLON.FreeCameraTouchInput());
  47173. return this;
  47174. };
  47175. /**
  47176. * Add virtual joystick input support to the input manager.
  47177. * @returns the current input manager
  47178. */
  47179. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47180. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47181. return this;
  47182. };
  47183. return FreeCameraInputsManager;
  47184. }(BABYLON.CameraInputsManager));
  47185. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47186. })(BABYLON || (BABYLON = {}));
  47187. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47188. var BABYLON;
  47189. (function (BABYLON) {
  47190. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47191. // Forcing to use the Universal camera
  47192. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47193. });
  47194. /**
  47195. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47196. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  47197. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47198. */
  47199. var FreeCamera = /** @class */ (function (_super) {
  47200. __extends(FreeCamera, _super);
  47201. /**
  47202. * Instantiates a Free Camera.
  47203. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47204. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  47205. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47206. * @param name Define the name of the camera in the scene
  47207. * @param position Define the start position of the camera in the scene
  47208. * @param scene Define the scene the camera belongs to
  47209. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47210. */
  47211. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47212. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47213. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47214. /**
  47215. * Define the collision ellipsoid of the camera.
  47216. * This is helpful to simulate a camera body like the player body around the camera
  47217. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47218. */
  47219. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47220. /**
  47221. * Define an offset for the position of the ellipsoid around the camera.
  47222. * This can be helpful to determine the center of the body near the gravity center of the body
  47223. * instead of its head.
  47224. */
  47225. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47226. /**
  47227. * Enable or disable collisions of the camera with the rest of the scene objects.
  47228. */
  47229. _this.checkCollisions = false;
  47230. /**
  47231. * Enable or disable gravity on the camera.
  47232. */
  47233. _this.applyGravity = false;
  47234. _this._needMoveForGravity = false;
  47235. _this._oldPosition = BABYLON.Vector3.Zero();
  47236. _this._diffPosition = BABYLON.Vector3.Zero();
  47237. _this._newPosition = BABYLON.Vector3.Zero();
  47238. // Collisions
  47239. _this._collisionMask = -1;
  47240. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47241. if (collidedMesh === void 0) { collidedMesh = null; }
  47242. //TODO move this to the collision coordinator!
  47243. if (_this.getScene().workerCollisions)
  47244. newPosition.multiplyInPlace(_this._collider._radius);
  47245. var updatePosition = function (newPos) {
  47246. _this._newPosition.copyFrom(newPos);
  47247. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47248. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47249. _this.position.addInPlace(_this._diffPosition);
  47250. if (_this.onCollide && collidedMesh) {
  47251. _this.onCollide(collidedMesh);
  47252. }
  47253. }
  47254. };
  47255. updatePosition(newPosition);
  47256. };
  47257. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47258. _this.inputs.addKeyboard().addMouse();
  47259. return _this;
  47260. }
  47261. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47262. /**
  47263. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47264. * Higher values reduce sensitivity.
  47265. */
  47266. get: function () {
  47267. var mouse = this.inputs.attached["mouse"];
  47268. if (mouse)
  47269. return mouse.angularSensibility;
  47270. return 0;
  47271. },
  47272. /**
  47273. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47274. * Higher values reduce sensitivity.
  47275. */
  47276. set: function (value) {
  47277. var mouse = this.inputs.attached["mouse"];
  47278. if (mouse)
  47279. mouse.angularSensibility = value;
  47280. },
  47281. enumerable: true,
  47282. configurable: true
  47283. });
  47284. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47285. /**
  47286. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47287. */
  47288. get: function () {
  47289. var keyboard = this.inputs.attached["keyboard"];
  47290. if (keyboard)
  47291. return keyboard.keysUp;
  47292. return [];
  47293. },
  47294. set: function (value) {
  47295. var keyboard = this.inputs.attached["keyboard"];
  47296. if (keyboard)
  47297. keyboard.keysUp = value;
  47298. },
  47299. enumerable: true,
  47300. configurable: true
  47301. });
  47302. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47303. /**
  47304. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47305. */
  47306. get: function () {
  47307. var keyboard = this.inputs.attached["keyboard"];
  47308. if (keyboard)
  47309. return keyboard.keysDown;
  47310. return [];
  47311. },
  47312. set: function (value) {
  47313. var keyboard = this.inputs.attached["keyboard"];
  47314. if (keyboard)
  47315. keyboard.keysDown = value;
  47316. },
  47317. enumerable: true,
  47318. configurable: true
  47319. });
  47320. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47321. /**
  47322. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47323. */
  47324. get: function () {
  47325. var keyboard = this.inputs.attached["keyboard"];
  47326. if (keyboard)
  47327. return keyboard.keysLeft;
  47328. return [];
  47329. },
  47330. set: function (value) {
  47331. var keyboard = this.inputs.attached["keyboard"];
  47332. if (keyboard)
  47333. keyboard.keysLeft = value;
  47334. },
  47335. enumerable: true,
  47336. configurable: true
  47337. });
  47338. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47339. /**
  47340. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47341. */
  47342. get: function () {
  47343. var keyboard = this.inputs.attached["keyboard"];
  47344. if (keyboard)
  47345. return keyboard.keysRight;
  47346. return [];
  47347. },
  47348. set: function (value) {
  47349. var keyboard = this.inputs.attached["keyboard"];
  47350. if (keyboard)
  47351. keyboard.keysRight = value;
  47352. },
  47353. enumerable: true,
  47354. configurable: true
  47355. });
  47356. /**
  47357. * Attached controls to the current camera.
  47358. * @param element Defines the element the controls should be listened from
  47359. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47360. */
  47361. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47362. this.inputs.attachElement(element, noPreventDefault);
  47363. };
  47364. /**
  47365. * Detach the current controls from the camera.
  47366. * The camera will stop reacting to inputs.
  47367. * @param element Defines the element to stop listening the inputs from
  47368. */
  47369. FreeCamera.prototype.detachControl = function (element) {
  47370. this.inputs.detachElement(element);
  47371. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47372. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47373. };
  47374. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47375. /**
  47376. * Define a collision mask to limit the list of object the camera can collide with
  47377. */
  47378. get: function () {
  47379. return this._collisionMask;
  47380. },
  47381. set: function (mask) {
  47382. this._collisionMask = !isNaN(mask) ? mask : -1;
  47383. },
  47384. enumerable: true,
  47385. configurable: true
  47386. });
  47387. /** @hidden */
  47388. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47389. var globalPosition;
  47390. if (this.parent) {
  47391. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47392. }
  47393. else {
  47394. globalPosition = this.position;
  47395. }
  47396. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47397. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47398. if (!this._collider) {
  47399. this._collider = new BABYLON.Collider();
  47400. }
  47401. this._collider._radius = this.ellipsoid;
  47402. this._collider.collisionMask = this._collisionMask;
  47403. //no need for clone, as long as gravity is not on.
  47404. var actualDisplacement = displacement;
  47405. //add gravity to the direction to prevent the dual-collision checking
  47406. if (this.applyGravity) {
  47407. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47408. actualDisplacement = displacement.add(this.getScene().gravity);
  47409. }
  47410. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47411. };
  47412. /** @hidden */
  47413. FreeCamera.prototype._checkInputs = function () {
  47414. if (!this._localDirection) {
  47415. this._localDirection = BABYLON.Vector3.Zero();
  47416. this._transformedDirection = BABYLON.Vector3.Zero();
  47417. }
  47418. this.inputs.checkInputs();
  47419. _super.prototype._checkInputs.call(this);
  47420. };
  47421. /** @hidden */
  47422. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47423. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47424. };
  47425. /** @hidden */
  47426. FreeCamera.prototype._updatePosition = function () {
  47427. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47428. this._collideWithWorld(this.cameraDirection);
  47429. }
  47430. else {
  47431. _super.prototype._updatePosition.call(this);
  47432. }
  47433. };
  47434. /**
  47435. * Destroy the camera and release the current resources hold by it.
  47436. */
  47437. FreeCamera.prototype.dispose = function () {
  47438. this.inputs.clear();
  47439. _super.prototype.dispose.call(this);
  47440. };
  47441. /**
  47442. * Gets the current object class name.
  47443. * @return the class name
  47444. */
  47445. FreeCamera.prototype.getClassName = function () {
  47446. return "FreeCamera";
  47447. };
  47448. __decorate([
  47449. BABYLON.serializeAsVector3()
  47450. ], FreeCamera.prototype, "ellipsoid", void 0);
  47451. __decorate([
  47452. BABYLON.serializeAsVector3()
  47453. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47454. __decorate([
  47455. BABYLON.serialize()
  47456. ], FreeCamera.prototype, "checkCollisions", void 0);
  47457. __decorate([
  47458. BABYLON.serialize()
  47459. ], FreeCamera.prototype, "applyGravity", void 0);
  47460. return FreeCamera;
  47461. }(BABYLON.TargetCamera));
  47462. BABYLON.FreeCamera = FreeCamera;
  47463. })(BABYLON || (BABYLON = {}));
  47464. //# sourceMappingURL=babylon.freeCamera.js.map
  47465. var BABYLON;
  47466. (function (BABYLON) {
  47467. /**
  47468. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  47469. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47470. */
  47471. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47472. function ArcRotateCameraKeyboardMoveInput() {
  47473. /**
  47474. * Defines the list of key codes associated with the up action (increase alpha)
  47475. */
  47476. this.keysUp = [38];
  47477. /**
  47478. * Defines the list of key codes associated with the down action (decrease alpha)
  47479. */
  47480. this.keysDown = [40];
  47481. /**
  47482. * Defines the list of key codes associated with the left action (increase beta)
  47483. */
  47484. this.keysLeft = [37];
  47485. /**
  47486. * Defines the list of key codes associated with the right action (decrease beta)
  47487. */
  47488. this.keysRight = [39];
  47489. /**
  47490. * Defines the list of key codes associated with the reset action.
  47491. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  47492. */
  47493. this.keysReset = [220];
  47494. /**
  47495. * Defines the panning sensibility of the inputs.
  47496. * (How fast is the camera paning)
  47497. */
  47498. this.panningSensibility = 50.0;
  47499. /**
  47500. * Defines the zooming sensibility of the inputs.
  47501. * (How fast is the camera zooming)
  47502. */
  47503. this.zoomingSensibility = 25.0;
  47504. /**
  47505. * Defines wether maintaining the alt key down switch the movement mode from
  47506. * orientation to zoom.
  47507. */
  47508. this.useAltToZoom = true;
  47509. this._keys = new Array();
  47510. }
  47511. /**
  47512. * Attach the input controls to a specific dom element to get the input from.
  47513. * @param element Defines the element the controls should be listened from
  47514. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47515. */
  47516. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47517. var _this = this;
  47518. if (this._onCanvasBlurObserver) {
  47519. return;
  47520. }
  47521. this._scene = this.camera.getScene();
  47522. this._engine = this._scene.getEngine();
  47523. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47524. _this._keys = [];
  47525. });
  47526. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47527. var evt = info.event;
  47528. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47529. _this._ctrlPressed = evt.ctrlKey;
  47530. _this._altPressed = evt.altKey;
  47531. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47532. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47533. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47534. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47535. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47536. var index = _this._keys.indexOf(evt.keyCode);
  47537. if (index === -1) {
  47538. _this._keys.push(evt.keyCode);
  47539. }
  47540. if (evt.preventDefault) {
  47541. if (!noPreventDefault) {
  47542. evt.preventDefault();
  47543. }
  47544. }
  47545. }
  47546. }
  47547. else {
  47548. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47549. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47550. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47551. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47552. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47553. var index = _this._keys.indexOf(evt.keyCode);
  47554. if (index >= 0) {
  47555. _this._keys.splice(index, 1);
  47556. }
  47557. if (evt.preventDefault) {
  47558. if (!noPreventDefault) {
  47559. evt.preventDefault();
  47560. }
  47561. }
  47562. }
  47563. }
  47564. });
  47565. };
  47566. /**
  47567. * Detach the current controls from the specified dom element.
  47568. * @param element Defines the element to stop listening the inputs from
  47569. */
  47570. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47571. if (this._scene) {
  47572. if (this._onKeyboardObserver) {
  47573. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47574. }
  47575. if (this._onCanvasBlurObserver) {
  47576. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47577. }
  47578. this._onKeyboardObserver = null;
  47579. this._onCanvasBlurObserver = null;
  47580. }
  47581. this._keys = [];
  47582. };
  47583. /**
  47584. * Update the current camera state depending on the inputs that have been used this frame.
  47585. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47586. */
  47587. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47588. if (this._onKeyboardObserver) {
  47589. var camera = this.camera;
  47590. for (var index = 0; index < this._keys.length; index++) {
  47591. var keyCode = this._keys[index];
  47592. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47593. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47594. camera.inertialPanningX -= 1 / this.panningSensibility;
  47595. }
  47596. else {
  47597. camera.inertialAlphaOffset -= 0.01;
  47598. }
  47599. }
  47600. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47601. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47602. camera.inertialPanningY += 1 / this.panningSensibility;
  47603. }
  47604. else if (this._altPressed && this.useAltToZoom) {
  47605. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47606. }
  47607. else {
  47608. camera.inertialBetaOffset -= 0.01;
  47609. }
  47610. }
  47611. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47612. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47613. camera.inertialPanningX += 1 / this.panningSensibility;
  47614. }
  47615. else {
  47616. camera.inertialAlphaOffset += 0.01;
  47617. }
  47618. }
  47619. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47620. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47621. camera.inertialPanningY -= 1 / this.panningSensibility;
  47622. }
  47623. else if (this._altPressed && this.useAltToZoom) {
  47624. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47625. }
  47626. else {
  47627. camera.inertialBetaOffset += 0.01;
  47628. }
  47629. }
  47630. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47631. if (camera.useInputToRestoreState) {
  47632. camera.restoreState();
  47633. }
  47634. }
  47635. }
  47636. }
  47637. };
  47638. /**
  47639. * Gets the class name of the current intput.
  47640. * @returns the class name
  47641. */
  47642. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47643. return "ArcRotateCameraKeyboardMoveInput";
  47644. };
  47645. /**
  47646. * Get the friendly name associated with the input class.
  47647. * @returns the input friendly name
  47648. */
  47649. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47650. return "keyboard";
  47651. };
  47652. __decorate([
  47653. BABYLON.serialize()
  47654. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47655. __decorate([
  47656. BABYLON.serialize()
  47657. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47658. __decorate([
  47659. BABYLON.serialize()
  47660. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47661. __decorate([
  47662. BABYLON.serialize()
  47663. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47664. __decorate([
  47665. BABYLON.serialize()
  47666. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47667. __decorate([
  47668. BABYLON.serialize()
  47669. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47670. __decorate([
  47671. BABYLON.serialize()
  47672. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47673. __decorate([
  47674. BABYLON.serialize()
  47675. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47676. return ArcRotateCameraKeyboardMoveInput;
  47677. }());
  47678. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47679. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47680. })(BABYLON || (BABYLON = {}));
  47681. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47682. var BABYLON;
  47683. (function (BABYLON) {
  47684. /**
  47685. * Manage the mouse wheel inputs to control an arc rotate camera.
  47686. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47687. */
  47688. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47689. function ArcRotateCameraMouseWheelInput() {
  47690. /**
  47691. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  47692. */
  47693. this.wheelPrecision = 3.0;
  47694. /**
  47695. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47696. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47697. */
  47698. this.wheelDeltaPercentage = 0;
  47699. }
  47700. /**
  47701. * Attach the input controls to a specific dom element to get the input from.
  47702. * @param element Defines the element the controls should be listened from
  47703. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47704. */
  47705. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47706. var _this = this;
  47707. this._wheel = function (p, s) {
  47708. //sanity check - this should be a PointerWheel event.
  47709. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47710. return;
  47711. var event = p.event;
  47712. var delta = 0;
  47713. if (event.wheelDelta) {
  47714. if (_this.wheelDeltaPercentage) {
  47715. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47716. if (event.wheelDelta > 0) {
  47717. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47718. }
  47719. else {
  47720. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47721. }
  47722. }
  47723. else {
  47724. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47725. }
  47726. }
  47727. else if (event.detail) {
  47728. delta = -event.detail / _this.wheelPrecision;
  47729. }
  47730. if (delta)
  47731. _this.camera.inertialRadiusOffset += delta;
  47732. if (event.preventDefault) {
  47733. if (!noPreventDefault) {
  47734. event.preventDefault();
  47735. }
  47736. }
  47737. };
  47738. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47739. };
  47740. /**
  47741. * Detach the current controls from the specified dom element.
  47742. * @param element Defines the element to stop listening the inputs from
  47743. */
  47744. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47745. if (this._observer && element) {
  47746. this.camera.getScene().onPointerObservable.remove(this._observer);
  47747. this._observer = null;
  47748. this._wheel = null;
  47749. }
  47750. };
  47751. /**
  47752. * Gets the class name of the current intput.
  47753. * @returns the class name
  47754. */
  47755. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47756. return "ArcRotateCameraMouseWheelInput";
  47757. };
  47758. /**
  47759. * Get the friendly name associated with the input class.
  47760. * @returns the input friendly name
  47761. */
  47762. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47763. return "mousewheel";
  47764. };
  47765. __decorate([
  47766. BABYLON.serialize()
  47767. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47768. __decorate([
  47769. BABYLON.serialize()
  47770. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47771. return ArcRotateCameraMouseWheelInput;
  47772. }());
  47773. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47774. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47775. })(BABYLON || (BABYLON = {}));
  47776. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47777. var BABYLON;
  47778. (function (BABYLON) {
  47779. /**
  47780. * Manage the pointers inputs to control an arc rotate camera.
  47781. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47782. */
  47783. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47784. function ArcRotateCameraPointersInput() {
  47785. /**
  47786. * Defines the buttons associated with the input to handle camera move.
  47787. */
  47788. this.buttons = [0, 1, 2];
  47789. /**
  47790. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  47791. */
  47792. this.angularSensibilityX = 1000.0;
  47793. /**
  47794. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  47795. */
  47796. this.angularSensibilityY = 1000.0;
  47797. /**
  47798. * Defines the pointer pinch precision or how fast is the camera zooming.
  47799. */
  47800. this.pinchPrecision = 12.0;
  47801. /**
  47802. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47803. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47804. */
  47805. this.pinchDeltaPercentage = 0;
  47806. /**
  47807. * Defines the pointer panning sensibility or how fast is the camera moving.
  47808. */
  47809. this.panningSensibility = 1000.0;
  47810. /**
  47811. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  47812. */
  47813. this.multiTouchPanning = true;
  47814. /**
  47815. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  47816. */
  47817. this.multiTouchPanAndZoom = true;
  47818. /**
  47819. * Revers pinch action direction.
  47820. */
  47821. this.pinchInwards = true;
  47822. this._isPanClick = false;
  47823. }
  47824. /**
  47825. * Attach the input controls to a specific dom element to get the input from.
  47826. * @param element Defines the element the controls should be listened from
  47827. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47828. */
  47829. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47830. var _this = this;
  47831. var engine = this.camera.getEngine();
  47832. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47833. var pointA = null;
  47834. var pointB = null;
  47835. var previousPinchSquaredDistance = 0;
  47836. var initialDistance = 0;
  47837. var twoFingerActivityCount = 0;
  47838. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47839. this._pointerInput = function (p, s) {
  47840. var evt = p.event;
  47841. var isTouch = p.event.pointerType === "touch";
  47842. if (engine.isInVRExclusivePointerMode) {
  47843. return;
  47844. }
  47845. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47846. return;
  47847. }
  47848. var srcElement = (evt.srcElement || evt.target);
  47849. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47850. try {
  47851. srcElement.setPointerCapture(evt.pointerId);
  47852. }
  47853. catch (e) {
  47854. //Nothing to do with the error. Execution will continue.
  47855. }
  47856. // Manage panning with pan button click
  47857. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47858. // manage pointers
  47859. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47860. if (pointA === null) {
  47861. pointA = cacheSoloPointer;
  47862. }
  47863. else if (pointB === null) {
  47864. pointB = cacheSoloPointer;
  47865. }
  47866. if (!noPreventDefault) {
  47867. evt.preventDefault();
  47868. element.focus();
  47869. }
  47870. }
  47871. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47872. if (_this.camera.useInputToRestoreState) {
  47873. _this.camera.restoreState();
  47874. }
  47875. }
  47876. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47877. try {
  47878. srcElement.releasePointerCapture(evt.pointerId);
  47879. }
  47880. catch (e) {
  47881. //Nothing to do with the error.
  47882. }
  47883. cacheSoloPointer = null;
  47884. previousPinchSquaredDistance = 0;
  47885. previousMultiTouchPanPosition.isPaning = false;
  47886. previousMultiTouchPanPosition.isPinching = false;
  47887. twoFingerActivityCount = 0;
  47888. initialDistance = 0;
  47889. if (!isTouch) {
  47890. pointB = null; // Mouse and pen are mono pointer
  47891. }
  47892. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47893. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47894. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47895. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47896. if (engine._badOS) {
  47897. pointA = pointB = null;
  47898. }
  47899. else {
  47900. //only remove the impacted pointer in case of multitouch allowing on most
  47901. //platforms switching from rotate to zoom and pan seamlessly.
  47902. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47903. pointA = pointB;
  47904. pointB = null;
  47905. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47906. }
  47907. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47908. pointB = null;
  47909. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47910. }
  47911. else {
  47912. pointA = pointB = null;
  47913. }
  47914. }
  47915. if (!noPreventDefault) {
  47916. evt.preventDefault();
  47917. }
  47918. }
  47919. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47920. if (!noPreventDefault) {
  47921. evt.preventDefault();
  47922. }
  47923. // One button down
  47924. if (pointA && pointB === null && cacheSoloPointer) {
  47925. if (_this.panningSensibility !== 0 &&
  47926. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47927. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47928. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47929. }
  47930. else {
  47931. var offsetX = evt.clientX - cacheSoloPointer.x;
  47932. var offsetY = evt.clientY - cacheSoloPointer.y;
  47933. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47934. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47935. }
  47936. cacheSoloPointer.x = evt.clientX;
  47937. cacheSoloPointer.y = evt.clientY;
  47938. }
  47939. // Two buttons down: pinch/pan
  47940. else if (pointA && pointB) {
  47941. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47942. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47943. ed.x = evt.clientX;
  47944. ed.y = evt.clientY;
  47945. var direction = _this.pinchInwards ? 1 : -1;
  47946. var distX = pointA.x - pointB.x;
  47947. var distY = pointA.y - pointB.y;
  47948. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47949. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47950. if (previousPinchSquaredDistance === 0) {
  47951. initialDistance = pinchDistance;
  47952. previousPinchSquaredDistance = pinchSquaredDistance;
  47953. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47954. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47955. return;
  47956. }
  47957. if (_this.multiTouchPanAndZoom) {
  47958. if (_this.pinchDeltaPercentage) {
  47959. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47960. }
  47961. else {
  47962. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47963. (_this.pinchPrecision *
  47964. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47965. direction);
  47966. }
  47967. if (_this.panningSensibility !== 0) {
  47968. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47969. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47970. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47971. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47972. previousMultiTouchPanPosition.x = pointersCenterX;
  47973. previousMultiTouchPanPosition.y = pointersCenterY;
  47974. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47975. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47976. }
  47977. }
  47978. else {
  47979. twoFingerActivityCount++;
  47980. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47981. if (_this.pinchDeltaPercentage) {
  47982. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47983. }
  47984. else {
  47985. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47986. (_this.pinchPrecision *
  47987. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47988. direction);
  47989. }
  47990. previousMultiTouchPanPosition.isPaning = false;
  47991. previousMultiTouchPanPosition.isPinching = true;
  47992. }
  47993. else {
  47994. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47995. if (!previousMultiTouchPanPosition.isPaning) {
  47996. previousMultiTouchPanPosition.isPaning = true;
  47997. previousMultiTouchPanPosition.isPinching = false;
  47998. previousMultiTouchPanPosition.x = ed.x;
  47999. previousMultiTouchPanPosition.y = ed.y;
  48000. return;
  48001. }
  48002. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48003. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48004. }
  48005. }
  48006. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48007. previousMultiTouchPanPosition.x = ed.x;
  48008. previousMultiTouchPanPosition.y = ed.y;
  48009. }
  48010. }
  48011. previousPinchSquaredDistance = pinchSquaredDistance;
  48012. }
  48013. }
  48014. };
  48015. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  48016. this._onContextMenu = function (evt) {
  48017. evt.preventDefault();
  48018. };
  48019. if (!this.camera._useCtrlForPanning) {
  48020. element.addEventListener("contextmenu", this._onContextMenu, false);
  48021. }
  48022. this._onLostFocus = function () {
  48023. //this._keys = [];
  48024. pointA = pointB = null;
  48025. previousPinchSquaredDistance = 0;
  48026. previousMultiTouchPanPosition.isPaning = false;
  48027. previousMultiTouchPanPosition.isPinching = false;
  48028. twoFingerActivityCount = 0;
  48029. cacheSoloPointer = null;
  48030. initialDistance = 0;
  48031. };
  48032. this._onMouseMove = function (evt) {
  48033. if (!engine.isPointerLock) {
  48034. return;
  48035. }
  48036. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48037. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48038. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48039. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48040. if (!noPreventDefault) {
  48041. evt.preventDefault();
  48042. }
  48043. };
  48044. this._onGestureStart = function (e) {
  48045. if (window.MSGesture === undefined) {
  48046. return;
  48047. }
  48048. if (!_this._MSGestureHandler) {
  48049. _this._MSGestureHandler = new MSGesture();
  48050. _this._MSGestureHandler.target = element;
  48051. }
  48052. _this._MSGestureHandler.addPointer(e.pointerId);
  48053. };
  48054. this._onGesture = function (e) {
  48055. _this.camera.radius *= e.scale;
  48056. if (e.preventDefault) {
  48057. if (!noPreventDefault) {
  48058. e.stopPropagation();
  48059. e.preventDefault();
  48060. }
  48061. }
  48062. };
  48063. element.addEventListener("mousemove", this._onMouseMove, false);
  48064. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48065. element.addEventListener("MSGestureChange", this._onGesture, false);
  48066. BABYLON.Tools.RegisterTopRootEvents([
  48067. { name: "blur", handler: this._onLostFocus }
  48068. ]);
  48069. };
  48070. /**
  48071. * Detach the current controls from the specified dom element.
  48072. * @param element Defines the element to stop listening the inputs from
  48073. */
  48074. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48075. if (this._onLostFocus) {
  48076. BABYLON.Tools.UnregisterTopRootEvents([
  48077. { name: "blur", handler: this._onLostFocus }
  48078. ]);
  48079. }
  48080. if (element && this._observer) {
  48081. this.camera.getScene().onPointerObservable.remove(this._observer);
  48082. this._observer = null;
  48083. if (this._onContextMenu) {
  48084. element.removeEventListener("contextmenu", this._onContextMenu);
  48085. }
  48086. if (this._onMouseMove) {
  48087. element.removeEventListener("mousemove", this._onMouseMove);
  48088. }
  48089. if (this._onGestureStart) {
  48090. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48091. }
  48092. if (this._onGesture) {
  48093. element.removeEventListener("MSGestureChange", this._onGesture);
  48094. }
  48095. this._isPanClick = false;
  48096. this.pinchInwards = true;
  48097. this._onMouseMove = null;
  48098. this._onGestureStart = null;
  48099. this._onGesture = null;
  48100. this._MSGestureHandler = null;
  48101. this._onLostFocus = null;
  48102. this._onContextMenu = null;
  48103. }
  48104. };
  48105. /**
  48106. * Gets the class name of the current intput.
  48107. * @returns the class name
  48108. */
  48109. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48110. return "ArcRotateCameraPointersInput";
  48111. };
  48112. /**
  48113. * Get the friendly name associated with the input class.
  48114. * @returns the input friendly name
  48115. */
  48116. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48117. return "pointers";
  48118. };
  48119. __decorate([
  48120. BABYLON.serialize()
  48121. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48122. __decorate([
  48123. BABYLON.serialize()
  48124. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48125. __decorate([
  48126. BABYLON.serialize()
  48127. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48128. __decorate([
  48129. BABYLON.serialize()
  48130. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48131. __decorate([
  48132. BABYLON.serialize()
  48133. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48134. __decorate([
  48135. BABYLON.serialize()
  48136. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48137. __decorate([
  48138. BABYLON.serialize()
  48139. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48140. __decorate([
  48141. BABYLON.serialize()
  48142. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48143. return ArcRotateCameraPointersInput;
  48144. }());
  48145. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48146. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48147. })(BABYLON || (BABYLON = {}));
  48148. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48149. var BABYLON;
  48150. (function (BABYLON) {
  48151. /**
  48152. * Default Inputs manager for the ArcRotateCamera.
  48153. * It groups all the default supported inputs for ease of use.
  48154. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48155. */
  48156. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48157. __extends(ArcRotateCameraInputsManager, _super);
  48158. /**
  48159. * Instantiates a new ArcRotateCameraInputsManager.
  48160. * @param camera Defines the camera the inputs belong to
  48161. */
  48162. function ArcRotateCameraInputsManager(camera) {
  48163. return _super.call(this, camera) || this;
  48164. }
  48165. /**
  48166. * Add mouse wheel input support to the input manager.
  48167. * @returns the current input manager
  48168. */
  48169. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48170. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48171. return this;
  48172. };
  48173. /**
  48174. * Add pointers input support to the input manager.
  48175. * @returns the current input manager
  48176. */
  48177. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48178. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48179. return this;
  48180. };
  48181. /**
  48182. * Add keyboard input support to the input manager.
  48183. * @returns the current input manager
  48184. */
  48185. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48186. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48187. return this;
  48188. };
  48189. /**
  48190. * Add orientation input support to the input manager.
  48191. * @returns the current input manager
  48192. */
  48193. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48194. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48195. return this;
  48196. };
  48197. return ArcRotateCameraInputsManager;
  48198. }(BABYLON.CameraInputsManager));
  48199. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48200. })(BABYLON || (BABYLON = {}));
  48201. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48202. var BABYLON;
  48203. (function (BABYLON) {
  48204. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  48205. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  48206. });
  48207. /**
  48208. * This represents an orbital type of camera.
  48209. *
  48210. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  48211. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  48212. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  48213. */
  48214. var ArcRotateCamera = /** @class */ (function (_super) {
  48215. __extends(ArcRotateCamera, _super);
  48216. /**
  48217. * Instantiates a new ArcRotateCamera in a given scene
  48218. * @param name Defines the name of the camera
  48219. * @param alpha Defines the camera rotation along the logitudinal axis
  48220. * @param beta Defines the camera rotation along the latitudinal axis
  48221. * @param radius Defines the camera distance from its target
  48222. * @param target Defines the camera target
  48223. * @param scene Defines the scene the camera belongs to
  48224. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48225. */
  48226. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48227. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48228. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48229. /**
  48230. * Current inertia value on the longitudinal axis.
  48231. * The bigger this number the longer it will take for the camera to stop.
  48232. */
  48233. _this.inertialAlphaOffset = 0;
  48234. /**
  48235. * Current inertia value on the latitudinal axis.
  48236. * The bigger this number the longer it will take for the camera to stop.
  48237. */
  48238. _this.inertialBetaOffset = 0;
  48239. /**
  48240. * Current inertia value on the radius axis.
  48241. * The bigger this number the longer it will take for the camera to stop.
  48242. */
  48243. _this.inertialRadiusOffset = 0;
  48244. /**
  48245. * Minimum allowed angle on the longitudinal axis.
  48246. * This can help limiting how the Camera is able to move in the scene.
  48247. */
  48248. _this.lowerAlphaLimit = null;
  48249. /**
  48250. * Maximum allowed angle on the longitudinal axis.
  48251. * This can help limiting how the Camera is able to move in the scene.
  48252. */
  48253. _this.upperAlphaLimit = null;
  48254. /**
  48255. * Minimum allowed angle on the latitudinal axis.
  48256. * This can help limiting how the Camera is able to move in the scene.
  48257. */
  48258. _this.lowerBetaLimit = 0.01;
  48259. /**
  48260. * Maximum allowed angle on the latitudinal axis.
  48261. * This can help limiting how the Camera is able to move in the scene.
  48262. */
  48263. _this.upperBetaLimit = Math.PI;
  48264. /**
  48265. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  48266. * This can help limiting how the Camera is able to move in the scene.
  48267. */
  48268. _this.lowerRadiusLimit = null;
  48269. /**
  48270. * Maximum allowed distance of the camera to the target (The camera can not get further).
  48271. * This can help limiting how the Camera is able to move in the scene.
  48272. */
  48273. _this.upperRadiusLimit = null;
  48274. /**
  48275. * Defines the current inertia value used during panning of the camera along the X axis.
  48276. */
  48277. _this.inertialPanningX = 0;
  48278. /**
  48279. * Defines the current inertia value used during panning of the camera along the Y axis.
  48280. */
  48281. _this.inertialPanningY = 0;
  48282. /**
  48283. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  48284. * Basically if your fingers moves away from more than this distance you will be considered
  48285. * in pinch mode.
  48286. */
  48287. _this.pinchToPanMaxDistance = 20;
  48288. /**
  48289. * Defines the maximum distance the camera can pan.
  48290. * This could help keeping the cammera always in your scene.
  48291. */
  48292. _this.panningDistanceLimit = null;
  48293. /**
  48294. * Defines the target of the camera before paning.
  48295. */
  48296. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48297. /**
  48298. * Defines the value of the inertia used during panning.
  48299. * 0 would mean stop inertia and one would mean no decelleration at all.
  48300. */
  48301. _this.panningInertia = 0.9;
  48302. //-- end properties for backward compatibility for inputs
  48303. /**
  48304. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  48305. */
  48306. _this.zoomOnFactor = 1;
  48307. /**
  48308. * Defines a screen offset for the camera position.
  48309. */
  48310. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48311. /**
  48312. * Allows the camera to be completely reversed.
  48313. * If false the camera can not arrive upside down.
  48314. */
  48315. _this.allowUpsideDown = true;
  48316. /**
  48317. * Define if double tap/click is used to restore the previously saved state of the camera.
  48318. */
  48319. _this.useInputToRestoreState = true;
  48320. /** @hidden */
  48321. _this._viewMatrix = new BABYLON.Matrix();
  48322. /**
  48323. * Defines the allowed panning axis.
  48324. */
  48325. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48326. /**
  48327. * Observable triggered when the mesh target has been changed on the camera.
  48328. */
  48329. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48330. /**
  48331. * Defines whether the camera should check collision with the objects oh the scene.
  48332. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  48333. */
  48334. _this.checkCollisions = false;
  48335. /**
  48336. * Defines the collision radius of the camera.
  48337. * This simulates a sphere around the camera.
  48338. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48339. */
  48340. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48341. _this._previousPosition = BABYLON.Vector3.Zero();
  48342. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48343. _this._newPosition = BABYLON.Vector3.Zero();
  48344. _this._computationVector = BABYLON.Vector3.Zero();
  48345. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48346. if (collidedMesh === void 0) { collidedMesh = null; }
  48347. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48348. newPosition.multiplyInPlace(_this._collider._radius);
  48349. }
  48350. if (!collidedMesh) {
  48351. _this._previousPosition.copyFrom(_this.position);
  48352. }
  48353. else {
  48354. _this.setPosition(newPosition);
  48355. if (_this.onCollide) {
  48356. _this.onCollide(collidedMesh);
  48357. }
  48358. }
  48359. // Recompute because of constraints
  48360. var cosa = Math.cos(_this.alpha);
  48361. var sina = Math.sin(_this.alpha);
  48362. var cosb = Math.cos(_this.beta);
  48363. var sinb = Math.sin(_this.beta);
  48364. if (sinb === 0) {
  48365. sinb = 0.0001;
  48366. }
  48367. var target = _this._getTargetPosition();
  48368. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48369. target.addToRef(_this._computationVector, _this._newPosition);
  48370. _this.position.copyFrom(_this._newPosition);
  48371. var up = _this.upVector;
  48372. if (_this.allowUpsideDown && _this.beta < 0) {
  48373. up = up.clone();
  48374. up = up.negate();
  48375. }
  48376. _this._computeViewMatrix(_this.position, target, up);
  48377. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48378. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48379. _this._collisionTriggered = false;
  48380. };
  48381. _this._target = BABYLON.Vector3.Zero();
  48382. if (target) {
  48383. _this.setTarget(target);
  48384. }
  48385. _this.alpha = alpha;
  48386. _this.beta = beta;
  48387. _this.radius = radius;
  48388. _this.getViewMatrix();
  48389. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48390. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48391. return _this;
  48392. }
  48393. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48394. /**
  48395. * Defines the target point of the camera.
  48396. * The camera looks towards it form the radius distance.
  48397. */
  48398. get: function () {
  48399. return this._target;
  48400. },
  48401. set: function (value) {
  48402. this.setTarget(value);
  48403. },
  48404. enumerable: true,
  48405. configurable: true
  48406. });
  48407. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48408. //-- begin properties for backward compatibility for inputs
  48409. /**
  48410. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48411. */
  48412. get: function () {
  48413. var pointers = this.inputs.attached["pointers"];
  48414. if (pointers)
  48415. return pointers.angularSensibilityX;
  48416. return 0;
  48417. },
  48418. set: function (value) {
  48419. var pointers = this.inputs.attached["pointers"];
  48420. if (pointers) {
  48421. pointers.angularSensibilityX = value;
  48422. }
  48423. },
  48424. enumerable: true,
  48425. configurable: true
  48426. });
  48427. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48428. /**
  48429. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48430. */
  48431. get: function () {
  48432. var pointers = this.inputs.attached["pointers"];
  48433. if (pointers)
  48434. return pointers.angularSensibilityY;
  48435. return 0;
  48436. },
  48437. set: function (value) {
  48438. var pointers = this.inputs.attached["pointers"];
  48439. if (pointers) {
  48440. pointers.angularSensibilityY = value;
  48441. }
  48442. },
  48443. enumerable: true,
  48444. configurable: true
  48445. });
  48446. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48447. /**
  48448. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  48449. */
  48450. get: function () {
  48451. var pointers = this.inputs.attached["pointers"];
  48452. if (pointers)
  48453. return pointers.pinchPrecision;
  48454. return 0;
  48455. },
  48456. set: function (value) {
  48457. var pointers = this.inputs.attached["pointers"];
  48458. if (pointers) {
  48459. pointers.pinchPrecision = value;
  48460. }
  48461. },
  48462. enumerable: true,
  48463. configurable: true
  48464. });
  48465. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48466. /**
  48467. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  48468. * It will be used instead of pinchDeltaPrecision if different from 0.
  48469. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48470. */
  48471. get: function () {
  48472. var pointers = this.inputs.attached["pointers"];
  48473. if (pointers)
  48474. return pointers.pinchDeltaPercentage;
  48475. return 0;
  48476. },
  48477. set: function (value) {
  48478. var pointers = this.inputs.attached["pointers"];
  48479. if (pointers) {
  48480. pointers.pinchDeltaPercentage = value;
  48481. }
  48482. },
  48483. enumerable: true,
  48484. configurable: true
  48485. });
  48486. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48487. /**
  48488. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  48489. */
  48490. get: function () {
  48491. var pointers = this.inputs.attached["pointers"];
  48492. if (pointers)
  48493. return pointers.panningSensibility;
  48494. return 0;
  48495. },
  48496. set: function (value) {
  48497. var pointers = this.inputs.attached["pointers"];
  48498. if (pointers) {
  48499. pointers.panningSensibility = value;
  48500. }
  48501. },
  48502. enumerable: true,
  48503. configurable: true
  48504. });
  48505. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48506. /**
  48507. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  48508. */
  48509. get: function () {
  48510. var keyboard = this.inputs.attached["keyboard"];
  48511. if (keyboard)
  48512. return keyboard.keysUp;
  48513. return [];
  48514. },
  48515. set: function (value) {
  48516. var keyboard = this.inputs.attached["keyboard"];
  48517. if (keyboard)
  48518. keyboard.keysUp = value;
  48519. },
  48520. enumerable: true,
  48521. configurable: true
  48522. });
  48523. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48524. /**
  48525. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  48526. */
  48527. get: function () {
  48528. var keyboard = this.inputs.attached["keyboard"];
  48529. if (keyboard)
  48530. return keyboard.keysDown;
  48531. return [];
  48532. },
  48533. set: function (value) {
  48534. var keyboard = this.inputs.attached["keyboard"];
  48535. if (keyboard)
  48536. keyboard.keysDown = value;
  48537. },
  48538. enumerable: true,
  48539. configurable: true
  48540. });
  48541. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48542. /**
  48543. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  48544. */
  48545. get: function () {
  48546. var keyboard = this.inputs.attached["keyboard"];
  48547. if (keyboard)
  48548. return keyboard.keysLeft;
  48549. return [];
  48550. },
  48551. set: function (value) {
  48552. var keyboard = this.inputs.attached["keyboard"];
  48553. if (keyboard)
  48554. keyboard.keysLeft = value;
  48555. },
  48556. enumerable: true,
  48557. configurable: true
  48558. });
  48559. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48560. /**
  48561. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  48562. */
  48563. get: function () {
  48564. var keyboard = this.inputs.attached["keyboard"];
  48565. if (keyboard)
  48566. return keyboard.keysRight;
  48567. return [];
  48568. },
  48569. set: function (value) {
  48570. var keyboard = this.inputs.attached["keyboard"];
  48571. if (keyboard)
  48572. keyboard.keysRight = value;
  48573. },
  48574. enumerable: true,
  48575. configurable: true
  48576. });
  48577. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48578. /**
  48579. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48580. */
  48581. get: function () {
  48582. var mousewheel = this.inputs.attached["mousewheel"];
  48583. if (mousewheel)
  48584. return mousewheel.wheelPrecision;
  48585. return 0;
  48586. },
  48587. set: function (value) {
  48588. var mousewheel = this.inputs.attached["mousewheel"];
  48589. if (mousewheel)
  48590. mousewheel.wheelPrecision = value;
  48591. },
  48592. enumerable: true,
  48593. configurable: true
  48594. });
  48595. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48596. /**
  48597. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  48598. * It will be used instead of pinchDeltaPrecision if different from 0.
  48599. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48600. */
  48601. get: function () {
  48602. var mousewheel = this.inputs.attached["mousewheel"];
  48603. if (mousewheel)
  48604. return mousewheel.wheelDeltaPercentage;
  48605. return 0;
  48606. },
  48607. set: function (value) {
  48608. var mousewheel = this.inputs.attached["mousewheel"];
  48609. if (mousewheel)
  48610. mousewheel.wheelDeltaPercentage = value;
  48611. },
  48612. enumerable: true,
  48613. configurable: true
  48614. });
  48615. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48616. /**
  48617. * Gets the bouncing behavior of the camera if it has been enabled.
  48618. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48619. */
  48620. get: function () {
  48621. return this._bouncingBehavior;
  48622. },
  48623. enumerable: true,
  48624. configurable: true
  48625. });
  48626. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48627. /**
  48628. * Defines if the bouncing behavior of the camera is enabled on the camera.
  48629. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48630. */
  48631. get: function () {
  48632. return this._bouncingBehavior != null;
  48633. },
  48634. set: function (value) {
  48635. if (value === this.useBouncingBehavior) {
  48636. return;
  48637. }
  48638. if (value) {
  48639. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48640. this.addBehavior(this._bouncingBehavior);
  48641. }
  48642. else if (this._bouncingBehavior) {
  48643. this.removeBehavior(this._bouncingBehavior);
  48644. this._bouncingBehavior = null;
  48645. }
  48646. },
  48647. enumerable: true,
  48648. configurable: true
  48649. });
  48650. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48651. /**
  48652. * Gets the framing behavior of the camera if it has been enabled.
  48653. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48654. */
  48655. get: function () {
  48656. return this._framingBehavior;
  48657. },
  48658. enumerable: true,
  48659. configurable: true
  48660. });
  48661. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48662. /**
  48663. * Defines if the framing behavior of the camera is enabled on the camera.
  48664. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48665. */
  48666. get: function () {
  48667. return this._framingBehavior != null;
  48668. },
  48669. set: function (value) {
  48670. if (value === this.useFramingBehavior) {
  48671. return;
  48672. }
  48673. if (value) {
  48674. this._framingBehavior = new BABYLON.FramingBehavior();
  48675. this.addBehavior(this._framingBehavior);
  48676. }
  48677. else if (this._framingBehavior) {
  48678. this.removeBehavior(this._framingBehavior);
  48679. this._framingBehavior = null;
  48680. }
  48681. },
  48682. enumerable: true,
  48683. configurable: true
  48684. });
  48685. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48686. /**
  48687. * Gets the auto rotation behavior of the camera if it has been enabled.
  48688. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48689. */
  48690. get: function () {
  48691. return this._autoRotationBehavior;
  48692. },
  48693. enumerable: true,
  48694. configurable: true
  48695. });
  48696. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48697. /**
  48698. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  48699. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48700. */
  48701. get: function () {
  48702. return this._autoRotationBehavior != null;
  48703. },
  48704. set: function (value) {
  48705. if (value === this.useAutoRotationBehavior) {
  48706. return;
  48707. }
  48708. if (value) {
  48709. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48710. this.addBehavior(this._autoRotationBehavior);
  48711. }
  48712. else if (this._autoRotationBehavior) {
  48713. this.removeBehavior(this._autoRotationBehavior);
  48714. this._autoRotationBehavior = null;
  48715. }
  48716. },
  48717. enumerable: true,
  48718. configurable: true
  48719. });
  48720. // Cache
  48721. /** @hidden */
  48722. ArcRotateCamera.prototype._initCache = function () {
  48723. _super.prototype._initCache.call(this);
  48724. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48725. this._cache.alpha = undefined;
  48726. this._cache.beta = undefined;
  48727. this._cache.radius = undefined;
  48728. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48729. };
  48730. /** @hidden */
  48731. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48732. if (!ignoreParentClass) {
  48733. _super.prototype._updateCache.call(this);
  48734. }
  48735. this._cache._target.copyFrom(this._getTargetPosition());
  48736. this._cache.alpha = this.alpha;
  48737. this._cache.beta = this.beta;
  48738. this._cache.radius = this.radius;
  48739. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48740. };
  48741. ArcRotateCamera.prototype._getTargetPosition = function () {
  48742. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48743. var pos = this._targetHost.getAbsolutePosition();
  48744. if (this._targetBoundingCenter) {
  48745. pos.addToRef(this._targetBoundingCenter, this._target);
  48746. }
  48747. else {
  48748. this._target.copyFrom(pos);
  48749. }
  48750. }
  48751. var lockedTargetPosition = this._getLockedTargetPosition();
  48752. if (lockedTargetPosition) {
  48753. return lockedTargetPosition;
  48754. }
  48755. return this._target;
  48756. };
  48757. /**
  48758. * Stores the current state of the camera (alpha, beta, radius and target)
  48759. * @returns the camera itself
  48760. */
  48761. ArcRotateCamera.prototype.storeState = function () {
  48762. this._storedAlpha = this.alpha;
  48763. this._storedBeta = this.beta;
  48764. this._storedRadius = this.radius;
  48765. this._storedTarget = this._getTargetPosition().clone();
  48766. return _super.prototype.storeState.call(this);
  48767. };
  48768. /**
  48769. * @hidden
  48770. * Restored camera state. You must call storeState() first
  48771. */
  48772. ArcRotateCamera.prototype._restoreStateValues = function () {
  48773. if (!_super.prototype._restoreStateValues.call(this)) {
  48774. return false;
  48775. }
  48776. this.alpha = this._storedAlpha;
  48777. this.beta = this._storedBeta;
  48778. this.radius = this._storedRadius;
  48779. this.setTarget(this._storedTarget.clone());
  48780. this.inertialAlphaOffset = 0;
  48781. this.inertialBetaOffset = 0;
  48782. this.inertialRadiusOffset = 0;
  48783. this.inertialPanningX = 0;
  48784. this.inertialPanningY = 0;
  48785. return true;
  48786. };
  48787. // Synchronized
  48788. /** @hidden */
  48789. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48790. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48791. return false;
  48792. return this._cache._target.equals(this._getTargetPosition())
  48793. && this._cache.alpha === this.alpha
  48794. && this._cache.beta === this.beta
  48795. && this._cache.radius === this.radius
  48796. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48797. };
  48798. /**
  48799. * Attached controls to the current camera.
  48800. * @param element Defines the element the controls should be listened from
  48801. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48802. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  48803. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  48804. */
  48805. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48806. var _this = this;
  48807. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48808. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48809. this._useCtrlForPanning = useCtrlForPanning;
  48810. this._panningMouseButton = panningMouseButton;
  48811. this.inputs.attachElement(element, noPreventDefault);
  48812. this._reset = function () {
  48813. _this.inertialAlphaOffset = 0;
  48814. _this.inertialBetaOffset = 0;
  48815. _this.inertialRadiusOffset = 0;
  48816. _this.inertialPanningX = 0;
  48817. _this.inertialPanningY = 0;
  48818. };
  48819. };
  48820. /**
  48821. * Detach the current controls from the camera.
  48822. * The camera will stop reacting to inputs.
  48823. * @param element Defines the element to stop listening the inputs from
  48824. */
  48825. ArcRotateCamera.prototype.detachControl = function (element) {
  48826. this.inputs.detachElement(element);
  48827. if (this._reset) {
  48828. this._reset();
  48829. }
  48830. };
  48831. /** @hidden */
  48832. ArcRotateCamera.prototype._checkInputs = function () {
  48833. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48834. if (this._collisionTriggered) {
  48835. return;
  48836. }
  48837. this.inputs.checkInputs();
  48838. // Inertia
  48839. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48840. var inertialAlphaOffset = this.inertialAlphaOffset;
  48841. if (this.beta <= 0)
  48842. inertialAlphaOffset *= -1;
  48843. if (this.getScene().useRightHandedSystem)
  48844. inertialAlphaOffset *= -1;
  48845. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48846. inertialAlphaOffset *= -1;
  48847. this.alpha += inertialAlphaOffset;
  48848. this.beta += this.inertialBetaOffset;
  48849. this.radius -= this.inertialRadiusOffset;
  48850. this.inertialAlphaOffset *= this.inertia;
  48851. this.inertialBetaOffset *= this.inertia;
  48852. this.inertialRadiusOffset *= this.inertia;
  48853. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48854. this.inertialAlphaOffset = 0;
  48855. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48856. this.inertialBetaOffset = 0;
  48857. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48858. this.inertialRadiusOffset = 0;
  48859. }
  48860. // Panning inertia
  48861. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48862. if (!this._localDirection) {
  48863. this._localDirection = BABYLON.Vector3.Zero();
  48864. this._transformedDirection = BABYLON.Vector3.Zero();
  48865. }
  48866. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48867. this._localDirection.multiplyInPlace(this.panningAxis);
  48868. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48869. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48870. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48871. if (!this.panningAxis.y) {
  48872. this._transformedDirection.y = 0;
  48873. }
  48874. if (!this._targetHost) {
  48875. if (this.panningDistanceLimit) {
  48876. this._transformedDirection.addInPlace(this._target);
  48877. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48878. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48879. this._target.copyFrom(this._transformedDirection);
  48880. }
  48881. }
  48882. else {
  48883. this._target.addInPlace(this._transformedDirection);
  48884. }
  48885. }
  48886. this.inertialPanningX *= this.panningInertia;
  48887. this.inertialPanningY *= this.panningInertia;
  48888. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48889. this.inertialPanningX = 0;
  48890. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48891. this.inertialPanningY = 0;
  48892. }
  48893. // Limits
  48894. this._checkLimits();
  48895. _super.prototype._checkInputs.call(this);
  48896. };
  48897. ArcRotateCamera.prototype._checkLimits = function () {
  48898. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48899. if (this.allowUpsideDown && this.beta > Math.PI) {
  48900. this.beta = this.beta - (2 * Math.PI);
  48901. }
  48902. }
  48903. else {
  48904. if (this.beta < this.lowerBetaLimit) {
  48905. this.beta = this.lowerBetaLimit;
  48906. }
  48907. }
  48908. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48909. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48910. this.beta = this.beta + (2 * Math.PI);
  48911. }
  48912. }
  48913. else {
  48914. if (this.beta > this.upperBetaLimit) {
  48915. this.beta = this.upperBetaLimit;
  48916. }
  48917. }
  48918. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48919. this.alpha = this.lowerAlphaLimit;
  48920. }
  48921. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48922. this.alpha = this.upperAlphaLimit;
  48923. }
  48924. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48925. this.radius = this.lowerRadiusLimit;
  48926. }
  48927. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48928. this.radius = this.upperRadiusLimit;
  48929. }
  48930. };
  48931. /**
  48932. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  48933. */
  48934. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48935. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48936. this.radius = this._computationVector.length();
  48937. if (this.radius === 0) {
  48938. this.radius = 0.0001; // Just to avoid division by zero
  48939. }
  48940. // Alpha
  48941. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48942. if (this._computationVector.z < 0) {
  48943. this.alpha = 2 * Math.PI - this.alpha;
  48944. }
  48945. // Beta
  48946. this.beta = Math.acos(this._computationVector.y / this.radius);
  48947. this._checkLimits();
  48948. };
  48949. /**
  48950. * Use a position to define the current camera related information like aplha, beta and radius
  48951. * @param position Defines the position to set the camera at
  48952. */
  48953. ArcRotateCamera.prototype.setPosition = function (position) {
  48954. if (this.position.equals(position)) {
  48955. return;
  48956. }
  48957. this.position.copyFrom(position);
  48958. this.rebuildAnglesAndRadius();
  48959. };
  48960. /**
  48961. * Defines the target the camera should look at.
  48962. * This will automatically adapt alpha beta and radius to fit within the new target.
  48963. * @param target Defines the new target as a Vector or a mesh
  48964. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  48965. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  48966. */
  48967. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48968. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48969. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48970. if (target.getBoundingInfo) {
  48971. if (toBoundingCenter) {
  48972. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48973. }
  48974. else {
  48975. this._targetBoundingCenter = null;
  48976. }
  48977. this._targetHost = target;
  48978. this._target = this._getTargetPosition();
  48979. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48980. }
  48981. else {
  48982. var newTarget = target;
  48983. var currentTarget = this._getTargetPosition();
  48984. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48985. return;
  48986. }
  48987. this._targetHost = null;
  48988. this._target = newTarget;
  48989. this._targetBoundingCenter = null;
  48990. this.onMeshTargetChangedObservable.notifyObservers(null);
  48991. }
  48992. this.rebuildAnglesAndRadius();
  48993. };
  48994. /** @hidden */
  48995. ArcRotateCamera.prototype._getViewMatrix = function () {
  48996. // Compute
  48997. var cosa = Math.cos(this.alpha);
  48998. var sina = Math.sin(this.alpha);
  48999. var cosb = Math.cos(this.beta);
  49000. var sinb = Math.sin(this.beta);
  49001. if (sinb === 0) {
  49002. sinb = 0.0001;
  49003. }
  49004. var target = this._getTargetPosition();
  49005. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49006. target.addToRef(this._computationVector, this._newPosition);
  49007. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49008. if (!this._collider) {
  49009. this._collider = new BABYLON.Collider();
  49010. }
  49011. this._collider._radius = this.collisionRadius;
  49012. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49013. this._collisionTriggered = true;
  49014. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49015. }
  49016. else {
  49017. this.position.copyFrom(this._newPosition);
  49018. var up = this.upVector;
  49019. if (this.allowUpsideDown && sinb < 0) {
  49020. up = up.clone();
  49021. up = up.negate();
  49022. }
  49023. this._computeViewMatrix(this.position, target, up);
  49024. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49025. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49026. }
  49027. this._currentTarget = target;
  49028. return this._viewMatrix;
  49029. };
  49030. /**
  49031. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  49032. * @param meshes Defines the mesh to zoom on
  49033. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  49034. */
  49035. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49036. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49037. meshes = meshes || this.getScene().meshes;
  49038. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49039. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49040. this.radius = distance * this.zoomOnFactor;
  49041. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49042. };
  49043. /**
  49044. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  49045. * The target will be changed but the radius
  49046. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  49047. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  49048. */
  49049. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49050. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49051. var meshesOrMinMaxVector;
  49052. var distance;
  49053. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49054. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49055. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49056. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49057. }
  49058. else { //minMaxVector and distance
  49059. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49060. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49061. distance = minMaxVectorAndDistance.distance;
  49062. }
  49063. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49064. if (!doNotUpdateMaxZ) {
  49065. this.maxZ = distance * 2;
  49066. }
  49067. };
  49068. /**
  49069. * @override
  49070. * Override Camera.createRigCamera
  49071. */
  49072. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49073. var alphaShift = 0;
  49074. switch (this.cameraRigMode) {
  49075. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49076. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49077. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49078. case BABYLON.Camera.RIG_MODE_VR:
  49079. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49080. break;
  49081. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49082. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49083. break;
  49084. }
  49085. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49086. rigCam._cameraRigParams = {};
  49087. return rigCam;
  49088. };
  49089. /**
  49090. * @hidden
  49091. * @override
  49092. * Override Camera._updateRigCameras
  49093. */
  49094. ArcRotateCamera.prototype._updateRigCameras = function () {
  49095. var camLeft = this._rigCameras[0];
  49096. var camRight = this._rigCameras[1];
  49097. camLeft.beta = camRight.beta = this.beta;
  49098. camLeft.radius = camRight.radius = this.radius;
  49099. switch (this.cameraRigMode) {
  49100. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49101. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49102. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49103. case BABYLON.Camera.RIG_MODE_VR:
  49104. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49105. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49106. break;
  49107. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49108. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49109. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49110. break;
  49111. }
  49112. _super.prototype._updateRigCameras.call(this);
  49113. };
  49114. /**
  49115. * Destroy the camera and release the current resources hold by it.
  49116. */
  49117. ArcRotateCamera.prototype.dispose = function () {
  49118. this.inputs.clear();
  49119. _super.prototype.dispose.call(this);
  49120. };
  49121. /**
  49122. * Gets the current object class name.
  49123. * @return the class name
  49124. */
  49125. ArcRotateCamera.prototype.getClassName = function () {
  49126. return "ArcRotateCamera";
  49127. };
  49128. __decorate([
  49129. BABYLON.serialize()
  49130. ], ArcRotateCamera.prototype, "alpha", void 0);
  49131. __decorate([
  49132. BABYLON.serialize()
  49133. ], ArcRotateCamera.prototype, "beta", void 0);
  49134. __decorate([
  49135. BABYLON.serialize()
  49136. ], ArcRotateCamera.prototype, "radius", void 0);
  49137. __decorate([
  49138. BABYLON.serializeAsVector3("target")
  49139. ], ArcRotateCamera.prototype, "_target", void 0);
  49140. __decorate([
  49141. BABYLON.serialize()
  49142. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49143. __decorate([
  49144. BABYLON.serialize()
  49145. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49146. __decorate([
  49147. BABYLON.serialize()
  49148. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49149. __decorate([
  49150. BABYLON.serialize()
  49151. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49152. __decorate([
  49153. BABYLON.serialize()
  49154. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49155. __decorate([
  49156. BABYLON.serialize()
  49157. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49158. __decorate([
  49159. BABYLON.serialize()
  49160. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49161. __decorate([
  49162. BABYLON.serialize()
  49163. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49164. __decorate([
  49165. BABYLON.serialize()
  49166. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49167. __decorate([
  49168. BABYLON.serialize()
  49169. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49170. __decorate([
  49171. BABYLON.serialize()
  49172. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49173. __decorate([
  49174. BABYLON.serialize()
  49175. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49176. __decorate([
  49177. BABYLON.serialize()
  49178. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49179. __decorate([
  49180. BABYLON.serializeAsVector3()
  49181. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49182. __decorate([
  49183. BABYLON.serialize()
  49184. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49185. __decorate([
  49186. BABYLON.serialize()
  49187. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49188. __decorate([
  49189. BABYLON.serialize()
  49190. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  49191. __decorate([
  49192. BABYLON.serialize()
  49193. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49194. __decorate([
  49195. BABYLON.serialize()
  49196. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  49197. return ArcRotateCamera;
  49198. }(BABYLON.TargetCamera));
  49199. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49200. })(BABYLON || (BABYLON = {}));
  49201. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49202. var BABYLON;
  49203. (function (BABYLON) {
  49204. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  49205. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  49206. });
  49207. /**
  49208. * The HemisphericLight simulates the ambient environment light,
  49209. * so the passed direction is the light reflection direction, not the incoming direction.
  49210. */
  49211. var HemisphericLight = /** @class */ (function (_super) {
  49212. __extends(HemisphericLight, _super);
  49213. /**
  49214. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49215. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49216. * The HemisphericLight can't cast shadows.
  49217. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49218. * @param name The friendly name of the light
  49219. * @param direction The direction of the light reflection
  49220. * @param scene The scene the light belongs to
  49221. */
  49222. function HemisphericLight(name, direction, scene) {
  49223. var _this = _super.call(this, name, scene) || this;
  49224. /**
  49225. * The groundColor is the light in the opposite direction to the one specified during creation.
  49226. * 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.
  49227. */
  49228. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49229. _this.direction = direction || BABYLON.Vector3.Up();
  49230. return _this;
  49231. }
  49232. HemisphericLight.prototype._buildUniformLayout = function () {
  49233. this._uniformBuffer.addUniform("vLightData", 4);
  49234. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49235. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49236. this._uniformBuffer.addUniform("vLightGround", 3);
  49237. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49238. this._uniformBuffer.addUniform("depthValues", 2);
  49239. this._uniformBuffer.create();
  49240. };
  49241. /**
  49242. * Returns the string "HemisphericLight".
  49243. * @return The class name
  49244. */
  49245. HemisphericLight.prototype.getClassName = function () {
  49246. return "HemisphericLight";
  49247. };
  49248. /**
  49249. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49250. * Returns the updated direction.
  49251. * @param target The target the direction should point to
  49252. * @return The computed direction
  49253. */
  49254. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49255. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49256. return this.direction;
  49257. };
  49258. /**
  49259. * Returns the shadow generator associated to the light.
  49260. * @returns Always null for hemispheric lights because it does not support shadows.
  49261. */
  49262. HemisphericLight.prototype.getShadowGenerator = function () {
  49263. return null;
  49264. };
  49265. /**
  49266. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49267. * @param effect The effect to update
  49268. * @param lightIndex The index of the light in the effect to update
  49269. * @returns The hemispheric light
  49270. */
  49271. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49272. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49273. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49274. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49275. return this;
  49276. };
  49277. /**
  49278. * Computes the world matrix of the node
  49279. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49280. * @param useWasUpdatedFlag defines a reserved property
  49281. * @returns the world matrix
  49282. */
  49283. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  49284. if (!this._worldMatrix) {
  49285. this._worldMatrix = BABYLON.Matrix.Identity();
  49286. }
  49287. return this._worldMatrix;
  49288. };
  49289. /**
  49290. * Returns the integer 3.
  49291. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49292. */
  49293. HemisphericLight.prototype.getTypeID = function () {
  49294. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49295. };
  49296. /**
  49297. * Prepares the list of defines specific to the light type.
  49298. * @param defines the list of defines
  49299. * @param lightIndex defines the index of the light for the effect
  49300. */
  49301. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49302. defines["HEMILIGHT" + lightIndex] = true;
  49303. };
  49304. __decorate([
  49305. BABYLON.serializeAsColor3()
  49306. ], HemisphericLight.prototype, "groundColor", void 0);
  49307. __decorate([
  49308. BABYLON.serializeAsVector3()
  49309. ], HemisphericLight.prototype, "direction", void 0);
  49310. return HemisphericLight;
  49311. }(BABYLON.Light));
  49312. BABYLON.HemisphericLight = HemisphericLight;
  49313. })(BABYLON || (BABYLON = {}));
  49314. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49315. var BABYLON;
  49316. (function (BABYLON) {
  49317. /**
  49318. * Base implementation IShadowLight
  49319. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49320. */
  49321. var ShadowLight = /** @class */ (function (_super) {
  49322. __extends(ShadowLight, _super);
  49323. function ShadowLight() {
  49324. var _this = _super !== null && _super.apply(this, arguments) || this;
  49325. _this._needProjectionMatrixCompute = true;
  49326. return _this;
  49327. }
  49328. ShadowLight.prototype._setPosition = function (value) {
  49329. this._position = value;
  49330. };
  49331. Object.defineProperty(ShadowLight.prototype, "position", {
  49332. /**
  49333. * Sets the position the shadow will be casted from. Also use as the light position for both
  49334. * point and spot lights.
  49335. */
  49336. get: function () {
  49337. return this._position;
  49338. },
  49339. /**
  49340. * Sets the position the shadow will be casted from. Also use as the light position for both
  49341. * point and spot lights.
  49342. */
  49343. set: function (value) {
  49344. this._setPosition(value);
  49345. },
  49346. enumerable: true,
  49347. configurable: true
  49348. });
  49349. ShadowLight.prototype._setDirection = function (value) {
  49350. this._direction = value;
  49351. };
  49352. Object.defineProperty(ShadowLight.prototype, "direction", {
  49353. /**
  49354. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49355. * Also use as the light direction on spot and directional lights.
  49356. */
  49357. get: function () {
  49358. return this._direction;
  49359. },
  49360. /**
  49361. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49362. * Also use as the light direction on spot and directional lights.
  49363. */
  49364. set: function (value) {
  49365. this._setDirection(value);
  49366. },
  49367. enumerable: true,
  49368. configurable: true
  49369. });
  49370. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49371. /**
  49372. * Gets the shadow projection clipping minimum z value.
  49373. */
  49374. get: function () {
  49375. return this._shadowMinZ;
  49376. },
  49377. /**
  49378. * Sets the shadow projection clipping minimum z value.
  49379. */
  49380. set: function (value) {
  49381. this._shadowMinZ = value;
  49382. this.forceProjectionMatrixCompute();
  49383. },
  49384. enumerable: true,
  49385. configurable: true
  49386. });
  49387. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49388. /**
  49389. * Sets the shadow projection clipping maximum z value.
  49390. */
  49391. get: function () {
  49392. return this._shadowMaxZ;
  49393. },
  49394. /**
  49395. * Gets the shadow projection clipping maximum z value.
  49396. */
  49397. set: function (value) {
  49398. this._shadowMaxZ = value;
  49399. this.forceProjectionMatrixCompute();
  49400. },
  49401. enumerable: true,
  49402. configurable: true
  49403. });
  49404. /**
  49405. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49406. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49407. */
  49408. ShadowLight.prototype.computeTransformedInformation = function () {
  49409. if (this.parent && this.parent.getWorldMatrix) {
  49410. if (!this.transformedPosition) {
  49411. this.transformedPosition = BABYLON.Vector3.Zero();
  49412. }
  49413. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49414. // In case the direction is present.
  49415. if (this.direction) {
  49416. if (!this.transformedDirection) {
  49417. this.transformedDirection = BABYLON.Vector3.Zero();
  49418. }
  49419. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49420. }
  49421. return true;
  49422. }
  49423. return false;
  49424. };
  49425. /**
  49426. * Return the depth scale used for the shadow map.
  49427. * @returns the depth scale.
  49428. */
  49429. ShadowLight.prototype.getDepthScale = function () {
  49430. return 50.0;
  49431. };
  49432. /**
  49433. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49434. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49435. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49436. */
  49437. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49438. return this.transformedDirection ? this.transformedDirection : this.direction;
  49439. };
  49440. /**
  49441. * Returns the ShadowLight absolute position in the World.
  49442. * @returns the position vector in world space
  49443. */
  49444. ShadowLight.prototype.getAbsolutePosition = function () {
  49445. return this.transformedPosition ? this.transformedPosition : this.position;
  49446. };
  49447. /**
  49448. * Sets the ShadowLight direction toward the passed target.
  49449. * @param target The point tot target in local space
  49450. * @returns the updated ShadowLight direction
  49451. */
  49452. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49453. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49454. return this.direction;
  49455. };
  49456. /**
  49457. * Returns the light rotation in euler definition.
  49458. * @returns the x y z rotation in local space.
  49459. */
  49460. ShadowLight.prototype.getRotation = function () {
  49461. this.direction.normalize();
  49462. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49463. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49464. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49465. };
  49466. /**
  49467. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49468. * @returns true if a cube texture needs to be use
  49469. */
  49470. ShadowLight.prototype.needCube = function () {
  49471. return false;
  49472. };
  49473. /**
  49474. * Detects if the projection matrix requires to be recomputed this frame.
  49475. * @returns true if it requires to be recomputed otherwise, false.
  49476. */
  49477. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49478. return this._needProjectionMatrixCompute;
  49479. };
  49480. /**
  49481. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49482. */
  49483. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49484. this._needProjectionMatrixCompute = true;
  49485. };
  49486. /** @hidden */
  49487. ShadowLight.prototype._initCache = function () {
  49488. _super.prototype._initCache.call(this);
  49489. this._cache.position = BABYLON.Vector3.Zero();
  49490. };
  49491. /** @hidden */
  49492. ShadowLight.prototype._isSynchronized = function () {
  49493. if (!this._cache.position.equals(this.position))
  49494. return false;
  49495. return true;
  49496. };
  49497. /**
  49498. * Computes the world matrix of the node
  49499. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49500. * @returns the world matrix
  49501. */
  49502. ShadowLight.prototype.computeWorldMatrix = function (force) {
  49503. if (!force && this.isSynchronized()) {
  49504. this._currentRenderId = this.getScene().getRenderId();
  49505. return this._worldMatrix;
  49506. }
  49507. this._updateCache();
  49508. this._cache.position.copyFrom(this.position);
  49509. if (!this._worldMatrix) {
  49510. this._worldMatrix = BABYLON.Matrix.Identity();
  49511. }
  49512. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49513. if (this.parent && this.parent.getWorldMatrix) {
  49514. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  49515. this._markSyncedWithParent();
  49516. }
  49517. // Cache the determinant
  49518. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  49519. return this._worldMatrix;
  49520. };
  49521. /**
  49522. * Gets the minZ used for shadow according to both the scene and the light.
  49523. * @param activeCamera The camera we are returning the min for
  49524. * @returns the depth min z
  49525. */
  49526. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49527. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49528. };
  49529. /**
  49530. * Gets the maxZ used for shadow according to both the scene and the light.
  49531. * @param activeCamera The camera we are returning the max for
  49532. * @returns the depth max z
  49533. */
  49534. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49535. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49536. };
  49537. /**
  49538. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49539. * @param matrix The materix to updated with the projection information
  49540. * @param viewMatrix The transform matrix of the light
  49541. * @param renderList The list of mesh to render in the map
  49542. * @returns The current light
  49543. */
  49544. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49545. if (this.customProjectionMatrixBuilder) {
  49546. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49547. }
  49548. else {
  49549. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49550. }
  49551. return this;
  49552. };
  49553. __decorate([
  49554. BABYLON.serializeAsVector3()
  49555. ], ShadowLight.prototype, "position", null);
  49556. __decorate([
  49557. BABYLON.serializeAsVector3()
  49558. ], ShadowLight.prototype, "direction", null);
  49559. __decorate([
  49560. BABYLON.serialize()
  49561. ], ShadowLight.prototype, "shadowMinZ", null);
  49562. __decorate([
  49563. BABYLON.serialize()
  49564. ], ShadowLight.prototype, "shadowMaxZ", null);
  49565. return ShadowLight;
  49566. }(BABYLON.Light));
  49567. BABYLON.ShadowLight = ShadowLight;
  49568. })(BABYLON || (BABYLON = {}));
  49569. //# sourceMappingURL=babylon.shadowLight.js.map
  49570. var BABYLON;
  49571. (function (BABYLON) {
  49572. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49573. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49574. });
  49575. /**
  49576. * A point light is a light defined by an unique point in world space.
  49577. * The light is emitted in every direction from this point.
  49578. * A good example of a point light is a standard light bulb.
  49579. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49580. */
  49581. var PointLight = /** @class */ (function (_super) {
  49582. __extends(PointLight, _super);
  49583. /**
  49584. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49585. * A PointLight emits the light in every direction.
  49586. * It can cast shadows.
  49587. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49588. * ```javascript
  49589. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49590. * ```
  49591. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49592. * @param name The light friendly name
  49593. * @param position The position of the point light in the scene
  49594. * @param scene The scene the lights belongs to
  49595. */
  49596. function PointLight(name, position, scene) {
  49597. var _this = _super.call(this, name, scene) || this;
  49598. _this._shadowAngle = Math.PI / 2;
  49599. _this.position = position;
  49600. return _this;
  49601. }
  49602. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49603. /**
  49604. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49605. * This specifies what angle the shadow will use to be created.
  49606. *
  49607. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49608. */
  49609. get: function () {
  49610. return this._shadowAngle;
  49611. },
  49612. /**
  49613. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49614. * This specifies what angle the shadow will use to be created.
  49615. *
  49616. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49617. */
  49618. set: function (value) {
  49619. this._shadowAngle = value;
  49620. this.forceProjectionMatrixCompute();
  49621. },
  49622. enumerable: true,
  49623. configurable: true
  49624. });
  49625. Object.defineProperty(PointLight.prototype, "direction", {
  49626. /**
  49627. * Gets the direction if it has been set.
  49628. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49629. */
  49630. get: function () {
  49631. return this._direction;
  49632. },
  49633. /**
  49634. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49635. */
  49636. set: function (value) {
  49637. var previousNeedCube = this.needCube();
  49638. this._direction = value;
  49639. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49640. this._shadowGenerator.recreateShadowMap();
  49641. }
  49642. },
  49643. enumerable: true,
  49644. configurable: true
  49645. });
  49646. /**
  49647. * Returns the string "PointLight"
  49648. * @returns the class name
  49649. */
  49650. PointLight.prototype.getClassName = function () {
  49651. return "PointLight";
  49652. };
  49653. /**
  49654. * Returns the integer 0.
  49655. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49656. */
  49657. PointLight.prototype.getTypeID = function () {
  49658. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49659. };
  49660. /**
  49661. * Specifies wether or not the shadowmap should be a cube texture.
  49662. * @returns true if the shadowmap needs to be a cube texture.
  49663. */
  49664. PointLight.prototype.needCube = function () {
  49665. return !this.direction;
  49666. };
  49667. /**
  49668. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49669. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49670. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49671. */
  49672. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49673. if (this.direction) {
  49674. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49675. }
  49676. else {
  49677. switch (faceIndex) {
  49678. case 0:
  49679. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49680. case 1:
  49681. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49682. case 2:
  49683. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49684. case 3:
  49685. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49686. case 4:
  49687. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49688. case 5:
  49689. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49690. }
  49691. }
  49692. return BABYLON.Vector3.Zero();
  49693. };
  49694. /**
  49695. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49696. * - fov = PI / 2
  49697. * - aspect ratio : 1.0
  49698. * - z-near and far equal to the active camera minZ and maxZ.
  49699. * Returns the PointLight.
  49700. */
  49701. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49702. var activeCamera = this.getScene().activeCamera;
  49703. if (!activeCamera) {
  49704. return;
  49705. }
  49706. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49707. };
  49708. PointLight.prototype._buildUniformLayout = function () {
  49709. this._uniformBuffer.addUniform("vLightData", 4);
  49710. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49711. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49712. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49713. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49714. this._uniformBuffer.addUniform("depthValues", 2);
  49715. this._uniformBuffer.create();
  49716. };
  49717. /**
  49718. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49719. * @param effect The effect to update
  49720. * @param lightIndex The index of the light in the effect to update
  49721. * @returns The point light
  49722. */
  49723. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49724. if (this.computeTransformedInformation()) {
  49725. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49726. }
  49727. else {
  49728. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49729. }
  49730. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49731. return this;
  49732. };
  49733. /**
  49734. * Prepares the list of defines specific to the light type.
  49735. * @param defines the list of defines
  49736. * @param lightIndex defines the index of the light for the effect
  49737. */
  49738. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49739. defines["POINTLIGHT" + lightIndex] = true;
  49740. };
  49741. __decorate([
  49742. BABYLON.serialize()
  49743. ], PointLight.prototype, "shadowAngle", null);
  49744. return PointLight;
  49745. }(BABYLON.ShadowLight));
  49746. BABYLON.PointLight = PointLight;
  49747. })(BABYLON || (BABYLON = {}));
  49748. //# sourceMappingURL=babylon.pointLight.js.map
  49749. var BABYLON;
  49750. (function (BABYLON) {
  49751. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49752. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49753. });
  49754. /**
  49755. * A directional light is defined by a direction (what a surprise!).
  49756. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49757. * 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.
  49758. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49759. */
  49760. var DirectionalLight = /** @class */ (function (_super) {
  49761. __extends(DirectionalLight, _super);
  49762. /**
  49763. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49764. * The directional light is emitted from everywhere in the given direction.
  49765. * It can cast shadows.
  49766. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49767. * @param name The friendly name of the light
  49768. * @param direction The direction of the light
  49769. * @param scene The scene the light belongs to
  49770. */
  49771. function DirectionalLight(name, direction, scene) {
  49772. var _this = _super.call(this, name, scene) || this;
  49773. _this._shadowFrustumSize = 0;
  49774. _this._shadowOrthoScale = 0.1;
  49775. /**
  49776. * Automatically compute the projection matrix to best fit (including all the casters)
  49777. * on each frame.
  49778. */
  49779. _this.autoUpdateExtends = true;
  49780. // Cache
  49781. _this._orthoLeft = Number.MAX_VALUE;
  49782. _this._orthoRight = Number.MIN_VALUE;
  49783. _this._orthoTop = Number.MIN_VALUE;
  49784. _this._orthoBottom = Number.MAX_VALUE;
  49785. _this.position = direction.scale(-1.0);
  49786. _this.direction = direction;
  49787. return _this;
  49788. }
  49789. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49790. /**
  49791. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49792. */
  49793. get: function () {
  49794. return this._shadowFrustumSize;
  49795. },
  49796. /**
  49797. * Specifies a fix frustum size for the shadow generation.
  49798. */
  49799. set: function (value) {
  49800. this._shadowFrustumSize = value;
  49801. this.forceProjectionMatrixCompute();
  49802. },
  49803. enumerable: true,
  49804. configurable: true
  49805. });
  49806. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49807. /**
  49808. * Gets the shadow projection scale against the optimal computed one.
  49809. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49810. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49811. */
  49812. get: function () {
  49813. return this._shadowOrthoScale;
  49814. },
  49815. /**
  49816. * Sets the shadow projection scale against the optimal computed one.
  49817. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49818. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49819. */
  49820. set: function (value) {
  49821. this._shadowOrthoScale = value;
  49822. this.forceProjectionMatrixCompute();
  49823. },
  49824. enumerable: true,
  49825. configurable: true
  49826. });
  49827. /**
  49828. * Returns the string "DirectionalLight".
  49829. * @return The class name
  49830. */
  49831. DirectionalLight.prototype.getClassName = function () {
  49832. return "DirectionalLight";
  49833. };
  49834. /**
  49835. * Returns the integer 1.
  49836. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49837. */
  49838. DirectionalLight.prototype.getTypeID = function () {
  49839. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49840. };
  49841. /**
  49842. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49843. * Returns the DirectionalLight Shadow projection matrix.
  49844. */
  49845. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49846. if (this.shadowFrustumSize > 0) {
  49847. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49848. }
  49849. else {
  49850. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49851. }
  49852. };
  49853. /**
  49854. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49855. * Returns the DirectionalLight Shadow projection matrix.
  49856. */
  49857. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49858. var activeCamera = this.getScene().activeCamera;
  49859. if (!activeCamera) {
  49860. return;
  49861. }
  49862. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49863. };
  49864. /**
  49865. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49866. * Returns the DirectionalLight Shadow projection matrix.
  49867. */
  49868. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49869. var activeCamera = this.getScene().activeCamera;
  49870. if (!activeCamera) {
  49871. return;
  49872. }
  49873. // Check extends
  49874. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49875. var tempVector3 = BABYLON.Vector3.Zero();
  49876. this._orthoLeft = Number.MAX_VALUE;
  49877. this._orthoRight = Number.MIN_VALUE;
  49878. this._orthoTop = Number.MIN_VALUE;
  49879. this._orthoBottom = Number.MAX_VALUE;
  49880. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49881. var mesh = renderList[meshIndex];
  49882. if (!mesh) {
  49883. continue;
  49884. }
  49885. var boundingInfo = mesh.getBoundingInfo();
  49886. var boundingBox = boundingInfo.boundingBox;
  49887. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49888. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49889. if (tempVector3.x < this._orthoLeft)
  49890. this._orthoLeft = tempVector3.x;
  49891. if (tempVector3.y < this._orthoBottom)
  49892. this._orthoBottom = tempVector3.y;
  49893. if (tempVector3.x > this._orthoRight)
  49894. this._orthoRight = tempVector3.x;
  49895. if (tempVector3.y > this._orthoTop)
  49896. this._orthoTop = tempVector3.y;
  49897. }
  49898. }
  49899. }
  49900. var xOffset = this._orthoRight - this._orthoLeft;
  49901. var yOffset = this._orthoTop - this._orthoBottom;
  49902. 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);
  49903. };
  49904. DirectionalLight.prototype._buildUniformLayout = function () {
  49905. this._uniformBuffer.addUniform("vLightData", 4);
  49906. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49907. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49908. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49909. this._uniformBuffer.addUniform("depthValues", 2);
  49910. this._uniformBuffer.create();
  49911. };
  49912. /**
  49913. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49914. * @param effect The effect to update
  49915. * @param lightIndex The index of the light in the effect to update
  49916. * @returns The directional light
  49917. */
  49918. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49919. if (this.computeTransformedInformation()) {
  49920. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49921. return this;
  49922. }
  49923. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49924. return this;
  49925. };
  49926. /**
  49927. * Gets the minZ used for shadow according to both the scene and the light.
  49928. *
  49929. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49930. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49931. * @param activeCamera The camera we are returning the min for
  49932. * @returns the depth min z
  49933. */
  49934. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49935. return 1;
  49936. };
  49937. /**
  49938. * Gets the maxZ used for shadow according to both the scene and the light.
  49939. *
  49940. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49941. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49942. * @param activeCamera The camera we are returning the max for
  49943. * @returns the depth max z
  49944. */
  49945. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49946. return 1;
  49947. };
  49948. /**
  49949. * Prepares the list of defines specific to the light type.
  49950. * @param defines the list of defines
  49951. * @param lightIndex defines the index of the light for the effect
  49952. */
  49953. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49954. defines["DIRLIGHT" + lightIndex] = true;
  49955. };
  49956. __decorate([
  49957. BABYLON.serialize()
  49958. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49959. __decorate([
  49960. BABYLON.serialize()
  49961. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49962. __decorate([
  49963. BABYLON.serialize()
  49964. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49965. return DirectionalLight;
  49966. }(BABYLON.ShadowLight));
  49967. BABYLON.DirectionalLight = DirectionalLight;
  49968. })(BABYLON || (BABYLON = {}));
  49969. //# sourceMappingURL=babylon.directionalLight.js.map
  49970. var BABYLON;
  49971. (function (BABYLON) {
  49972. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49973. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49974. });
  49975. /**
  49976. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49977. * These values define a cone of light starting from the position, emitting toward the direction.
  49978. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49979. * and the exponent defines the speed of the decay of the light with distance (reach).
  49980. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49981. */
  49982. var SpotLight = /** @class */ (function (_super) {
  49983. __extends(SpotLight, _super);
  49984. /**
  49985. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49986. * It can cast shadows.
  49987. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49988. * @param name The light friendly name
  49989. * @param position The position of the spot light in the scene
  49990. * @param direction The direction of the light in the scene
  49991. * @param angle The cone angle of the light in Radians
  49992. * @param exponent The light decay speed with the distance from the emission spot
  49993. * @param scene The scene the lights belongs to
  49994. */
  49995. function SpotLight(name, position, direction, angle, exponent, scene) {
  49996. var _this = _super.call(this, name, scene) || this;
  49997. _this._innerAngle = 0;
  49998. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49999. _this._projectionTextureLightNear = 1e-6;
  50000. _this._projectionTextureLightFar = 1000.0;
  50001. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50002. _this._projectionTextureViewLightDirty = true;
  50003. _this._projectionTextureProjectionLightDirty = true;
  50004. _this._projectionTextureDirty = true;
  50005. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50006. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50007. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50008. _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);
  50009. _this.position = position;
  50010. _this.direction = direction;
  50011. _this.angle = angle;
  50012. _this.exponent = exponent;
  50013. return _this;
  50014. }
  50015. Object.defineProperty(SpotLight.prototype, "angle", {
  50016. /**
  50017. * Gets the cone angle of the spot light in Radians.
  50018. */
  50019. get: function () {
  50020. return this._angle;
  50021. },
  50022. /**
  50023. * Sets the cone angle of the spot light in Radians.
  50024. */
  50025. set: function (value) {
  50026. this._angle = value;
  50027. this._cosHalfAngle = Math.cos(value * 0.5);
  50028. this._projectionTextureProjectionLightDirty = true;
  50029. this.forceProjectionMatrixCompute();
  50030. this._computeAngleValues();
  50031. },
  50032. enumerable: true,
  50033. configurable: true
  50034. });
  50035. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  50036. /**
  50037. * Only used in gltf falloff mode, this defines the angle where
  50038. * the directional falloff will start before cutting at angle which could be seen
  50039. * as outer angle.
  50040. */
  50041. get: function () {
  50042. return this._innerAngle;
  50043. },
  50044. /**
  50045. * Only used in gltf falloff mode, this defines the angle where
  50046. * the directional falloff will start before cutting at angle which could be seen
  50047. * as outer angle.
  50048. */
  50049. set: function (value) {
  50050. this._innerAngle = value;
  50051. this._computeAngleValues();
  50052. },
  50053. enumerable: true,
  50054. configurable: true
  50055. });
  50056. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50057. /**
  50058. * Allows scaling the angle of the light for shadow generation only.
  50059. */
  50060. get: function () {
  50061. return this._shadowAngleScale;
  50062. },
  50063. /**
  50064. * Allows scaling the angle of the light for shadow generation only.
  50065. */
  50066. set: function (value) {
  50067. this._shadowAngleScale = value;
  50068. this.forceProjectionMatrixCompute();
  50069. },
  50070. enumerable: true,
  50071. configurable: true
  50072. });
  50073. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50074. /**
  50075. * Allows reading the projecton texture
  50076. */
  50077. get: function () {
  50078. return this._projectionTextureMatrix;
  50079. },
  50080. enumerable: true,
  50081. configurable: true
  50082. });
  50083. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50084. /**
  50085. * Gets the near clip of the Spotlight for texture projection.
  50086. */
  50087. get: function () {
  50088. return this._projectionTextureLightNear;
  50089. },
  50090. /**
  50091. * Sets the near clip of the Spotlight for texture projection.
  50092. */
  50093. set: function (value) {
  50094. this._projectionTextureLightNear = value;
  50095. this._projectionTextureProjectionLightDirty = true;
  50096. },
  50097. enumerable: true,
  50098. configurable: true
  50099. });
  50100. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50101. /**
  50102. * Gets the far clip of the Spotlight for texture projection.
  50103. */
  50104. get: function () {
  50105. return this._projectionTextureLightFar;
  50106. },
  50107. /**
  50108. * Sets the far clip of the Spotlight for texture projection.
  50109. */
  50110. set: function (value) {
  50111. this._projectionTextureLightFar = value;
  50112. this._projectionTextureProjectionLightDirty = true;
  50113. },
  50114. enumerable: true,
  50115. configurable: true
  50116. });
  50117. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50118. /**
  50119. * Gets the Up vector of the Spotlight for texture projection.
  50120. */
  50121. get: function () {
  50122. return this._projectionTextureUpDirection;
  50123. },
  50124. /**
  50125. * Sets the Up vector of the Spotlight for texture projection.
  50126. */
  50127. set: function (value) {
  50128. this._projectionTextureUpDirection = value;
  50129. this._projectionTextureProjectionLightDirty = true;
  50130. },
  50131. enumerable: true,
  50132. configurable: true
  50133. });
  50134. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50135. /**
  50136. * Gets the projection texture of the light.
  50137. */
  50138. get: function () {
  50139. return this._projectionTexture;
  50140. },
  50141. /**
  50142. * Sets the projection texture of the light.
  50143. */
  50144. set: function (value) {
  50145. this._projectionTexture = value;
  50146. this._projectionTextureDirty = true;
  50147. },
  50148. enumerable: true,
  50149. configurable: true
  50150. });
  50151. /**
  50152. * Returns the string "SpotLight".
  50153. * @returns the class name
  50154. */
  50155. SpotLight.prototype.getClassName = function () {
  50156. return "SpotLight";
  50157. };
  50158. /**
  50159. * Returns the integer 2.
  50160. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50161. */
  50162. SpotLight.prototype.getTypeID = function () {
  50163. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50164. };
  50165. /**
  50166. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50167. */
  50168. SpotLight.prototype._setDirection = function (value) {
  50169. _super.prototype._setDirection.call(this, value);
  50170. this._projectionTextureViewLightDirty = true;
  50171. };
  50172. /**
  50173. * Overrides the position setter to recompute the projection texture view light Matrix.
  50174. */
  50175. SpotLight.prototype._setPosition = function (value) {
  50176. _super.prototype._setPosition.call(this, value);
  50177. this._projectionTextureViewLightDirty = true;
  50178. };
  50179. /**
  50180. * 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.
  50181. * Returns the SpotLight.
  50182. */
  50183. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50184. var activeCamera = this.getScene().activeCamera;
  50185. if (!activeCamera) {
  50186. return;
  50187. }
  50188. this._shadowAngleScale = this._shadowAngleScale || 1;
  50189. var angle = this._shadowAngleScale * this._angle;
  50190. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50191. };
  50192. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50193. this._projectionTextureViewLightDirty = false;
  50194. this._projectionTextureDirty = true;
  50195. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50196. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50197. };
  50198. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50199. this._projectionTextureProjectionLightDirty = false;
  50200. this._projectionTextureDirty = true;
  50201. var light_far = this.projectionTextureLightFar;
  50202. var light_near = this.projectionTextureLightNear;
  50203. var P = light_far / (light_far - light_near);
  50204. var Q = -P * light_near;
  50205. var S = 1.0 / Math.tan(this._angle / 2.0);
  50206. var A = 1.0;
  50207. 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);
  50208. };
  50209. /**
  50210. * Main function for light texture projection matrix computing.
  50211. */
  50212. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50213. this._projectionTextureDirty = false;
  50214. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50215. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50216. };
  50217. SpotLight.prototype._buildUniformLayout = function () {
  50218. this._uniformBuffer.addUniform("vLightData", 4);
  50219. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50220. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50221. this._uniformBuffer.addUniform("vLightDirection", 3);
  50222. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50223. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50224. this._uniformBuffer.addUniform("depthValues", 2);
  50225. this._uniformBuffer.create();
  50226. };
  50227. SpotLight.prototype._computeAngleValues = function () {
  50228. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  50229. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  50230. };
  50231. /**
  50232. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50233. * @param effect The effect to update
  50234. * @param lightIndex The index of the light in the effect to update
  50235. * @returns The spot light
  50236. */
  50237. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50238. var normalizeDirection;
  50239. if (this.computeTransformedInformation()) {
  50240. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50241. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50242. }
  50243. else {
  50244. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50245. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50246. }
  50247. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  50248. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  50249. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50250. if (this._projectionTextureViewLightDirty) {
  50251. this._computeProjectionTextureViewLightMatrix();
  50252. }
  50253. if (this._projectionTextureProjectionLightDirty) {
  50254. this._computeProjectionTextureProjectionLightMatrix();
  50255. }
  50256. if (this._projectionTextureDirty) {
  50257. this._computeProjectionTextureMatrix();
  50258. }
  50259. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50260. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50261. }
  50262. return this;
  50263. };
  50264. /**
  50265. * Disposes the light and the associated resources.
  50266. */
  50267. SpotLight.prototype.dispose = function () {
  50268. _super.prototype.dispose.call(this);
  50269. if (this._projectionTexture) {
  50270. this._projectionTexture.dispose();
  50271. }
  50272. };
  50273. /**
  50274. * Prepares the list of defines specific to the light type.
  50275. * @param defines the list of defines
  50276. * @param lightIndex defines the index of the light for the effect
  50277. */
  50278. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50279. defines["SPOTLIGHT" + lightIndex] = true;
  50280. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  50281. };
  50282. __decorate([
  50283. BABYLON.serialize()
  50284. ], SpotLight.prototype, "angle", null);
  50285. __decorate([
  50286. BABYLON.serialize()
  50287. ], SpotLight.prototype, "innerAngle", null);
  50288. __decorate([
  50289. BABYLON.serialize()
  50290. ], SpotLight.prototype, "shadowAngleScale", null);
  50291. __decorate([
  50292. BABYLON.serialize()
  50293. ], SpotLight.prototype, "exponent", void 0);
  50294. __decorate([
  50295. BABYLON.serialize()
  50296. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50297. __decorate([
  50298. BABYLON.serialize()
  50299. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50300. __decorate([
  50301. BABYLON.serialize()
  50302. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50303. __decorate([
  50304. BABYLON.serializeAsTexture("projectedLightTexture")
  50305. ], SpotLight.prototype, "_projectionTexture", void 0);
  50306. return SpotLight;
  50307. }(BABYLON.ShadowLight));
  50308. BABYLON.SpotLight = SpotLight;
  50309. })(BABYLON || (BABYLON = {}));
  50310. //# sourceMappingURL=babylon.spotLight.js.map
  50311. var BABYLON;
  50312. (function (BABYLON) {
  50313. /**
  50314. * Class used to override all child animations of a given target
  50315. */
  50316. var AnimationPropertiesOverride = /** @class */ (function () {
  50317. function AnimationPropertiesOverride() {
  50318. /**
  50319. * Gets or sets a value indicating if animation blending must be used
  50320. */
  50321. this.enableBlending = false;
  50322. /**
  50323. * Gets or sets the blending speed to use when enableBlending is true
  50324. */
  50325. this.blendingSpeed = 0.01;
  50326. /**
  50327. * Gets or sets the default loop mode to use
  50328. */
  50329. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50330. }
  50331. return AnimationPropertiesOverride;
  50332. }());
  50333. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50334. })(BABYLON || (BABYLON = {}));
  50335. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50336. var BABYLON;
  50337. (function (BABYLON) {
  50338. /**
  50339. * Represents the range of an animation
  50340. */
  50341. var AnimationRange = /** @class */ (function () {
  50342. /**
  50343. * Initializes the range of an animation
  50344. * @param name The name of the animation range
  50345. * @param from The starting frame of the animation
  50346. * @param to The ending frame of the animation
  50347. */
  50348. function AnimationRange(
  50349. /**The name of the animation range**/
  50350. name,
  50351. /**The starting frame of the animation */
  50352. from,
  50353. /**The ending frame of the animation*/
  50354. to) {
  50355. this.name = name;
  50356. this.from = from;
  50357. this.to = to;
  50358. }
  50359. /**
  50360. * Makes a copy of the animation range
  50361. * @returns A copy of the animation range
  50362. */
  50363. AnimationRange.prototype.clone = function () {
  50364. return new AnimationRange(this.name, this.from, this.to);
  50365. };
  50366. return AnimationRange;
  50367. }());
  50368. BABYLON.AnimationRange = AnimationRange;
  50369. /**
  50370. * Composed of a frame, and an action function
  50371. */
  50372. var AnimationEvent = /** @class */ (function () {
  50373. /**
  50374. * Initializes the animation event
  50375. * @param frame The frame for which the event is triggered
  50376. * @param action The event to perform when triggered
  50377. * @param onlyOnce Specifies if the event should be triggered only once
  50378. */
  50379. function AnimationEvent(
  50380. /** The frame for which the event is triggered **/
  50381. frame,
  50382. /** The event to perform when triggered **/
  50383. action,
  50384. /** Specifies if the event should be triggered only once**/
  50385. onlyOnce) {
  50386. this.frame = frame;
  50387. this.action = action;
  50388. this.onlyOnce = onlyOnce;
  50389. /**
  50390. * Specifies if the animation event is done
  50391. */
  50392. this.isDone = false;
  50393. }
  50394. /** @hidden */
  50395. AnimationEvent.prototype._clone = function () {
  50396. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50397. };
  50398. return AnimationEvent;
  50399. }());
  50400. BABYLON.AnimationEvent = AnimationEvent;
  50401. /**
  50402. * A cursor which tracks a point on a path
  50403. */
  50404. var PathCursor = /** @class */ (function () {
  50405. /**
  50406. * Initializes the path cursor
  50407. * @param path The path to track
  50408. */
  50409. function PathCursor(path) {
  50410. this.path = path;
  50411. /**
  50412. * Stores path cursor callbacks for when an onchange event is triggered
  50413. */
  50414. this._onchange = new Array();
  50415. /**
  50416. * The value of the path cursor
  50417. */
  50418. this.value = 0;
  50419. /**
  50420. * The animation array of the path cursor
  50421. */
  50422. this.animations = new Array();
  50423. }
  50424. /**
  50425. * Gets the cursor point on the path
  50426. * @returns A point on the path cursor at the cursor location
  50427. */
  50428. PathCursor.prototype.getPoint = function () {
  50429. var point = this.path.getPointAtLengthPosition(this.value);
  50430. return new BABYLON.Vector3(point.x, 0, point.y);
  50431. };
  50432. /**
  50433. * Moves the cursor ahead by the step amount
  50434. * @param step The amount to move the cursor forward
  50435. * @returns This path cursor
  50436. */
  50437. PathCursor.prototype.moveAhead = function (step) {
  50438. if (step === void 0) { step = 0.002; }
  50439. this.move(step);
  50440. return this;
  50441. };
  50442. /**
  50443. * Moves the cursor behind by the step amount
  50444. * @param step The amount to move the cursor back
  50445. * @returns This path cursor
  50446. */
  50447. PathCursor.prototype.moveBack = function (step) {
  50448. if (step === void 0) { step = 0.002; }
  50449. this.move(-step);
  50450. return this;
  50451. };
  50452. /**
  50453. * Moves the cursor by the step amount
  50454. * If the step amount is greater than one, an exception is thrown
  50455. * @param step The amount to move the cursor
  50456. * @returns This path cursor
  50457. */
  50458. PathCursor.prototype.move = function (step) {
  50459. if (Math.abs(step) > 1) {
  50460. throw "step size should be less than 1.";
  50461. }
  50462. this.value += step;
  50463. this.ensureLimits();
  50464. this.raiseOnChange();
  50465. return this;
  50466. };
  50467. /**
  50468. * Ensures that the value is limited between zero and one
  50469. * @returns This path cursor
  50470. */
  50471. PathCursor.prototype.ensureLimits = function () {
  50472. while (this.value > 1) {
  50473. this.value -= 1;
  50474. }
  50475. while (this.value < 0) {
  50476. this.value += 1;
  50477. }
  50478. return this;
  50479. };
  50480. /**
  50481. * Runs onchange callbacks on change (used by the animation engine)
  50482. * @returns This path cursor
  50483. */
  50484. PathCursor.prototype.raiseOnChange = function () {
  50485. var _this = this;
  50486. this._onchange.forEach(function (f) { return f(_this); });
  50487. return this;
  50488. };
  50489. /**
  50490. * Executes a function on change
  50491. * @param f A path cursor onchange callback
  50492. * @returns This path cursor
  50493. */
  50494. PathCursor.prototype.onchange = function (f) {
  50495. this._onchange.push(f);
  50496. return this;
  50497. };
  50498. return PathCursor;
  50499. }());
  50500. BABYLON.PathCursor = PathCursor;
  50501. /**
  50502. * Enum for the animation key frame interpolation type
  50503. */
  50504. var AnimationKeyInterpolation;
  50505. (function (AnimationKeyInterpolation) {
  50506. /**
  50507. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50508. */
  50509. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50510. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50511. /**
  50512. * Class used to store any kind of animation
  50513. */
  50514. var Animation = /** @class */ (function () {
  50515. /**
  50516. * Initializes the animation
  50517. * @param name Name of the animation
  50518. * @param targetProperty Property to animate
  50519. * @param framePerSecond The frames per second of the animation
  50520. * @param dataType The data type of the animation
  50521. * @param loopMode The loop mode of the animation
  50522. * @param enableBlendings Specifies if blending should be enabled
  50523. */
  50524. function Animation(
  50525. /**Name of the animation */
  50526. name,
  50527. /**Property to animate */
  50528. targetProperty,
  50529. /**The frames per second of the animation */
  50530. framePerSecond,
  50531. /**The data type of the animation */
  50532. dataType,
  50533. /**The loop mode of the animation */
  50534. loopMode,
  50535. /**Specifies if blending should be enabled */
  50536. enableBlending) {
  50537. this.name = name;
  50538. this.targetProperty = targetProperty;
  50539. this.framePerSecond = framePerSecond;
  50540. this.dataType = dataType;
  50541. this.loopMode = loopMode;
  50542. this.enableBlending = enableBlending;
  50543. /**
  50544. * @hidden Internal use only
  50545. */
  50546. this._runtimeAnimations = new Array();
  50547. /**
  50548. * The set of event that will be linked to this animation
  50549. */
  50550. this._events = new Array();
  50551. /**
  50552. * Stores the blending speed of the animation
  50553. */
  50554. this.blendingSpeed = 0.01;
  50555. /**
  50556. * Stores the animation ranges for the animation
  50557. */
  50558. this._ranges = {};
  50559. this.targetPropertyPath = targetProperty.split(".");
  50560. this.dataType = dataType;
  50561. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50562. }
  50563. /**
  50564. * @hidden Internal use
  50565. */
  50566. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50567. var dataType = undefined;
  50568. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50569. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50570. }
  50571. else if (from instanceof BABYLON.Quaternion) {
  50572. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50573. }
  50574. else if (from instanceof BABYLON.Vector3) {
  50575. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50576. }
  50577. else if (from instanceof BABYLON.Vector2) {
  50578. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50579. }
  50580. else if (from instanceof BABYLON.Color3) {
  50581. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50582. }
  50583. else if (from instanceof BABYLON.Size) {
  50584. dataType = Animation.ANIMATIONTYPE_SIZE;
  50585. }
  50586. if (dataType == undefined) {
  50587. return null;
  50588. }
  50589. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50590. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50591. animation.setKeys(keys);
  50592. if (easingFunction !== undefined) {
  50593. animation.setEasingFunction(easingFunction);
  50594. }
  50595. return animation;
  50596. };
  50597. /**
  50598. * Sets up an animation
  50599. * @param property The property to animate
  50600. * @param animationType The animation type to apply
  50601. * @param framePerSecond The frames per second of the animation
  50602. * @param easingFunction The easing function used in the animation
  50603. * @returns The created animation
  50604. */
  50605. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50606. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50607. animation.setEasingFunction(easingFunction);
  50608. return animation;
  50609. };
  50610. /**
  50611. * Create and start an animation on a node
  50612. * @param name defines the name of the global animation that will be run on all nodes
  50613. * @param node defines the root node where the animation will take place
  50614. * @param targetProperty defines property to animate
  50615. * @param framePerSecond defines the number of frame per second yo use
  50616. * @param totalFrame defines the number of frames in total
  50617. * @param from defines the initial value
  50618. * @param to defines the final value
  50619. * @param loopMode defines which loop mode you want to use (off by default)
  50620. * @param easingFunction defines the easing function to use (linear by default)
  50621. * @param onAnimationEnd defines the callback to call when animation end
  50622. * @returns the animatable created for this animation
  50623. */
  50624. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50625. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50626. if (!animation) {
  50627. return null;
  50628. }
  50629. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50630. };
  50631. /**
  50632. * Create and start an animation on a node and its descendants
  50633. * @param name defines the name of the global animation that will be run on all nodes
  50634. * @param node defines the root node where the animation will take place
  50635. * @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
  50636. * @param targetProperty defines property to animate
  50637. * @param framePerSecond defines the number of frame per second to use
  50638. * @param totalFrame defines the number of frames in total
  50639. * @param from defines the initial value
  50640. * @param to defines the final value
  50641. * @param loopMode defines which loop mode you want to use (off by default)
  50642. * @param easingFunction defines the easing function to use (linear by default)
  50643. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50644. * @returns the list of animatables created for all nodes
  50645. * @example https://www.babylonjs-playground.com/#MH0VLI
  50646. */
  50647. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50648. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50649. if (!animation) {
  50650. return null;
  50651. }
  50652. var scene = node.getScene();
  50653. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50654. };
  50655. /**
  50656. * Creates a new animation, merges it with the existing animations and starts it
  50657. * @param name Name of the animation
  50658. * @param node Node which contains the scene that begins the animations
  50659. * @param targetProperty Specifies which property to animate
  50660. * @param framePerSecond The frames per second of the animation
  50661. * @param totalFrame The total number of frames
  50662. * @param from The frame at the beginning of the animation
  50663. * @param to The frame at the end of the animation
  50664. * @param loopMode Specifies the loop mode of the animation
  50665. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50666. * @param onAnimationEnd Callback to run once the animation is complete
  50667. * @returns Nullable animation
  50668. */
  50669. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50670. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50671. if (!animation) {
  50672. return null;
  50673. }
  50674. node.animations.push(animation);
  50675. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50676. };
  50677. /**
  50678. * Transition property of an host to the target Value
  50679. * @param property The property to transition
  50680. * @param targetValue The target Value of the property
  50681. * @param host The object where the property to animate belongs
  50682. * @param scene Scene used to run the animation
  50683. * @param frameRate Framerate (in frame/s) to use
  50684. * @param transition The transition type we want to use
  50685. * @param duration The duration of the animation, in milliseconds
  50686. * @param onAnimationEnd Callback trigger at the end of the animation
  50687. * @returns Nullable animation
  50688. */
  50689. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50690. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50691. if (duration <= 0) {
  50692. host[property] = targetValue;
  50693. if (onAnimationEnd) {
  50694. onAnimationEnd();
  50695. }
  50696. return null;
  50697. }
  50698. var endFrame = frameRate * (duration / 1000);
  50699. transition.setKeys([{
  50700. frame: 0,
  50701. value: host[property].clone ? host[property].clone() : host[property]
  50702. },
  50703. {
  50704. frame: endFrame,
  50705. value: targetValue
  50706. }]);
  50707. if (!host.animations) {
  50708. host.animations = [];
  50709. }
  50710. host.animations.push(transition);
  50711. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50712. animation.onAnimationEnd = onAnimationEnd;
  50713. return animation;
  50714. };
  50715. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50716. /**
  50717. * Return the array of runtime animations currently using this animation
  50718. */
  50719. get: function () {
  50720. return this._runtimeAnimations;
  50721. },
  50722. enumerable: true,
  50723. configurable: true
  50724. });
  50725. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50726. /**
  50727. * Specifies if any of the runtime animations are currently running
  50728. */
  50729. get: function () {
  50730. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50731. var runtimeAnimation = _a[_i];
  50732. if (!runtimeAnimation.isStopped) {
  50733. return true;
  50734. }
  50735. }
  50736. return false;
  50737. },
  50738. enumerable: true,
  50739. configurable: true
  50740. });
  50741. // Methods
  50742. /**
  50743. * Converts the animation to a string
  50744. * @param fullDetails support for multiple levels of logging within scene loading
  50745. * @returns String form of the animation
  50746. */
  50747. Animation.prototype.toString = function (fullDetails) {
  50748. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50749. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50750. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50751. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50752. if (fullDetails) {
  50753. ret += ", Ranges: {";
  50754. var first = true;
  50755. for (var name in this._ranges) {
  50756. if (first) {
  50757. ret += ", ";
  50758. first = false;
  50759. }
  50760. ret += name;
  50761. }
  50762. ret += "}";
  50763. }
  50764. return ret;
  50765. };
  50766. /**
  50767. * Add an event to this animation
  50768. * @param event Event to add
  50769. */
  50770. Animation.prototype.addEvent = function (event) {
  50771. this._events.push(event);
  50772. };
  50773. /**
  50774. * Remove all events found at the given frame
  50775. * @param frame The frame to remove events from
  50776. */
  50777. Animation.prototype.removeEvents = function (frame) {
  50778. for (var index = 0; index < this._events.length; index++) {
  50779. if (this._events[index].frame === frame) {
  50780. this._events.splice(index, 1);
  50781. index--;
  50782. }
  50783. }
  50784. };
  50785. /**
  50786. * Retrieves all the events from the animation
  50787. * @returns Events from the animation
  50788. */
  50789. Animation.prototype.getEvents = function () {
  50790. return this._events;
  50791. };
  50792. /**
  50793. * Creates an animation range
  50794. * @param name Name of the animation range
  50795. * @param from Starting frame of the animation range
  50796. * @param to Ending frame of the animation
  50797. */
  50798. Animation.prototype.createRange = function (name, from, to) {
  50799. // check name not already in use; could happen for bones after serialized
  50800. if (!this._ranges[name]) {
  50801. this._ranges[name] = new AnimationRange(name, from, to);
  50802. }
  50803. };
  50804. /**
  50805. * Deletes an animation range by name
  50806. * @param name Name of the animation range to delete
  50807. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50808. */
  50809. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50810. if (deleteFrames === void 0) { deleteFrames = true; }
  50811. var range = this._ranges[name];
  50812. if (!range) {
  50813. return;
  50814. }
  50815. if (deleteFrames) {
  50816. var from = range.from;
  50817. var to = range.to;
  50818. // this loop MUST go high to low for multiple splices to work
  50819. for (var key = this._keys.length - 1; key >= 0; key--) {
  50820. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50821. this._keys.splice(key, 1);
  50822. }
  50823. }
  50824. }
  50825. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50826. };
  50827. /**
  50828. * Gets the animation range by name, or null if not defined
  50829. * @param name Name of the animation range
  50830. * @returns Nullable animation range
  50831. */
  50832. Animation.prototype.getRange = function (name) {
  50833. return this._ranges[name];
  50834. };
  50835. /**
  50836. * Gets the key frames from the animation
  50837. * @returns The key frames of the animation
  50838. */
  50839. Animation.prototype.getKeys = function () {
  50840. return this._keys;
  50841. };
  50842. /**
  50843. * Gets the highest frame rate of the animation
  50844. * @returns Highest frame rate of the animation
  50845. */
  50846. Animation.prototype.getHighestFrame = function () {
  50847. var ret = 0;
  50848. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50849. if (ret < this._keys[key].frame) {
  50850. ret = this._keys[key].frame;
  50851. }
  50852. }
  50853. return ret;
  50854. };
  50855. /**
  50856. * Gets the easing function of the animation
  50857. * @returns Easing function of the animation
  50858. */
  50859. Animation.prototype.getEasingFunction = function () {
  50860. return this._easingFunction;
  50861. };
  50862. /**
  50863. * Sets the easing function of the animation
  50864. * @param easingFunction A custom mathematical formula for animation
  50865. */
  50866. Animation.prototype.setEasingFunction = function (easingFunction) {
  50867. this._easingFunction = easingFunction;
  50868. };
  50869. /**
  50870. * Interpolates a scalar linearly
  50871. * @param startValue Start value of the animation curve
  50872. * @param endValue End value of the animation curve
  50873. * @param gradient Scalar amount to interpolate
  50874. * @returns Interpolated scalar value
  50875. */
  50876. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50877. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50878. };
  50879. /**
  50880. * Interpolates a scalar cubically
  50881. * @param startValue Start value of the animation curve
  50882. * @param outTangent End tangent of the animation
  50883. * @param endValue End value of the animation curve
  50884. * @param inTangent Start tangent of the animation curve
  50885. * @param gradient Scalar amount to interpolate
  50886. * @returns Interpolated scalar value
  50887. */
  50888. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50889. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50890. };
  50891. /**
  50892. * Interpolates a quaternion using a spherical linear interpolation
  50893. * @param startValue Start value of the animation curve
  50894. * @param endValue End value of the animation curve
  50895. * @param gradient Scalar amount to interpolate
  50896. * @returns Interpolated quaternion value
  50897. */
  50898. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50899. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50900. };
  50901. /**
  50902. * Interpolates a quaternion cubically
  50903. * @param startValue Start value of the animation curve
  50904. * @param outTangent End tangent of the animation curve
  50905. * @param endValue End value of the animation curve
  50906. * @param inTangent Start tangent of the animation curve
  50907. * @param gradient Scalar amount to interpolate
  50908. * @returns Interpolated quaternion value
  50909. */
  50910. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50911. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50912. };
  50913. /**
  50914. * Interpolates a Vector3 linearl
  50915. * @param startValue Start value of the animation curve
  50916. * @param endValue End value of the animation curve
  50917. * @param gradient Scalar amount to interpolate
  50918. * @returns Interpolated scalar value
  50919. */
  50920. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50921. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50922. };
  50923. /**
  50924. * Interpolates a Vector3 cubically
  50925. * @param startValue Start value of the animation curve
  50926. * @param outTangent End tangent of the animation
  50927. * @param endValue End value of the animation curve
  50928. * @param inTangent Start tangent of the animation curve
  50929. * @param gradient Scalar amount to interpolate
  50930. * @returns InterpolatedVector3 value
  50931. */
  50932. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50933. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50934. };
  50935. /**
  50936. * Interpolates a Vector2 linearly
  50937. * @param startValue Start value of the animation curve
  50938. * @param endValue End value of the animation curve
  50939. * @param gradient Scalar amount to interpolate
  50940. * @returns Interpolated Vector2 value
  50941. */
  50942. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50943. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50944. };
  50945. /**
  50946. * Interpolates a Vector2 cubically
  50947. * @param startValue Start value of the animation curve
  50948. * @param outTangent End tangent of the animation
  50949. * @param endValue End value of the animation curve
  50950. * @param inTangent Start tangent of the animation curve
  50951. * @param gradient Scalar amount to interpolate
  50952. * @returns Interpolated Vector2 value
  50953. */
  50954. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50955. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50956. };
  50957. /**
  50958. * Interpolates a size linearly
  50959. * @param startValue Start value of the animation curve
  50960. * @param endValue End value of the animation curve
  50961. * @param gradient Scalar amount to interpolate
  50962. * @returns Interpolated Size value
  50963. */
  50964. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50965. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50966. };
  50967. /**
  50968. * Interpolates a Color3 linearly
  50969. * @param startValue Start value of the animation curve
  50970. * @param endValue End value of the animation curve
  50971. * @param gradient Scalar amount to interpolate
  50972. * @returns Interpolated Color3 value
  50973. */
  50974. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50975. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50976. };
  50977. /**
  50978. * @hidden Internal use only
  50979. */
  50980. Animation.prototype._getKeyValue = function (value) {
  50981. if (typeof value === "function") {
  50982. return value();
  50983. }
  50984. return value;
  50985. };
  50986. /**
  50987. * @hidden Internal use only
  50988. */
  50989. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50990. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50991. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50992. }
  50993. var keys = this.getKeys();
  50994. // Try to get a hash to find the right key
  50995. 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));
  50996. if (keys[startKeyIndex].frame >= currentFrame) {
  50997. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50998. startKeyIndex--;
  50999. }
  51000. }
  51001. for (var key = startKeyIndex; key < keys.length; key++) {
  51002. var endKey = keys[key + 1];
  51003. if (endKey.frame >= currentFrame) {
  51004. var startKey = keys[key];
  51005. var startValue = this._getKeyValue(startKey.value);
  51006. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51007. return startValue;
  51008. }
  51009. var endValue = this._getKeyValue(endKey.value);
  51010. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51011. var frameDelta = endKey.frame - startKey.frame;
  51012. // gradient : percent of currentFrame between the frame inf and the frame sup
  51013. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51014. // check for easingFunction and correction of gradient
  51015. var easingFunction = this.getEasingFunction();
  51016. if (easingFunction != null) {
  51017. gradient = easingFunction.ease(gradient);
  51018. }
  51019. switch (this.dataType) {
  51020. // Float
  51021. case Animation.ANIMATIONTYPE_FLOAT:
  51022. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51023. switch (loopMode) {
  51024. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51025. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51026. return floatValue;
  51027. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51028. return offsetValue * repeatCount + floatValue;
  51029. }
  51030. break;
  51031. // Quaternion
  51032. case Animation.ANIMATIONTYPE_QUATERNION:
  51033. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51034. switch (loopMode) {
  51035. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51036. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51037. return quatValue;
  51038. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51039. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51040. }
  51041. return quatValue;
  51042. // Vector3
  51043. case Animation.ANIMATIONTYPE_VECTOR3:
  51044. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51045. switch (loopMode) {
  51046. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51047. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51048. return vec3Value;
  51049. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51050. return vec3Value.add(offsetValue.scale(repeatCount));
  51051. }
  51052. // Vector2
  51053. case Animation.ANIMATIONTYPE_VECTOR2:
  51054. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51055. switch (loopMode) {
  51056. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51057. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51058. return vec2Value;
  51059. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51060. return vec2Value.add(offsetValue.scale(repeatCount));
  51061. }
  51062. // Size
  51063. case Animation.ANIMATIONTYPE_SIZE:
  51064. switch (loopMode) {
  51065. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51066. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51067. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51068. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51069. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51070. }
  51071. // Color3
  51072. case Animation.ANIMATIONTYPE_COLOR3:
  51073. switch (loopMode) {
  51074. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51075. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51076. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51077. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51078. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51079. }
  51080. // Matrix
  51081. case Animation.ANIMATIONTYPE_MATRIX:
  51082. switch (loopMode) {
  51083. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51084. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51085. if (Animation.AllowMatricesInterpolation) {
  51086. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51087. }
  51088. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51089. return startValue;
  51090. }
  51091. default:
  51092. break;
  51093. }
  51094. break;
  51095. }
  51096. }
  51097. return this._getKeyValue(keys[keys.length - 1].value);
  51098. };
  51099. /**
  51100. * Defines the function to use to interpolate matrices
  51101. * @param startValue defines the start matrix
  51102. * @param endValue defines the end matrix
  51103. * @param gradient defines the gradient between both matrices
  51104. * @param result defines an optional target matrix where to store the interpolation
  51105. * @returns the interpolated matrix
  51106. */
  51107. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51108. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51109. if (result) {
  51110. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51111. return result;
  51112. }
  51113. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51114. }
  51115. if (result) {
  51116. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51117. return result;
  51118. }
  51119. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51120. };
  51121. /**
  51122. * Makes a copy of the animation
  51123. * @returns Cloned animation
  51124. */
  51125. Animation.prototype.clone = function () {
  51126. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51127. clone.enableBlending = this.enableBlending;
  51128. clone.blendingSpeed = this.blendingSpeed;
  51129. if (this._keys) {
  51130. clone.setKeys(this._keys);
  51131. }
  51132. if (this._ranges) {
  51133. clone._ranges = {};
  51134. for (var name in this._ranges) {
  51135. var range = this._ranges[name];
  51136. if (!range) {
  51137. continue;
  51138. }
  51139. clone._ranges[name] = range.clone();
  51140. }
  51141. }
  51142. return clone;
  51143. };
  51144. /**
  51145. * Sets the key frames of the animation
  51146. * @param values The animation key frames to set
  51147. */
  51148. Animation.prototype.setKeys = function (values) {
  51149. this._keys = values.slice(0);
  51150. };
  51151. /**
  51152. * Serializes the animation to an object
  51153. * @returns Serialized object
  51154. */
  51155. Animation.prototype.serialize = function () {
  51156. var serializationObject = {};
  51157. serializationObject.name = this.name;
  51158. serializationObject.property = this.targetProperty;
  51159. serializationObject.framePerSecond = this.framePerSecond;
  51160. serializationObject.dataType = this.dataType;
  51161. serializationObject.loopBehavior = this.loopMode;
  51162. serializationObject.enableBlending = this.enableBlending;
  51163. serializationObject.blendingSpeed = this.blendingSpeed;
  51164. var dataType = this.dataType;
  51165. serializationObject.keys = [];
  51166. var keys = this.getKeys();
  51167. for (var index = 0; index < keys.length; index++) {
  51168. var animationKey = keys[index];
  51169. var key = {};
  51170. key.frame = animationKey.frame;
  51171. switch (dataType) {
  51172. case Animation.ANIMATIONTYPE_FLOAT:
  51173. key.values = [animationKey.value];
  51174. break;
  51175. case Animation.ANIMATIONTYPE_QUATERNION:
  51176. case Animation.ANIMATIONTYPE_MATRIX:
  51177. case Animation.ANIMATIONTYPE_VECTOR3:
  51178. case Animation.ANIMATIONTYPE_COLOR3:
  51179. key.values = animationKey.value.asArray();
  51180. break;
  51181. }
  51182. serializationObject.keys.push(key);
  51183. }
  51184. serializationObject.ranges = [];
  51185. for (var name in this._ranges) {
  51186. var source = this._ranges[name];
  51187. if (!source) {
  51188. continue;
  51189. }
  51190. var range = {};
  51191. range.name = name;
  51192. range.from = source.from;
  51193. range.to = source.to;
  51194. serializationObject.ranges.push(range);
  51195. }
  51196. return serializationObject;
  51197. };
  51198. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51199. /**
  51200. * Get the float animation type
  51201. */
  51202. get: function () {
  51203. return Animation._ANIMATIONTYPE_FLOAT;
  51204. },
  51205. enumerable: true,
  51206. configurable: true
  51207. });
  51208. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51209. /**
  51210. * Get the Vector3 animation type
  51211. */
  51212. get: function () {
  51213. return Animation._ANIMATIONTYPE_VECTOR3;
  51214. },
  51215. enumerable: true,
  51216. configurable: true
  51217. });
  51218. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51219. /**
  51220. * Get the Vector2 animation type
  51221. */
  51222. get: function () {
  51223. return Animation._ANIMATIONTYPE_VECTOR2;
  51224. },
  51225. enumerable: true,
  51226. configurable: true
  51227. });
  51228. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51229. /**
  51230. * Get the Size animation type
  51231. */
  51232. get: function () {
  51233. return Animation._ANIMATIONTYPE_SIZE;
  51234. },
  51235. enumerable: true,
  51236. configurable: true
  51237. });
  51238. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51239. /**
  51240. * Get the Quaternion animation type
  51241. */
  51242. get: function () {
  51243. return Animation._ANIMATIONTYPE_QUATERNION;
  51244. },
  51245. enumerable: true,
  51246. configurable: true
  51247. });
  51248. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51249. /**
  51250. * Get the Matrix animation type
  51251. */
  51252. get: function () {
  51253. return Animation._ANIMATIONTYPE_MATRIX;
  51254. },
  51255. enumerable: true,
  51256. configurable: true
  51257. });
  51258. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51259. /**
  51260. * Get the Color3 animation type
  51261. */
  51262. get: function () {
  51263. return Animation._ANIMATIONTYPE_COLOR3;
  51264. },
  51265. enumerable: true,
  51266. configurable: true
  51267. });
  51268. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51269. /**
  51270. * Get the Relative Loop Mode
  51271. */
  51272. get: function () {
  51273. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51274. },
  51275. enumerable: true,
  51276. configurable: true
  51277. });
  51278. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51279. /**
  51280. * Get the Cycle Loop Mode
  51281. */
  51282. get: function () {
  51283. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51284. },
  51285. enumerable: true,
  51286. configurable: true
  51287. });
  51288. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51289. /**
  51290. * Get the Constant Loop Mode
  51291. */
  51292. get: function () {
  51293. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51294. },
  51295. enumerable: true,
  51296. configurable: true
  51297. });
  51298. /** @hidden */
  51299. Animation._UniversalLerp = function (left, right, amount) {
  51300. var constructor = left.constructor;
  51301. if (constructor.Lerp) { // Lerp supported
  51302. return constructor.Lerp(left, right, amount);
  51303. }
  51304. else if (constructor.Slerp) { // Slerp supported
  51305. return constructor.Slerp(left, right, amount);
  51306. }
  51307. else if (left.toFixed) { // Number
  51308. return left * (1.0 - amount) + amount * right;
  51309. }
  51310. else { // Blending not supported
  51311. return right;
  51312. }
  51313. };
  51314. /**
  51315. * Parses an animation object and creates an animation
  51316. * @param parsedAnimation Parsed animation object
  51317. * @returns Animation object
  51318. */
  51319. Animation.Parse = function (parsedAnimation) {
  51320. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51321. var dataType = parsedAnimation.dataType;
  51322. var keys = [];
  51323. var data;
  51324. var index;
  51325. if (parsedAnimation.enableBlending) {
  51326. animation.enableBlending = parsedAnimation.enableBlending;
  51327. }
  51328. if (parsedAnimation.blendingSpeed) {
  51329. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51330. }
  51331. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51332. var key = parsedAnimation.keys[index];
  51333. var inTangent;
  51334. var outTangent;
  51335. switch (dataType) {
  51336. case Animation.ANIMATIONTYPE_FLOAT:
  51337. data = key.values[0];
  51338. if (key.values.length >= 1) {
  51339. inTangent = key.values[1];
  51340. }
  51341. if (key.values.length >= 2) {
  51342. outTangent = key.values[2];
  51343. }
  51344. break;
  51345. case Animation.ANIMATIONTYPE_QUATERNION:
  51346. data = BABYLON.Quaternion.FromArray(key.values);
  51347. if (key.values.length >= 8) {
  51348. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51349. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51350. inTangent = _inTangent;
  51351. }
  51352. }
  51353. if (key.values.length >= 12) {
  51354. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51355. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51356. outTangent = _outTangent;
  51357. }
  51358. }
  51359. break;
  51360. case Animation.ANIMATIONTYPE_MATRIX:
  51361. data = BABYLON.Matrix.FromArray(key.values);
  51362. break;
  51363. case Animation.ANIMATIONTYPE_COLOR3:
  51364. data = BABYLON.Color3.FromArray(key.values);
  51365. break;
  51366. case Animation.ANIMATIONTYPE_VECTOR3:
  51367. default:
  51368. data = BABYLON.Vector3.FromArray(key.values);
  51369. break;
  51370. }
  51371. var keyData = {};
  51372. keyData.frame = key.frame;
  51373. keyData.value = data;
  51374. if (inTangent != undefined) {
  51375. keyData.inTangent = inTangent;
  51376. }
  51377. if (outTangent != undefined) {
  51378. keyData.outTangent = outTangent;
  51379. }
  51380. keys.push(keyData);
  51381. }
  51382. animation.setKeys(keys);
  51383. if (parsedAnimation.ranges) {
  51384. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51385. data = parsedAnimation.ranges[index];
  51386. animation.createRange(data.name, data.from, data.to);
  51387. }
  51388. }
  51389. return animation;
  51390. };
  51391. /**
  51392. * Appends the serialized animations from the source animations
  51393. * @param source Source containing the animations
  51394. * @param destination Target to store the animations
  51395. */
  51396. Animation.AppendSerializedAnimations = function (source, destination) {
  51397. if (source.animations) {
  51398. destination.animations = [];
  51399. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51400. var animation = source.animations[animationIndex];
  51401. destination.animations.push(animation.serialize());
  51402. }
  51403. }
  51404. };
  51405. /**
  51406. * Use matrix interpolation instead of using direct key value when animating matrices
  51407. */
  51408. Animation.AllowMatricesInterpolation = false;
  51409. /**
  51410. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51411. */
  51412. Animation.AllowMatrixDecomposeForInterpolation = true;
  51413. // Statics
  51414. /**
  51415. * Float animation type
  51416. */
  51417. Animation._ANIMATIONTYPE_FLOAT = 0;
  51418. /**
  51419. * Vector3 animation type
  51420. */
  51421. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51422. /**
  51423. * Quaternion animation type
  51424. */
  51425. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51426. /**
  51427. * Matrix animation type
  51428. */
  51429. Animation._ANIMATIONTYPE_MATRIX = 3;
  51430. /**
  51431. * Color3 animation type
  51432. */
  51433. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51434. /**
  51435. * Vector2 animation type
  51436. */
  51437. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51438. /**
  51439. * Size animation type
  51440. */
  51441. Animation._ANIMATIONTYPE_SIZE = 6;
  51442. /**
  51443. * Relative Loop Mode
  51444. */
  51445. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51446. /**
  51447. * Cycle Loop Mode
  51448. */
  51449. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51450. /**
  51451. * Constant Loop Mode
  51452. */
  51453. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51454. return Animation;
  51455. }());
  51456. BABYLON.Animation = Animation;
  51457. })(BABYLON || (BABYLON = {}));
  51458. //# sourceMappingURL=babylon.animation.js.map
  51459. var BABYLON;
  51460. (function (BABYLON) {
  51461. /**
  51462. * This class defines the direct association between an animation and a target
  51463. */
  51464. var TargetedAnimation = /** @class */ (function () {
  51465. function TargetedAnimation() {
  51466. }
  51467. return TargetedAnimation;
  51468. }());
  51469. BABYLON.TargetedAnimation = TargetedAnimation;
  51470. /**
  51471. * Use this class to create coordinated animations on multiple targets
  51472. */
  51473. var AnimationGroup = /** @class */ (function () {
  51474. /**
  51475. * Instantiates a new Animation Group.
  51476. * This helps managing several animations at once.
  51477. * @see http://doc.babylonjs.com/how_to/group
  51478. * @param name Defines the name of the group
  51479. * @param scene Defines the scene the group belongs to
  51480. */
  51481. function AnimationGroup(
  51482. /** The name of the animation group */
  51483. name, scene) {
  51484. if (scene === void 0) { scene = null; }
  51485. this.name = name;
  51486. this._targetedAnimations = new Array();
  51487. this._animatables = new Array();
  51488. this._from = Number.MAX_VALUE;
  51489. this._to = -Number.MAX_VALUE;
  51490. this._speedRatio = 1;
  51491. /**
  51492. * This observable will notify when one animation have ended.
  51493. */
  51494. this.onAnimationEndObservable = new BABYLON.Observable();
  51495. /**
  51496. * This observable will notify when all animations have ended.
  51497. */
  51498. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51499. /**
  51500. * This observable will notify when all animations have paused.
  51501. */
  51502. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  51503. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51504. this._scene.animationGroups.push(this);
  51505. }
  51506. Object.defineProperty(AnimationGroup.prototype, "from", {
  51507. /**
  51508. * Gets the first frame
  51509. */
  51510. get: function () {
  51511. return this._from;
  51512. },
  51513. enumerable: true,
  51514. configurable: true
  51515. });
  51516. Object.defineProperty(AnimationGroup.prototype, "to", {
  51517. /**
  51518. * Gets the last frame
  51519. */
  51520. get: function () {
  51521. return this._to;
  51522. },
  51523. enumerable: true,
  51524. configurable: true
  51525. });
  51526. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51527. /**
  51528. * Define if the animations are started
  51529. */
  51530. get: function () {
  51531. return this._isStarted;
  51532. },
  51533. enumerable: true,
  51534. configurable: true
  51535. });
  51536. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51537. /**
  51538. * Gets or sets the speed ratio to use for all animations
  51539. */
  51540. get: function () {
  51541. return this._speedRatio;
  51542. },
  51543. /**
  51544. * Gets or sets the speed ratio to use for all animations
  51545. */
  51546. set: function (value) {
  51547. if (this._speedRatio === value) {
  51548. return;
  51549. }
  51550. this._speedRatio = value;
  51551. for (var index = 0; index < this._animatables.length; index++) {
  51552. var animatable = this._animatables[index];
  51553. animatable.speedRatio = this._speedRatio;
  51554. }
  51555. },
  51556. enumerable: true,
  51557. configurable: true
  51558. });
  51559. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51560. /**
  51561. * Gets the targeted animations for this animation group
  51562. */
  51563. get: function () {
  51564. return this._targetedAnimations;
  51565. },
  51566. enumerable: true,
  51567. configurable: true
  51568. });
  51569. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51570. /**
  51571. * returning the list of animatables controlled by this animation group.
  51572. */
  51573. get: function () {
  51574. return this._animatables;
  51575. },
  51576. enumerable: true,
  51577. configurable: true
  51578. });
  51579. /**
  51580. * Add an animation (with its target) in the group
  51581. * @param animation defines the animation we want to add
  51582. * @param target defines the target of the animation
  51583. * @returns the {BABYLON.TargetedAnimation} object
  51584. */
  51585. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51586. var targetedAnimation = {
  51587. animation: animation,
  51588. target: target
  51589. };
  51590. var keys = animation.getKeys();
  51591. if (this._from > keys[0].frame) {
  51592. this._from = keys[0].frame;
  51593. }
  51594. if (this._to < keys[keys.length - 1].frame) {
  51595. this._to = keys[keys.length - 1].frame;
  51596. }
  51597. this._targetedAnimations.push(targetedAnimation);
  51598. return targetedAnimation;
  51599. };
  51600. /**
  51601. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51602. * It can add constant keys at begin or end
  51603. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51604. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51605. * @returns the animation group
  51606. */
  51607. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51608. if (beginFrame === void 0) { beginFrame = null; }
  51609. if (endFrame === void 0) { endFrame = null; }
  51610. if (beginFrame == null)
  51611. beginFrame = this._from;
  51612. if (endFrame == null)
  51613. endFrame = this._to;
  51614. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51615. var targetedAnimation = this._targetedAnimations[index];
  51616. var keys = targetedAnimation.animation.getKeys();
  51617. var startKey = keys[0];
  51618. var endKey = keys[keys.length - 1];
  51619. if (startKey.frame > beginFrame) {
  51620. var newKey = {
  51621. frame: beginFrame,
  51622. value: startKey.value,
  51623. inTangent: startKey.inTangent,
  51624. outTangent: startKey.outTangent,
  51625. interpolation: startKey.interpolation
  51626. };
  51627. keys.splice(0, 0, newKey);
  51628. }
  51629. if (endKey.frame < endFrame) {
  51630. var newKey = {
  51631. frame: endFrame,
  51632. value: endKey.value,
  51633. inTangent: endKey.outTangent,
  51634. outTangent: endKey.outTangent,
  51635. interpolation: endKey.interpolation
  51636. };
  51637. keys.push(newKey);
  51638. }
  51639. }
  51640. this._from = beginFrame;
  51641. this._to = endFrame;
  51642. return this;
  51643. };
  51644. /**
  51645. * Start all animations on given targets
  51646. * @param loop defines if animations must loop
  51647. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51648. * @param from defines the from key (optional)
  51649. * @param to defines the to key (optional)
  51650. * @returns the current animation group
  51651. */
  51652. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51653. var _this = this;
  51654. if (loop === void 0) { loop = false; }
  51655. if (speedRatio === void 0) { speedRatio = 1; }
  51656. if (this._isStarted || this._targetedAnimations.length === 0) {
  51657. return this;
  51658. }
  51659. var _loop_1 = function (targetedAnimation) {
  51660. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51661. animatable.onAnimationEnd = function () {
  51662. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51663. _this._checkAnimationGroupEnded(animatable);
  51664. };
  51665. this_1._animatables.push(animatable);
  51666. };
  51667. var this_1 = this;
  51668. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51669. var targetedAnimation = _a[_i];
  51670. _loop_1(targetedAnimation);
  51671. }
  51672. this._speedRatio = speedRatio;
  51673. this._isStarted = true;
  51674. return this;
  51675. };
  51676. /**
  51677. * Pause all animations
  51678. * @returns the animation group
  51679. */
  51680. AnimationGroup.prototype.pause = function () {
  51681. if (!this._isStarted) {
  51682. return this;
  51683. }
  51684. for (var index = 0; index < this._animatables.length; index++) {
  51685. var animatable = this._animatables[index];
  51686. animatable.pause();
  51687. }
  51688. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51689. return this;
  51690. };
  51691. /**
  51692. * Play all animations to initial state
  51693. * This function will start() the animations if they were not started or will restart() them if they were paused
  51694. * @param loop defines if animations must loop
  51695. * @returns the animation group
  51696. */
  51697. AnimationGroup.prototype.play = function (loop) {
  51698. // only if all animatables are ready and exist
  51699. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51700. if (loop !== undefined) {
  51701. for (var index = 0; index < this._animatables.length; index++) {
  51702. var animatable = this._animatables[index];
  51703. animatable.loopAnimation = loop;
  51704. }
  51705. }
  51706. this.restart();
  51707. }
  51708. else {
  51709. this.stop();
  51710. this.start(loop, this._speedRatio);
  51711. }
  51712. return this;
  51713. };
  51714. /**
  51715. * Reset all animations to initial state
  51716. * @returns the animation group
  51717. */
  51718. AnimationGroup.prototype.reset = function () {
  51719. if (!this._isStarted) {
  51720. return this;
  51721. }
  51722. for (var index = 0; index < this._animatables.length; index++) {
  51723. var animatable = this._animatables[index];
  51724. animatable.reset();
  51725. }
  51726. return this;
  51727. };
  51728. /**
  51729. * Restart animations from key 0
  51730. * @returns the animation group
  51731. */
  51732. AnimationGroup.prototype.restart = function () {
  51733. if (!this._isStarted) {
  51734. return this;
  51735. }
  51736. for (var index = 0; index < this._animatables.length; index++) {
  51737. var animatable = this._animatables[index];
  51738. animatable.restart();
  51739. }
  51740. return this;
  51741. };
  51742. /**
  51743. * Stop all animations
  51744. * @returns the animation group
  51745. */
  51746. AnimationGroup.prototype.stop = function () {
  51747. if (!this._isStarted) {
  51748. return this;
  51749. }
  51750. var list = this._animatables.slice();
  51751. for (var index = 0; index < list.length; index++) {
  51752. list[index].stop();
  51753. }
  51754. this._isStarted = false;
  51755. return this;
  51756. };
  51757. /**
  51758. * Set animation weight for all animatables
  51759. * @param weight defines the weight to use
  51760. * @return the animationGroup
  51761. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51762. */
  51763. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51764. for (var index = 0; index < this._animatables.length; index++) {
  51765. var animatable = this._animatables[index];
  51766. animatable.weight = weight;
  51767. }
  51768. return this;
  51769. };
  51770. /**
  51771. * Synchronize and normalize all animatables with a source animatable
  51772. * @param root defines the root animatable to synchronize with
  51773. * @return the animationGroup
  51774. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51775. */
  51776. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51777. for (var index = 0; index < this._animatables.length; index++) {
  51778. var animatable = this._animatables[index];
  51779. animatable.syncWith(root);
  51780. }
  51781. return this;
  51782. };
  51783. /**
  51784. * Goes to a specific frame in this animation group
  51785. * @param frame the frame number to go to
  51786. * @return the animationGroup
  51787. */
  51788. AnimationGroup.prototype.goToFrame = function (frame) {
  51789. if (!this._isStarted) {
  51790. return this;
  51791. }
  51792. for (var index = 0; index < this._animatables.length; index++) {
  51793. var animatable = this._animatables[index];
  51794. animatable.goToFrame(frame);
  51795. }
  51796. return this;
  51797. };
  51798. /**
  51799. * Dispose all associated resources
  51800. */
  51801. AnimationGroup.prototype.dispose = function () {
  51802. this._targetedAnimations = [];
  51803. this._animatables = [];
  51804. var index = this._scene.animationGroups.indexOf(this);
  51805. if (index > -1) {
  51806. this._scene.animationGroups.splice(index, 1);
  51807. }
  51808. };
  51809. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51810. // animatable should be taken out of the array
  51811. var idx = this._animatables.indexOf(animatable);
  51812. if (idx > -1) {
  51813. this._animatables.splice(idx, 1);
  51814. }
  51815. // all animatables were removed? animation group ended!
  51816. if (this._animatables.length === 0) {
  51817. this._isStarted = false;
  51818. this.onAnimationGroupEndObservable.notifyObservers(this);
  51819. }
  51820. };
  51821. // Statics
  51822. /**
  51823. * Returns a new AnimationGroup object parsed from the source provided.
  51824. * @param parsedAnimationGroup defines the source
  51825. * @param scene defines the scene that will receive the animationGroup
  51826. * @returns a new AnimationGroup
  51827. */
  51828. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  51829. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  51830. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  51831. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  51832. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  51833. var id = targetedAnimation.targetId;
  51834. var targetNode = scene.getNodeByID(id);
  51835. if (targetNode != null)
  51836. animationGroup.addTargetedAnimation(animation, targetNode);
  51837. }
  51838. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  51839. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  51840. return animationGroup;
  51841. };
  51842. /**
  51843. * Returns the string "AnimationGroup"
  51844. * @returns "AnimationGroup"
  51845. */
  51846. AnimationGroup.prototype.getClassName = function () {
  51847. return "AnimationGroup";
  51848. };
  51849. /**
  51850. * Creates a detailled string about the object
  51851. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  51852. * @returns a string representing the object
  51853. */
  51854. AnimationGroup.prototype.toString = function (fullDetails) {
  51855. var ret = "Name: " + this.name;
  51856. ret += ", type: " + this.getClassName();
  51857. if (fullDetails) {
  51858. ret += ", from: " + this._from;
  51859. ret += ", to: " + this._to;
  51860. ret += ", isStarted: " + this._isStarted;
  51861. ret += ", speedRatio: " + this._speedRatio;
  51862. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  51863. ret += ", animatables length: " + this._animatables;
  51864. }
  51865. return ret;
  51866. };
  51867. return AnimationGroup;
  51868. }());
  51869. BABYLON.AnimationGroup = AnimationGroup;
  51870. })(BABYLON || (BABYLON = {}));
  51871. //# sourceMappingURL=babylon.animationGroup.js.map
  51872. var BABYLON;
  51873. (function (BABYLON) {
  51874. // Static values to help the garbage collector
  51875. // Quaternion
  51876. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51877. // Vector3
  51878. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51879. // Vector2
  51880. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51881. // Size
  51882. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51883. // Color3
  51884. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51885. /**
  51886. * Defines a runtime animation
  51887. */
  51888. var RuntimeAnimation = /** @class */ (function () {
  51889. /**
  51890. * Create a new RuntimeAnimation object
  51891. * @param target defines the target of the animation
  51892. * @param animation defines the source animation object
  51893. * @param scene defines the hosting scene
  51894. * @param host defines the initiating Animatable
  51895. */
  51896. function RuntimeAnimation(target, animation, scene, host) {
  51897. var _this = this;
  51898. this._events = new Array();
  51899. /**
  51900. * The current frame of the runtime animation
  51901. */
  51902. this._currentFrame = 0;
  51903. /**
  51904. * The original value of the runtime animation
  51905. */
  51906. this._originalValue = new Array();
  51907. /**
  51908. * The offsets cache of the runtime animation
  51909. */
  51910. this._offsetsCache = {};
  51911. /**
  51912. * The high limits cache of the runtime animation
  51913. */
  51914. this._highLimitsCache = {};
  51915. /**
  51916. * Specifies if the runtime animation has been stopped
  51917. */
  51918. this._stopped = false;
  51919. /**
  51920. * The blending factor of the runtime animation
  51921. */
  51922. this._blendingFactor = 0;
  51923. /**
  51924. * The target path of the runtime animation
  51925. */
  51926. this._targetPath = "";
  51927. /**
  51928. * The weight of the runtime animation
  51929. */
  51930. this._weight = 1.0;
  51931. /**
  51932. * The ratio offset of the runtime animation
  51933. */
  51934. this._ratioOffset = 0;
  51935. /**
  51936. * The previous delay of the runtime animation
  51937. */
  51938. this._previousDelay = 0;
  51939. /**
  51940. * The previous ratio of the runtime animation
  51941. */
  51942. this._previousRatio = 0;
  51943. this._animation = animation;
  51944. this._target = target;
  51945. this._scene = scene;
  51946. this._host = host;
  51947. animation._runtimeAnimations.push(this);
  51948. // Cloning events locally
  51949. var events = animation.getEvents();
  51950. if (events && events.length > 0) {
  51951. events.forEach(function (e) {
  51952. _this._events.push(e._clone());
  51953. });
  51954. }
  51955. }
  51956. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51957. /**
  51958. * Gets the current frame of the runtime animation
  51959. */
  51960. get: function () {
  51961. return this._currentFrame;
  51962. },
  51963. enumerable: true,
  51964. configurable: true
  51965. });
  51966. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51967. /**
  51968. * Gets the weight of the runtime animation
  51969. */
  51970. get: function () {
  51971. return this._weight;
  51972. },
  51973. enumerable: true,
  51974. configurable: true
  51975. });
  51976. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51977. /**
  51978. * Gets the current value of the runtime animation
  51979. */
  51980. get: function () {
  51981. return this._currentValue;
  51982. },
  51983. enumerable: true,
  51984. configurable: true
  51985. });
  51986. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51987. /**
  51988. * Gets the target path of the runtime animation
  51989. */
  51990. get: function () {
  51991. return this._targetPath;
  51992. },
  51993. enumerable: true,
  51994. configurable: true
  51995. });
  51996. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51997. /**
  51998. * Gets the actual target of the runtime animation
  51999. */
  52000. get: function () {
  52001. return this._activeTarget;
  52002. },
  52003. enumerable: true,
  52004. configurable: true
  52005. });
  52006. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52007. /**
  52008. * Gets the animation from the runtime animation
  52009. */
  52010. get: function () {
  52011. return this._animation;
  52012. },
  52013. enumerable: true,
  52014. configurable: true
  52015. });
  52016. /**
  52017. * Resets the runtime animation to the beginning
  52018. * @param restoreOriginal defines whether to restore the target property to the original value
  52019. */
  52020. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52021. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52022. if (restoreOriginal) {
  52023. if (this._target instanceof Array) {
  52024. var index = 0;
  52025. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52026. var target = _a[_i];
  52027. if (this._originalValue[index] !== undefined) {
  52028. this._setValue(target, this._originalValue[index], -1);
  52029. }
  52030. index++;
  52031. }
  52032. }
  52033. else {
  52034. if (this._originalValue[0] !== undefined) {
  52035. this._setValue(this._target, this._originalValue[0], -1);
  52036. }
  52037. }
  52038. }
  52039. this._offsetsCache = {};
  52040. this._highLimitsCache = {};
  52041. this._currentFrame = 0;
  52042. this._blendingFactor = 0;
  52043. this._originalValue = new Array();
  52044. // Events
  52045. for (var index = 0; index < this._events.length; index++) {
  52046. this._events[index].isDone = false;
  52047. }
  52048. };
  52049. /**
  52050. * Specifies if the runtime animation is stopped
  52051. * @returns Boolean specifying if the runtime animation is stopped
  52052. */
  52053. RuntimeAnimation.prototype.isStopped = function () {
  52054. return this._stopped;
  52055. };
  52056. /**
  52057. * Disposes of the runtime animation
  52058. */
  52059. RuntimeAnimation.prototype.dispose = function () {
  52060. var index = this._animation.runtimeAnimations.indexOf(this);
  52061. if (index > -1) {
  52062. this._animation.runtimeAnimations.splice(index, 1);
  52063. }
  52064. };
  52065. /**
  52066. * Interpolates the animation from the current frame
  52067. * @param currentFrame The frame to interpolate the animation to
  52068. * @param repeatCount The number of times that the animation should loop
  52069. * @param loopMode The type of looping mode to use
  52070. * @param offsetValue Animation offset value
  52071. * @param highLimitValue The high limit value
  52072. * @returns The interpolated value
  52073. */
  52074. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52075. this._currentFrame = currentFrame;
  52076. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52077. this._workValue = BABYLON.Matrix.Zero();
  52078. }
  52079. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52080. };
  52081. /**
  52082. * Apply the interpolated value to the target
  52083. * @param currentValue defines the value computed by the animation
  52084. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52085. */
  52086. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52087. if (weight === void 0) { weight = 1.0; }
  52088. if (this._target instanceof Array) {
  52089. var index = 0;
  52090. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52091. var target = _a[_i];
  52092. this._setValue(target, currentValue, weight, index);
  52093. index++;
  52094. }
  52095. }
  52096. else {
  52097. this._setValue(this._target, currentValue, weight);
  52098. }
  52099. };
  52100. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52101. if (targetIndex === void 0) { targetIndex = 0; }
  52102. // Set value
  52103. var path;
  52104. var destination;
  52105. var targetPropertyPath = this._animation.targetPropertyPath;
  52106. if (targetPropertyPath.length > 1) {
  52107. var property = target[targetPropertyPath[0]];
  52108. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52109. property = property[targetPropertyPath[index]];
  52110. }
  52111. path = targetPropertyPath[targetPropertyPath.length - 1];
  52112. destination = property;
  52113. }
  52114. else {
  52115. path = targetPropertyPath[0];
  52116. destination = target;
  52117. }
  52118. this._targetPath = path;
  52119. this._activeTarget = destination;
  52120. this._weight = weight;
  52121. if (this._originalValue[targetIndex] === undefined) {
  52122. var originalValue = void 0;
  52123. if (destination.getRestPose && path === "_matrix") { // For bones
  52124. originalValue = destination.getRestPose();
  52125. }
  52126. else {
  52127. originalValue = destination[path];
  52128. }
  52129. if (originalValue && originalValue.clone) {
  52130. this._originalValue[targetIndex] = originalValue.clone();
  52131. }
  52132. else {
  52133. this._originalValue[targetIndex] = originalValue;
  52134. }
  52135. }
  52136. // Blending
  52137. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52138. if (enableBlending && this._blendingFactor <= 1.0) {
  52139. if (!this._originalBlendValue) {
  52140. var originalValue = destination[path];
  52141. if (originalValue.clone) {
  52142. this._originalBlendValue = originalValue.clone();
  52143. }
  52144. else {
  52145. this._originalBlendValue = originalValue;
  52146. }
  52147. }
  52148. if (this._originalBlendValue.m) { // Matrix
  52149. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52150. if (this._currentValue) {
  52151. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52152. }
  52153. else {
  52154. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52155. }
  52156. }
  52157. else {
  52158. if (this._currentValue) {
  52159. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52160. }
  52161. else {
  52162. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52163. }
  52164. }
  52165. }
  52166. else {
  52167. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52168. }
  52169. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52170. this._blendingFactor += blendingSpeed;
  52171. }
  52172. else {
  52173. this._currentValue = currentValue;
  52174. }
  52175. if (weight !== -1.0) {
  52176. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52177. }
  52178. else {
  52179. destination[path] = this._currentValue;
  52180. }
  52181. if (target.markAsDirty) {
  52182. target.markAsDirty(this._animation.targetProperty);
  52183. }
  52184. };
  52185. /**
  52186. * Gets the loop pmode of the runtime animation
  52187. * @returns Loop Mode
  52188. */
  52189. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52190. if (this._target && this._target.animationPropertiesOverride) {
  52191. return this._target.animationPropertiesOverride.loopMode;
  52192. }
  52193. return this._animation.loopMode;
  52194. };
  52195. /**
  52196. * Move the current animation to a given frame
  52197. * @param frame defines the frame to move to
  52198. */
  52199. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52200. var keys = this._animation.getKeys();
  52201. if (frame < keys[0].frame) {
  52202. frame = keys[0].frame;
  52203. }
  52204. else if (frame > keys[keys.length - 1].frame) {
  52205. frame = keys[keys.length - 1].frame;
  52206. }
  52207. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52208. this.setValue(currentValue, -1);
  52209. };
  52210. /**
  52211. * @hidden Internal use only
  52212. */
  52213. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52214. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52215. this._ratioOffset = this._previousRatio - newRatio;
  52216. };
  52217. /**
  52218. * Execute the current animation
  52219. * @param delay defines the delay to add to the current frame
  52220. * @param from defines the lower bound of the animation range
  52221. * @param to defines the upper bound of the animation range
  52222. * @param loop defines if the current animation must loop
  52223. * @param speedRatio defines the current speed ratio
  52224. * @param weight defines the weight of the animation (default is -1 so no weight)
  52225. * @returns a boolean indicating if the animation is running
  52226. */
  52227. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52228. if (weight === void 0) { weight = -1.0; }
  52229. var targetPropertyPath = this._animation.targetPropertyPath;
  52230. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52231. this._stopped = true;
  52232. return false;
  52233. }
  52234. var returnValue = true;
  52235. var keys = this._animation.getKeys();
  52236. // Adding a start key at frame 0 if missing
  52237. if (keys[0].frame !== 0) {
  52238. var newKey = { frame: 0, value: keys[0].value };
  52239. keys.splice(0, 0, newKey);
  52240. }
  52241. // Adding a duplicate key when there is only one key at frame zero
  52242. else if (keys.length === 1) {
  52243. var newKey = { frame: 0.001, value: keys[0].value };
  52244. keys.push(newKey);
  52245. }
  52246. // Check limits
  52247. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52248. from = keys[0].frame;
  52249. }
  52250. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52251. to = keys[keys.length - 1].frame;
  52252. }
  52253. //to and from cannot be the same key
  52254. if (from === to) {
  52255. if (from > keys[0].frame) {
  52256. from--;
  52257. }
  52258. else if (to < keys[keys.length - 1].frame) {
  52259. to++;
  52260. }
  52261. }
  52262. // Compute ratio
  52263. var range = to - from;
  52264. var offsetValue;
  52265. // ratio represents the frame delta between from and to
  52266. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52267. var highLimitValue = 0;
  52268. this._previousDelay = delay;
  52269. this._previousRatio = ratio;
  52270. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52271. returnValue = false;
  52272. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52273. }
  52274. else {
  52275. // Get max value if required
  52276. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52277. var keyOffset = to.toString() + from.toString();
  52278. if (!this._offsetsCache[keyOffset]) {
  52279. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52280. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52281. switch (this._animation.dataType) {
  52282. // Float
  52283. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52284. this._offsetsCache[keyOffset] = toValue - fromValue;
  52285. break;
  52286. // Quaternion
  52287. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52288. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52289. break;
  52290. // Vector3
  52291. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52292. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52293. // Vector2
  52294. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52295. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52296. // Size
  52297. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52298. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52299. // Color3
  52300. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52301. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52302. default:
  52303. break;
  52304. }
  52305. this._highLimitsCache[keyOffset] = toValue;
  52306. }
  52307. highLimitValue = this._highLimitsCache[keyOffset];
  52308. offsetValue = this._offsetsCache[keyOffset];
  52309. }
  52310. }
  52311. if (offsetValue === undefined) {
  52312. switch (this._animation.dataType) {
  52313. // Float
  52314. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52315. offsetValue = 0;
  52316. break;
  52317. // Quaternion
  52318. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52319. offsetValue = _staticOffsetValueQuaternion;
  52320. break;
  52321. // Vector3
  52322. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52323. offsetValue = _staticOffsetValueVector3;
  52324. break;
  52325. // Vector2
  52326. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52327. offsetValue = _staticOffsetValueVector2;
  52328. break;
  52329. // Size
  52330. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52331. offsetValue = _staticOffsetValueSize;
  52332. break;
  52333. // Color3
  52334. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52335. offsetValue = _staticOffsetValueColor3;
  52336. }
  52337. }
  52338. // Compute value
  52339. var repeatCount = (ratio / range) >> 0;
  52340. var currentFrame = returnValue ? from + ratio % range : to;
  52341. // Need to normalize?
  52342. if (this._host && this._host.syncRoot) {
  52343. var syncRoot = this._host.syncRoot;
  52344. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52345. currentFrame = from + (to - from) * hostNormalizedFrame;
  52346. }
  52347. // Reset events if looping
  52348. var events = this._events;
  52349. if (range > 0 && this.currentFrame > currentFrame ||
  52350. range < 0 && this.currentFrame < currentFrame) {
  52351. // Need to reset animation events
  52352. for (var index = 0; index < events.length; index++) {
  52353. if (!events[index].onlyOnce) {
  52354. // reset event, the animation is looping
  52355. events[index].isDone = false;
  52356. }
  52357. }
  52358. }
  52359. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52360. // Set value
  52361. this.setValue(currentValue, weight);
  52362. // Check events
  52363. for (var index = 0; index < events.length; index++) {
  52364. // Make sure current frame has passed event frame and that event frame is within the current range
  52365. // Also, handle both forward and reverse animations
  52366. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52367. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52368. var event = events[index];
  52369. if (!event.isDone) {
  52370. // If event should be done only once, remove it.
  52371. if (event.onlyOnce) {
  52372. events.splice(index, 1);
  52373. index--;
  52374. }
  52375. event.isDone = true;
  52376. event.action(currentFrame);
  52377. } // Don't do anything if the event has already be done.
  52378. }
  52379. }
  52380. if (!returnValue) {
  52381. this._stopped = true;
  52382. }
  52383. return returnValue;
  52384. };
  52385. return RuntimeAnimation;
  52386. }());
  52387. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52388. })(BABYLON || (BABYLON = {}));
  52389. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52390. var BABYLON;
  52391. (function (BABYLON) {
  52392. /**
  52393. * Class used to store an actual running animation
  52394. */
  52395. var Animatable = /** @class */ (function () {
  52396. /**
  52397. * Creates a new Animatable
  52398. * @param scene defines the hosting scene
  52399. * @param target defines the target object
  52400. * @param fromFrame defines the starting frame number (default is 0)
  52401. * @param toFrame defines the ending frame number (default is 100)
  52402. * @param loopAnimation defines if the animation must loop (default is false)
  52403. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  52404. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  52405. * @param animations defines a group of animation to add to the new Animatable
  52406. */
  52407. function Animatable(scene,
  52408. /** defines the target object */
  52409. target,
  52410. /** defines the starting frame number (default is 0) */
  52411. fromFrame,
  52412. /** defines the ending frame number (default is 100) */
  52413. toFrame,
  52414. /** defines if the animation must loop (default is false) */
  52415. loopAnimation, speedRatio,
  52416. /** defines a callback to call when animation ends if it is not looping */
  52417. onAnimationEnd, animations) {
  52418. if (fromFrame === void 0) { fromFrame = 0; }
  52419. if (toFrame === void 0) { toFrame = 100; }
  52420. if (loopAnimation === void 0) { loopAnimation = false; }
  52421. if (speedRatio === void 0) { speedRatio = 1.0; }
  52422. this.target = target;
  52423. this.fromFrame = fromFrame;
  52424. this.toFrame = toFrame;
  52425. this.loopAnimation = loopAnimation;
  52426. this.onAnimationEnd = onAnimationEnd;
  52427. this._localDelayOffset = null;
  52428. this._pausedDelay = null;
  52429. this._runtimeAnimations = new Array();
  52430. this._paused = false;
  52431. this._speedRatio = 1;
  52432. this._weight = -1.0;
  52433. /**
  52434. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  52435. * This will only apply for non looping animation (default is true)
  52436. */
  52437. this.disposeOnEnd = true;
  52438. /**
  52439. * Gets a boolean indicating if the animation has started
  52440. */
  52441. this.animationStarted = false;
  52442. /**
  52443. * Observer raised when the animation ends
  52444. */
  52445. this.onAnimationEndObservable = new BABYLON.Observable();
  52446. this._scene = scene;
  52447. if (animations) {
  52448. this.appendAnimations(target, animations);
  52449. }
  52450. this._speedRatio = speedRatio;
  52451. scene._activeAnimatables.push(this);
  52452. }
  52453. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52454. /**
  52455. * Gets the root Animatable used to synchronize and normalize animations
  52456. */
  52457. get: function () {
  52458. return this._syncRoot;
  52459. },
  52460. enumerable: true,
  52461. configurable: true
  52462. });
  52463. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52464. /**
  52465. * Gets the current frame of the first RuntimeAnimation
  52466. * Used to synchronize Animatables
  52467. */
  52468. get: function () {
  52469. if (this._runtimeAnimations.length === 0) {
  52470. return 0;
  52471. }
  52472. return this._runtimeAnimations[0].currentFrame;
  52473. },
  52474. enumerable: true,
  52475. configurable: true
  52476. });
  52477. Object.defineProperty(Animatable.prototype, "weight", {
  52478. /**
  52479. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52480. */
  52481. get: function () {
  52482. return this._weight;
  52483. },
  52484. set: function (value) {
  52485. if (value === -1) { // -1 is ok and means no weight
  52486. this._weight = -1;
  52487. return;
  52488. }
  52489. // Else weight must be in [0, 1] range
  52490. this._weight = Math.min(Math.max(value, 0), 1.0);
  52491. },
  52492. enumerable: true,
  52493. configurable: true
  52494. });
  52495. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52496. /**
  52497. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52498. */
  52499. get: function () {
  52500. return this._speedRatio;
  52501. },
  52502. set: function (value) {
  52503. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52504. var animation = this._runtimeAnimations[index];
  52505. animation._prepareForSpeedRatioChange(value);
  52506. }
  52507. this._speedRatio = value;
  52508. },
  52509. enumerable: true,
  52510. configurable: true
  52511. });
  52512. // Methods
  52513. /**
  52514. * Synchronize and normalize current Animatable with a source Animatable
  52515. * This is useful when using animation weights and when animations are not of the same length
  52516. * @param root defines the root Animatable to synchronize with
  52517. * @returns the current Animatable
  52518. */
  52519. Animatable.prototype.syncWith = function (root) {
  52520. this._syncRoot = root;
  52521. if (root) {
  52522. // Make sure this animatable will animate after the root
  52523. var index = this._scene._activeAnimatables.indexOf(this);
  52524. if (index > -1) {
  52525. this._scene._activeAnimatables.splice(index, 1);
  52526. this._scene._activeAnimatables.push(this);
  52527. }
  52528. }
  52529. return this;
  52530. };
  52531. /**
  52532. * Gets the list of runtime animations
  52533. * @returns an array of RuntimeAnimation
  52534. */
  52535. Animatable.prototype.getAnimations = function () {
  52536. return this._runtimeAnimations;
  52537. };
  52538. /**
  52539. * Adds more animations to the current animatable
  52540. * @param target defines the target of the animations
  52541. * @param animations defines the new animations to add
  52542. */
  52543. Animatable.prototype.appendAnimations = function (target, animations) {
  52544. for (var index = 0; index < animations.length; index++) {
  52545. var animation = animations[index];
  52546. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52547. }
  52548. };
  52549. /**
  52550. * Gets the source animation for a specific property
  52551. * @param property defines the propertyu to look for
  52552. * @returns null or the source animation for the given property
  52553. */
  52554. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52555. var runtimeAnimations = this._runtimeAnimations;
  52556. for (var index = 0; index < runtimeAnimations.length; index++) {
  52557. if (runtimeAnimations[index].animation.targetProperty === property) {
  52558. return runtimeAnimations[index].animation;
  52559. }
  52560. }
  52561. return null;
  52562. };
  52563. /**
  52564. * Gets the runtime animation for a specific property
  52565. * @param property defines the propertyu to look for
  52566. * @returns null or the runtime animation for the given property
  52567. */
  52568. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52569. var runtimeAnimations = this._runtimeAnimations;
  52570. for (var index = 0; index < runtimeAnimations.length; index++) {
  52571. if (runtimeAnimations[index].animation.targetProperty === property) {
  52572. return runtimeAnimations[index];
  52573. }
  52574. }
  52575. return null;
  52576. };
  52577. /**
  52578. * Resets the animatable to its original state
  52579. */
  52580. Animatable.prototype.reset = function () {
  52581. var runtimeAnimations = this._runtimeAnimations;
  52582. for (var index = 0; index < runtimeAnimations.length; index++) {
  52583. runtimeAnimations[index].reset(true);
  52584. }
  52585. this._localDelayOffset = null;
  52586. this._pausedDelay = null;
  52587. };
  52588. /**
  52589. * Allows the animatable to blend with current running animations
  52590. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52591. * @param blendingSpeed defines the blending speed to use
  52592. */
  52593. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52594. var runtimeAnimations = this._runtimeAnimations;
  52595. for (var index = 0; index < runtimeAnimations.length; index++) {
  52596. runtimeAnimations[index].animation.enableBlending = true;
  52597. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52598. }
  52599. };
  52600. /**
  52601. * Disable animation blending
  52602. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52603. */
  52604. Animatable.prototype.disableBlending = function () {
  52605. var runtimeAnimations = this._runtimeAnimations;
  52606. for (var index = 0; index < runtimeAnimations.length; index++) {
  52607. runtimeAnimations[index].animation.enableBlending = false;
  52608. }
  52609. };
  52610. /**
  52611. * Jump directly to a given frame
  52612. * @param frame defines the frame to jump to
  52613. */
  52614. Animatable.prototype.goToFrame = function (frame) {
  52615. var runtimeAnimations = this._runtimeAnimations;
  52616. if (runtimeAnimations[0]) {
  52617. var fps = runtimeAnimations[0].animation.framePerSecond;
  52618. var currentFrame = runtimeAnimations[0].currentFrame;
  52619. var adjustTime = frame - currentFrame;
  52620. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52621. if (this._localDelayOffset === null) {
  52622. this._localDelayOffset = 0;
  52623. }
  52624. this._localDelayOffset -= delay;
  52625. }
  52626. for (var index = 0; index < runtimeAnimations.length; index++) {
  52627. runtimeAnimations[index].goToFrame(frame);
  52628. }
  52629. };
  52630. /**
  52631. * Pause the animation
  52632. */
  52633. Animatable.prototype.pause = function () {
  52634. if (this._paused) {
  52635. return;
  52636. }
  52637. this._paused = true;
  52638. };
  52639. /**
  52640. * Restart the animation
  52641. */
  52642. Animatable.prototype.restart = function () {
  52643. this._paused = false;
  52644. };
  52645. Animatable.prototype._raiseOnAnimationEnd = function () {
  52646. if (this.onAnimationEnd) {
  52647. this.onAnimationEnd();
  52648. }
  52649. this.onAnimationEndObservable.notifyObservers(this);
  52650. };
  52651. /**
  52652. * Stop and delete the current animation
  52653. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52654. * @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)
  52655. */
  52656. Animatable.prototype.stop = function (animationName, targetMask) {
  52657. if (animationName || targetMask) {
  52658. var idx = this._scene._activeAnimatables.indexOf(this);
  52659. if (idx > -1) {
  52660. var runtimeAnimations = this._runtimeAnimations;
  52661. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52662. var runtimeAnimation = runtimeAnimations[index];
  52663. if (animationName && runtimeAnimation.animation.name != animationName) {
  52664. continue;
  52665. }
  52666. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52667. continue;
  52668. }
  52669. runtimeAnimation.dispose();
  52670. runtimeAnimations.splice(index, 1);
  52671. }
  52672. if (runtimeAnimations.length == 0) {
  52673. this._scene._activeAnimatables.splice(idx, 1);
  52674. this._raiseOnAnimationEnd();
  52675. }
  52676. }
  52677. }
  52678. else {
  52679. var index = this._scene._activeAnimatables.indexOf(this);
  52680. if (index > -1) {
  52681. this._scene._activeAnimatables.splice(index, 1);
  52682. var runtimeAnimations = this._runtimeAnimations;
  52683. for (var index = 0; index < runtimeAnimations.length; index++) {
  52684. runtimeAnimations[index].dispose();
  52685. }
  52686. this._raiseOnAnimationEnd();
  52687. }
  52688. }
  52689. };
  52690. /**
  52691. * Wait asynchronously for the animation to end
  52692. * @returns a promise which will be fullfilled when the animation ends
  52693. */
  52694. Animatable.prototype.waitAsync = function () {
  52695. var _this = this;
  52696. return new Promise(function (resolve, reject) {
  52697. _this.onAnimationEndObservable.add(function () {
  52698. resolve(_this);
  52699. }, undefined, undefined, _this, true);
  52700. });
  52701. };
  52702. /** @hidden */
  52703. Animatable.prototype._animate = function (delay) {
  52704. if (this._paused) {
  52705. this.animationStarted = false;
  52706. if (this._pausedDelay === null) {
  52707. this._pausedDelay = delay;
  52708. }
  52709. return true;
  52710. }
  52711. if (this._localDelayOffset === null) {
  52712. this._localDelayOffset = delay;
  52713. this._pausedDelay = null;
  52714. }
  52715. else if (this._pausedDelay !== null) {
  52716. this._localDelayOffset += delay - this._pausedDelay;
  52717. this._pausedDelay = null;
  52718. }
  52719. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52720. return true;
  52721. }
  52722. // Animating
  52723. var running = false;
  52724. var runtimeAnimations = this._runtimeAnimations;
  52725. var index;
  52726. for (index = 0; index < runtimeAnimations.length; index++) {
  52727. var animation = runtimeAnimations[index];
  52728. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52729. running = running || isRunning;
  52730. }
  52731. this.animationStarted = running;
  52732. if (!running) {
  52733. if (this.disposeOnEnd) {
  52734. // Remove from active animatables
  52735. index = this._scene._activeAnimatables.indexOf(this);
  52736. this._scene._activeAnimatables.splice(index, 1);
  52737. // Dispose all runtime animations
  52738. for (index = 0; index < runtimeAnimations.length; index++) {
  52739. runtimeAnimations[index].dispose();
  52740. }
  52741. }
  52742. this._raiseOnAnimationEnd();
  52743. if (this.disposeOnEnd) {
  52744. this.onAnimationEnd = null;
  52745. this.onAnimationEndObservable.clear();
  52746. }
  52747. }
  52748. return running;
  52749. };
  52750. return Animatable;
  52751. }());
  52752. BABYLON.Animatable = Animatable;
  52753. })(BABYLON || (BABYLON = {}));
  52754. //# sourceMappingURL=babylon.animatable.js.map
  52755. var BABYLON;
  52756. (function (BABYLON) {
  52757. /**
  52758. * Base class used for every default easing function.
  52759. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52760. */
  52761. var EasingFunction = /** @class */ (function () {
  52762. function EasingFunction() {
  52763. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52764. }
  52765. /**
  52766. * Sets the easing mode of the current function.
  52767. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  52768. */
  52769. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52770. var n = Math.min(Math.max(easingMode, 0), 2);
  52771. this._easingMode = n;
  52772. };
  52773. /**
  52774. * Gets the current easing mode.
  52775. * @returns the easing mode
  52776. */
  52777. EasingFunction.prototype.getEasingMode = function () {
  52778. return this._easingMode;
  52779. };
  52780. /**
  52781. * @hidden
  52782. */
  52783. EasingFunction.prototype.easeInCore = function (gradient) {
  52784. throw new Error('You must implement this method');
  52785. };
  52786. /**
  52787. * Given an input gradient between 0 and 1, this returns the corrseponding value
  52788. * of the easing function.
  52789. * @param gradient Defines the value between 0 and 1 we want the easing value for
  52790. * @returns the corresponding value on the curve defined by the easing function
  52791. */
  52792. EasingFunction.prototype.ease = function (gradient) {
  52793. switch (this._easingMode) {
  52794. case EasingFunction.EASINGMODE_EASEIN:
  52795. return this.easeInCore(gradient);
  52796. case EasingFunction.EASINGMODE_EASEOUT:
  52797. return (1 - this.easeInCore(1 - gradient));
  52798. }
  52799. if (gradient >= 0.5) {
  52800. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52801. }
  52802. return (this.easeInCore(gradient * 2) * 0.5);
  52803. };
  52804. /**
  52805. * Interpolation follows the mathematical formula associated with the easing function.
  52806. */
  52807. EasingFunction.EASINGMODE_EASEIN = 0;
  52808. /**
  52809. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  52810. */
  52811. EasingFunction.EASINGMODE_EASEOUT = 1;
  52812. /**
  52813. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  52814. */
  52815. EasingFunction.EASINGMODE_EASEINOUT = 2;
  52816. return EasingFunction;
  52817. }());
  52818. BABYLON.EasingFunction = EasingFunction;
  52819. /**
  52820. * Easing function with a circle shape (see link below).
  52821. * @see https://easings.net/#easeInCirc
  52822. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52823. */
  52824. var CircleEase = /** @class */ (function (_super) {
  52825. __extends(CircleEase, _super);
  52826. function CircleEase() {
  52827. return _super !== null && _super.apply(this, arguments) || this;
  52828. }
  52829. /** @hidden */
  52830. CircleEase.prototype.easeInCore = function (gradient) {
  52831. gradient = Math.max(0, Math.min(1, gradient));
  52832. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52833. };
  52834. return CircleEase;
  52835. }(EasingFunction));
  52836. BABYLON.CircleEase = CircleEase;
  52837. /**
  52838. * Easing function with a ease back shape (see link below).
  52839. * @see https://easings.net/#easeInBack
  52840. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52841. */
  52842. var BackEase = /** @class */ (function (_super) {
  52843. __extends(BackEase, _super);
  52844. /**
  52845. * Instantiates a back ease easing
  52846. * @see https://easings.net/#easeInBack
  52847. * @param amplitude Defines the amplitude of the function
  52848. */
  52849. function BackEase(
  52850. /** Defines the amplitude of the function */
  52851. amplitude) {
  52852. if (amplitude === void 0) { amplitude = 1; }
  52853. var _this = _super.call(this) || this;
  52854. _this.amplitude = amplitude;
  52855. return _this;
  52856. }
  52857. /** @hidden */
  52858. BackEase.prototype.easeInCore = function (gradient) {
  52859. var num = Math.max(0, this.amplitude);
  52860. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52861. };
  52862. return BackEase;
  52863. }(EasingFunction));
  52864. BABYLON.BackEase = BackEase;
  52865. /**
  52866. * Easing function with a bouncing shape (see link below).
  52867. * @see https://easings.net/#easeInBounce
  52868. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52869. */
  52870. var BounceEase = /** @class */ (function (_super) {
  52871. __extends(BounceEase, _super);
  52872. /**
  52873. * Instantiates a bounce easing
  52874. * @see https://easings.net/#easeInBounce
  52875. * @param bounces Defines the number of bounces
  52876. * @param bounciness Defines the amplitude of the bounce
  52877. */
  52878. function BounceEase(
  52879. /** Defines the number of bounces */
  52880. bounces,
  52881. /** Defines the amplitude of the bounce */
  52882. bounciness) {
  52883. if (bounces === void 0) { bounces = 3; }
  52884. if (bounciness === void 0) { bounciness = 2; }
  52885. var _this = _super.call(this) || this;
  52886. _this.bounces = bounces;
  52887. _this.bounciness = bounciness;
  52888. return _this;
  52889. }
  52890. /** @hidden */
  52891. BounceEase.prototype.easeInCore = function (gradient) {
  52892. var y = Math.max(0.0, this.bounces);
  52893. var bounciness = this.bounciness;
  52894. if (bounciness <= 1.0) {
  52895. bounciness = 1.001;
  52896. }
  52897. var num9 = Math.pow(bounciness, y);
  52898. var num5 = 1.0 - bounciness;
  52899. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52900. var num15 = gradient * num4;
  52901. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52902. var num3 = Math.floor(num65);
  52903. var num13 = num3 + 1.0;
  52904. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52905. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52906. var num7 = (num8 + num12) * 0.5;
  52907. var num6 = gradient - num7;
  52908. var num2 = num7 - num8;
  52909. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52910. };
  52911. return BounceEase;
  52912. }(EasingFunction));
  52913. BABYLON.BounceEase = BounceEase;
  52914. /**
  52915. * Easing function with a power of 3 shape (see link below).
  52916. * @see https://easings.net/#easeInCubic
  52917. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52918. */
  52919. var CubicEase = /** @class */ (function (_super) {
  52920. __extends(CubicEase, _super);
  52921. function CubicEase() {
  52922. return _super !== null && _super.apply(this, arguments) || this;
  52923. }
  52924. /** @hidden */
  52925. CubicEase.prototype.easeInCore = function (gradient) {
  52926. return (gradient * gradient * gradient);
  52927. };
  52928. return CubicEase;
  52929. }(EasingFunction));
  52930. BABYLON.CubicEase = CubicEase;
  52931. /**
  52932. * Easing function with an elastic shape (see link below).
  52933. * @see https://easings.net/#easeInElastic
  52934. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52935. */
  52936. var ElasticEase = /** @class */ (function (_super) {
  52937. __extends(ElasticEase, _super);
  52938. /**
  52939. * Instantiates an elastic easing function
  52940. * @see https://easings.net/#easeInElastic
  52941. * @param oscillations Defines the number of oscillations
  52942. * @param springiness Defines the amplitude of the oscillations
  52943. */
  52944. function ElasticEase(
  52945. /** Defines the number of oscillations*/
  52946. oscillations,
  52947. /** Defines the amplitude of the oscillations*/
  52948. springiness) {
  52949. if (oscillations === void 0) { oscillations = 3; }
  52950. if (springiness === void 0) { springiness = 3; }
  52951. var _this = _super.call(this) || this;
  52952. _this.oscillations = oscillations;
  52953. _this.springiness = springiness;
  52954. return _this;
  52955. }
  52956. /** @hidden */
  52957. ElasticEase.prototype.easeInCore = function (gradient) {
  52958. var num2;
  52959. var num3 = Math.max(0.0, this.oscillations);
  52960. var num = Math.max(0.0, this.springiness);
  52961. if (num == 0) {
  52962. num2 = gradient;
  52963. }
  52964. else {
  52965. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52966. }
  52967. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52968. };
  52969. return ElasticEase;
  52970. }(EasingFunction));
  52971. BABYLON.ElasticEase = ElasticEase;
  52972. /**
  52973. * Easing function with an exponential shape (see link below).
  52974. * @see https://easings.net/#easeInExpo
  52975. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52976. */
  52977. var ExponentialEase = /** @class */ (function (_super) {
  52978. __extends(ExponentialEase, _super);
  52979. /**
  52980. * Instantiates an exponential easing function
  52981. * @see https://easings.net/#easeInExpo
  52982. * @param exponent Defines the exponent of the function
  52983. */
  52984. function ExponentialEase(
  52985. /** Defines the exponent of the function */
  52986. exponent) {
  52987. if (exponent === void 0) { exponent = 2; }
  52988. var _this = _super.call(this) || this;
  52989. _this.exponent = exponent;
  52990. return _this;
  52991. }
  52992. /** @hidden */
  52993. ExponentialEase.prototype.easeInCore = function (gradient) {
  52994. if (this.exponent <= 0) {
  52995. return gradient;
  52996. }
  52997. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52998. };
  52999. return ExponentialEase;
  53000. }(EasingFunction));
  53001. BABYLON.ExponentialEase = ExponentialEase;
  53002. /**
  53003. * Easing function with a power shape (see link below).
  53004. * @see https://easings.net/#easeInQuad
  53005. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53006. */
  53007. var PowerEase = /** @class */ (function (_super) {
  53008. __extends(PowerEase, _super);
  53009. /**
  53010. * Instantiates an power base easing function
  53011. * @see https://easings.net/#easeInQuad
  53012. * @param power Defines the power of the function
  53013. */
  53014. function PowerEase(
  53015. /** Defines the power of the function */
  53016. power) {
  53017. if (power === void 0) { power = 2; }
  53018. var _this = _super.call(this) || this;
  53019. _this.power = power;
  53020. return _this;
  53021. }
  53022. /** @hidden */
  53023. PowerEase.prototype.easeInCore = function (gradient) {
  53024. var y = Math.max(0.0, this.power);
  53025. return Math.pow(gradient, y);
  53026. };
  53027. return PowerEase;
  53028. }(EasingFunction));
  53029. BABYLON.PowerEase = PowerEase;
  53030. /**
  53031. * Easing function with a power of 2 shape (see link below).
  53032. * @see https://easings.net/#easeInQuad
  53033. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53034. */
  53035. var QuadraticEase = /** @class */ (function (_super) {
  53036. __extends(QuadraticEase, _super);
  53037. function QuadraticEase() {
  53038. return _super !== null && _super.apply(this, arguments) || this;
  53039. }
  53040. /** @hidden */
  53041. QuadraticEase.prototype.easeInCore = function (gradient) {
  53042. return (gradient * gradient);
  53043. };
  53044. return QuadraticEase;
  53045. }(EasingFunction));
  53046. BABYLON.QuadraticEase = QuadraticEase;
  53047. /**
  53048. * Easing function with a power of 4 shape (see link below).
  53049. * @see https://easings.net/#easeInQuart
  53050. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53051. */
  53052. var QuarticEase = /** @class */ (function (_super) {
  53053. __extends(QuarticEase, _super);
  53054. function QuarticEase() {
  53055. return _super !== null && _super.apply(this, arguments) || this;
  53056. }
  53057. /** @hidden */
  53058. QuarticEase.prototype.easeInCore = function (gradient) {
  53059. return (gradient * gradient * gradient * gradient);
  53060. };
  53061. return QuarticEase;
  53062. }(EasingFunction));
  53063. BABYLON.QuarticEase = QuarticEase;
  53064. /**
  53065. * Easing function with a power of 5 shape (see link below).
  53066. * @see https://easings.net/#easeInQuint
  53067. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53068. */
  53069. var QuinticEase = /** @class */ (function (_super) {
  53070. __extends(QuinticEase, _super);
  53071. function QuinticEase() {
  53072. return _super !== null && _super.apply(this, arguments) || this;
  53073. }
  53074. /** @hidden */
  53075. QuinticEase.prototype.easeInCore = function (gradient) {
  53076. return (gradient * gradient * gradient * gradient * gradient);
  53077. };
  53078. return QuinticEase;
  53079. }(EasingFunction));
  53080. BABYLON.QuinticEase = QuinticEase;
  53081. /**
  53082. * Easing function with a sin shape (see link below).
  53083. * @see https://easings.net/#easeInSine
  53084. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53085. */
  53086. var SineEase = /** @class */ (function (_super) {
  53087. __extends(SineEase, _super);
  53088. function SineEase() {
  53089. return _super !== null && _super.apply(this, arguments) || this;
  53090. }
  53091. /** @hidden */
  53092. SineEase.prototype.easeInCore = function (gradient) {
  53093. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53094. };
  53095. return SineEase;
  53096. }(EasingFunction));
  53097. BABYLON.SineEase = SineEase;
  53098. /**
  53099. * Easing function with a bezier shape (see link below).
  53100. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53101. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53102. */
  53103. var BezierCurveEase = /** @class */ (function (_super) {
  53104. __extends(BezierCurveEase, _super);
  53105. /**
  53106. * Instantiates a bezier function
  53107. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53108. * @param x1 Defines the x component of the start tangent in the bezier curve
  53109. * @param y1 Defines the y component of the start tangent in the bezier curve
  53110. * @param x2 Defines the x component of the end tangent in the bezier curve
  53111. * @param y2 Defines the y component of the end tangent in the bezier curve
  53112. */
  53113. function BezierCurveEase(
  53114. /** Defines the x component of the start tangent in the bezier curve */
  53115. x1,
  53116. /** Defines the y component of the start tangent in the bezier curve */
  53117. y1,
  53118. /** Defines the x component of the end tangent in the bezier curve */
  53119. x2,
  53120. /** Defines the y component of the end tangent in the bezier curve */
  53121. y2) {
  53122. if (x1 === void 0) { x1 = 0; }
  53123. if (y1 === void 0) { y1 = 0; }
  53124. if (x2 === void 0) { x2 = 1; }
  53125. if (y2 === void 0) { y2 = 1; }
  53126. var _this = _super.call(this) || this;
  53127. _this.x1 = x1;
  53128. _this.y1 = y1;
  53129. _this.x2 = x2;
  53130. _this.y2 = y2;
  53131. return _this;
  53132. }
  53133. /** @hidden */
  53134. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53135. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53136. };
  53137. return BezierCurveEase;
  53138. }(EasingFunction));
  53139. BABYLON.BezierCurveEase = BezierCurveEase;
  53140. })(BABYLON || (BABYLON = {}));
  53141. //# sourceMappingURL=babylon.easing.js.map
  53142. var BABYLON;
  53143. (function (BABYLON) {
  53144. /**
  53145. * A Condition applied to an Action
  53146. */
  53147. var Condition = /** @class */ (function () {
  53148. /**
  53149. * Creates a new Condition
  53150. * @param actionManager the manager of the action the condition is applied to
  53151. */
  53152. function Condition(actionManager) {
  53153. this._actionManager = actionManager;
  53154. }
  53155. /**
  53156. * Check if the current condition is valid
  53157. * @returns a boolean
  53158. */
  53159. Condition.prototype.isValid = function () {
  53160. return true;
  53161. };
  53162. /**
  53163. * Internal only
  53164. * @hidden
  53165. */
  53166. Condition.prototype._getProperty = function (propertyPath) {
  53167. return this._actionManager._getProperty(propertyPath);
  53168. };
  53169. /**
  53170. * Internal only
  53171. * @hidden
  53172. */
  53173. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53174. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53175. };
  53176. /**
  53177. * Serialize placeholder for child classes
  53178. * @returns the serialized object
  53179. */
  53180. Condition.prototype.serialize = function () {
  53181. };
  53182. /**
  53183. * Internal only
  53184. * @hidden
  53185. */
  53186. Condition.prototype._serialize = function (serializedCondition) {
  53187. return {
  53188. type: 2,
  53189. children: [],
  53190. name: serializedCondition.name,
  53191. properties: serializedCondition.properties
  53192. };
  53193. };
  53194. return Condition;
  53195. }());
  53196. BABYLON.Condition = Condition;
  53197. /**
  53198. * Defines specific conditional operators as extensions of Condition
  53199. */
  53200. var ValueCondition = /** @class */ (function (_super) {
  53201. __extends(ValueCondition, _super);
  53202. /**
  53203. * Creates a new ValueCondition
  53204. * @param actionManager manager for the action the condition applies to
  53205. * @param target for the action
  53206. * @param propertyPath path to specify the property of the target the conditional operator uses
  53207. * @param value the value compared by the conditional operator against the current value of the property
  53208. * @param operator the conditional operator, default ValueCondition.IsEqual
  53209. */
  53210. function ValueCondition(actionManager, target,
  53211. /** path to specify the property of the target the conditional operator uses */
  53212. propertyPath,
  53213. /** the value compared by the conditional operator against the current value of the property */
  53214. value,
  53215. /** the conditional operator, default ValueCondition.IsEqual */
  53216. operator) {
  53217. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53218. var _this = _super.call(this, actionManager) || this;
  53219. _this.propertyPath = propertyPath;
  53220. _this.value = value;
  53221. _this.operator = operator;
  53222. _this._target = target;
  53223. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53224. _this._property = _this._getProperty(_this.propertyPath);
  53225. return _this;
  53226. }
  53227. Object.defineProperty(ValueCondition, "IsEqual", {
  53228. /**
  53229. * returns the number for IsEqual
  53230. */
  53231. get: function () {
  53232. return ValueCondition._IsEqual;
  53233. },
  53234. enumerable: true,
  53235. configurable: true
  53236. });
  53237. Object.defineProperty(ValueCondition, "IsDifferent", {
  53238. /**
  53239. * Returns the number for IsDifferent
  53240. */
  53241. get: function () {
  53242. return ValueCondition._IsDifferent;
  53243. },
  53244. enumerable: true,
  53245. configurable: true
  53246. });
  53247. Object.defineProperty(ValueCondition, "IsGreater", {
  53248. /**
  53249. * Returns the number for IsGreater
  53250. */
  53251. get: function () {
  53252. return ValueCondition._IsGreater;
  53253. },
  53254. enumerable: true,
  53255. configurable: true
  53256. });
  53257. Object.defineProperty(ValueCondition, "IsLesser", {
  53258. /**
  53259. * Returns the number for IsLesser
  53260. */
  53261. get: function () {
  53262. return ValueCondition._IsLesser;
  53263. },
  53264. enumerable: true,
  53265. configurable: true
  53266. });
  53267. /**
  53268. * Compares the given value with the property value for the specified conditional operator
  53269. * @returns the result of the comparison
  53270. */
  53271. ValueCondition.prototype.isValid = function () {
  53272. switch (this.operator) {
  53273. case ValueCondition.IsGreater:
  53274. return this._effectiveTarget[this._property] > this.value;
  53275. case ValueCondition.IsLesser:
  53276. return this._effectiveTarget[this._property] < this.value;
  53277. case ValueCondition.IsEqual:
  53278. case ValueCondition.IsDifferent:
  53279. var check;
  53280. if (this.value.equals) {
  53281. check = this.value.equals(this._effectiveTarget[this._property]);
  53282. }
  53283. else {
  53284. check = this.value === this._effectiveTarget[this._property];
  53285. }
  53286. return this.operator === ValueCondition.IsEqual ? check : !check;
  53287. }
  53288. return false;
  53289. };
  53290. /**
  53291. * Serialize the ValueCondition into a JSON compatible object
  53292. * @returns serialization object
  53293. */
  53294. ValueCondition.prototype.serialize = function () {
  53295. return this._serialize({
  53296. name: "ValueCondition",
  53297. properties: [
  53298. BABYLON.Action._GetTargetProperty(this._target),
  53299. { name: "propertyPath", value: this.propertyPath },
  53300. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53301. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53302. ]
  53303. });
  53304. };
  53305. /**
  53306. * Gets the name of the conditional operator for the ValueCondition
  53307. * @param operator the conditional operator
  53308. * @returns the name
  53309. */
  53310. ValueCondition.GetOperatorName = function (operator) {
  53311. switch (operator) {
  53312. case ValueCondition._IsEqual: return "IsEqual";
  53313. case ValueCondition._IsDifferent: return "IsDifferent";
  53314. case ValueCondition._IsGreater: return "IsGreater";
  53315. case ValueCondition._IsLesser: return "IsLesser";
  53316. default: return "";
  53317. }
  53318. };
  53319. /**
  53320. * Internal only
  53321. * @hidden
  53322. */
  53323. ValueCondition._IsEqual = 0;
  53324. /**
  53325. * Internal only
  53326. * @hidden
  53327. */
  53328. ValueCondition._IsDifferent = 1;
  53329. /**
  53330. * Internal only
  53331. * @hidden
  53332. */
  53333. ValueCondition._IsGreater = 2;
  53334. /**
  53335. * Internal only
  53336. * @hidden
  53337. */
  53338. ValueCondition._IsLesser = 3;
  53339. return ValueCondition;
  53340. }(Condition));
  53341. BABYLON.ValueCondition = ValueCondition;
  53342. /**
  53343. * Defines a predicate condition as an extension of Condition
  53344. */
  53345. var PredicateCondition = /** @class */ (function (_super) {
  53346. __extends(PredicateCondition, _super);
  53347. /**
  53348. * Creates a new PredicateCondition
  53349. * @param actionManager manager for the action the condition applies to
  53350. * @param predicate defines the predicate function used to validate the condition
  53351. */
  53352. function PredicateCondition(actionManager,
  53353. /** defines the predicate function used to validate the condition */
  53354. predicate) {
  53355. var _this = _super.call(this, actionManager) || this;
  53356. _this.predicate = predicate;
  53357. return _this;
  53358. }
  53359. /**
  53360. * @returns the validity of the predicate condition
  53361. */
  53362. PredicateCondition.prototype.isValid = function () {
  53363. return this.predicate();
  53364. };
  53365. return PredicateCondition;
  53366. }(Condition));
  53367. BABYLON.PredicateCondition = PredicateCondition;
  53368. /**
  53369. * Defines a state condition as an extension of Condition
  53370. */
  53371. var StateCondition = /** @class */ (function (_super) {
  53372. __extends(StateCondition, _super);
  53373. /**
  53374. * Creates a new StateCondition
  53375. * @param actionManager manager for the action the condition applies to
  53376. * @param target of the condition
  53377. * @param value to compare with target state
  53378. */
  53379. function StateCondition(actionManager, target, value) {
  53380. var _this = _super.call(this, actionManager) || this;
  53381. _this.value = value;
  53382. _this._target = target;
  53383. return _this;
  53384. }
  53385. /**
  53386. * @returns the validity of the state
  53387. */
  53388. StateCondition.prototype.isValid = function () {
  53389. return this._target.state === this.value;
  53390. };
  53391. /**
  53392. * Serialize the StateCondition into a JSON compatible object
  53393. * @returns serialization object
  53394. */
  53395. StateCondition.prototype.serialize = function () {
  53396. return this._serialize({
  53397. name: "StateCondition",
  53398. properties: [
  53399. BABYLON.Action._GetTargetProperty(this._target),
  53400. { name: "value", value: this.value }
  53401. ]
  53402. });
  53403. };
  53404. return StateCondition;
  53405. }(Condition));
  53406. BABYLON.StateCondition = StateCondition;
  53407. })(BABYLON || (BABYLON = {}));
  53408. //# sourceMappingURL=babylon.condition.js.map
  53409. var BABYLON;
  53410. (function (BABYLON) {
  53411. /**
  53412. * The action to be carried out following a trigger
  53413. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53414. */
  53415. var Action = /** @class */ (function () {
  53416. /**
  53417. * Creates a new Action
  53418. * @param triggerOptions the trigger, with or without parameters, for the action
  53419. * @param condition an optional determinant of action
  53420. */
  53421. function Action(
  53422. /** the trigger, with or without parameters, for the action */
  53423. triggerOptions, condition) {
  53424. this.triggerOptions = triggerOptions;
  53425. /**
  53426. * An event triggered prior to action being executed.
  53427. */
  53428. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53429. if (triggerOptions.parameter) {
  53430. this.trigger = triggerOptions.trigger;
  53431. this._triggerParameter = triggerOptions.parameter;
  53432. }
  53433. else if (triggerOptions.trigger) {
  53434. this.trigger = triggerOptions.trigger;
  53435. }
  53436. else {
  53437. this.trigger = triggerOptions;
  53438. }
  53439. this._nextActiveAction = this;
  53440. this._condition = condition;
  53441. }
  53442. /**
  53443. * Internal only
  53444. * @hidden
  53445. */
  53446. Action.prototype._prepare = function () {
  53447. };
  53448. /**
  53449. * Gets the trigger parameters
  53450. * @returns the trigger parameters
  53451. */
  53452. Action.prototype.getTriggerParameter = function () {
  53453. return this._triggerParameter;
  53454. };
  53455. /**
  53456. * Internal only - executes current action event
  53457. * @hidden
  53458. */
  53459. Action.prototype._executeCurrent = function (evt) {
  53460. if (this._nextActiveAction._condition) {
  53461. var condition = this._nextActiveAction._condition;
  53462. var currentRenderId = this._actionManager.getScene().getRenderId();
  53463. // We cache the current evaluation for the current frame
  53464. if (condition._evaluationId === currentRenderId) {
  53465. if (!condition._currentResult) {
  53466. return;
  53467. }
  53468. }
  53469. else {
  53470. condition._evaluationId = currentRenderId;
  53471. if (!condition.isValid()) {
  53472. condition._currentResult = false;
  53473. return;
  53474. }
  53475. condition._currentResult = true;
  53476. }
  53477. }
  53478. this.onBeforeExecuteObservable.notifyObservers(this);
  53479. this._nextActiveAction.execute(evt);
  53480. this.skipToNextActiveAction();
  53481. };
  53482. /**
  53483. * Execute placeholder for child classes
  53484. * @param evt optional action event
  53485. */
  53486. Action.prototype.execute = function (evt) {
  53487. };
  53488. /**
  53489. * Skips to next active action
  53490. */
  53491. Action.prototype.skipToNextActiveAction = function () {
  53492. if (this._nextActiveAction._child) {
  53493. if (!this._nextActiveAction._child._actionManager) {
  53494. this._nextActiveAction._child._actionManager = this._actionManager;
  53495. }
  53496. this._nextActiveAction = this._nextActiveAction._child;
  53497. }
  53498. else {
  53499. this._nextActiveAction = this;
  53500. }
  53501. };
  53502. /**
  53503. * Adds action to chain of actions, may be a DoNothingAction
  53504. * @param action defines the next action to execute
  53505. * @returns The action passed in
  53506. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53507. */
  53508. Action.prototype.then = function (action) {
  53509. this._child = action;
  53510. action._actionManager = this._actionManager;
  53511. action._prepare();
  53512. return action;
  53513. };
  53514. /**
  53515. * Internal only
  53516. * @hidden
  53517. */
  53518. Action.prototype._getProperty = function (propertyPath) {
  53519. return this._actionManager._getProperty(propertyPath);
  53520. };
  53521. /**
  53522. * Internal only
  53523. * @hidden
  53524. */
  53525. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53526. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53527. };
  53528. /**
  53529. * Serialize placeholder for child classes
  53530. * @param parent of child
  53531. * @returns the serialized object
  53532. */
  53533. Action.prototype.serialize = function (parent) {
  53534. };
  53535. /**
  53536. * Internal only called by serialize
  53537. * @hidden
  53538. */
  53539. Action.prototype._serialize = function (serializedAction, parent) {
  53540. var serializationObject = {
  53541. type: 1,
  53542. children: [],
  53543. name: serializedAction.name,
  53544. properties: serializedAction.properties || []
  53545. };
  53546. // Serialize child
  53547. if (this._child) {
  53548. this._child.serialize(serializationObject);
  53549. }
  53550. // Check if "this" has a condition
  53551. if (this._condition) {
  53552. var serializedCondition = this._condition.serialize();
  53553. serializedCondition.children.push(serializationObject);
  53554. if (parent) {
  53555. parent.children.push(serializedCondition);
  53556. }
  53557. return serializedCondition;
  53558. }
  53559. if (parent) {
  53560. parent.children.push(serializationObject);
  53561. }
  53562. return serializationObject;
  53563. };
  53564. /**
  53565. * Internal only
  53566. * @hidden
  53567. */
  53568. Action._SerializeValueAsString = function (value) {
  53569. if (typeof value === "number") {
  53570. return value.toString();
  53571. }
  53572. if (typeof value === "boolean") {
  53573. return value ? "true" : "false";
  53574. }
  53575. if (value instanceof BABYLON.Vector2) {
  53576. return value.x + ", " + value.y;
  53577. }
  53578. if (value instanceof BABYLON.Vector3) {
  53579. return value.x + ", " + value.y + ", " + value.z;
  53580. }
  53581. if (value instanceof BABYLON.Color3) {
  53582. return value.r + ", " + value.g + ", " + value.b;
  53583. }
  53584. if (value instanceof BABYLON.Color4) {
  53585. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53586. }
  53587. return value; // string
  53588. };
  53589. /**
  53590. * Internal only
  53591. * @hidden
  53592. */
  53593. Action._GetTargetProperty = function (target) {
  53594. return {
  53595. name: "target",
  53596. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53597. : target instanceof BABYLON.Light ? "LightProperties"
  53598. : target instanceof BABYLON.Camera ? "CameraProperties"
  53599. : "SceneProperties",
  53600. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53601. };
  53602. };
  53603. return Action;
  53604. }());
  53605. BABYLON.Action = Action;
  53606. })(BABYLON || (BABYLON = {}));
  53607. //# sourceMappingURL=babylon.action.js.map
  53608. var BABYLON;
  53609. (function (BABYLON) {
  53610. /**
  53611. * ActionEvent is the event being sent when an action is triggered.
  53612. */
  53613. var ActionEvent = /** @class */ (function () {
  53614. /**
  53615. * Creates a new ActionEvent
  53616. * @param source The mesh or sprite that triggered the action
  53617. * @param pointerX The X mouse cursor position at the time of the event
  53618. * @param pointerY The Y mouse cursor position at the time of the event
  53619. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53620. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53621. * @param additionalData additional data for the event
  53622. */
  53623. function ActionEvent(
  53624. /** The mesh or sprite that triggered the action */
  53625. source,
  53626. /** The X mouse cursor position at the time of the event */
  53627. pointerX,
  53628. /** The Y mouse cursor position at the time of the event */
  53629. pointerY,
  53630. /** The mesh that is currently pointed at (can be null) */
  53631. meshUnderPointer,
  53632. /** the original (browser) event that triggered the ActionEvent */
  53633. sourceEvent,
  53634. /** additional data for the event */
  53635. additionalData) {
  53636. this.source = source;
  53637. this.pointerX = pointerX;
  53638. this.pointerY = pointerY;
  53639. this.meshUnderPointer = meshUnderPointer;
  53640. this.sourceEvent = sourceEvent;
  53641. this.additionalData = additionalData;
  53642. }
  53643. /**
  53644. * Helper function to auto-create an ActionEvent from a source mesh.
  53645. * @param source The source mesh that triggered the event
  53646. * @param evt The original (browser) event
  53647. * @param additionalData additional data for the event
  53648. * @returns the new ActionEvent
  53649. */
  53650. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53651. var scene = source.getScene();
  53652. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53653. };
  53654. /**
  53655. * Helper function to auto-create an ActionEvent from a source sprite
  53656. * @param source The source sprite that triggered the event
  53657. * @param scene Scene associated with the sprite
  53658. * @param evt The original (browser) event
  53659. * @param additionalData additional data for the event
  53660. * @returns the new ActionEvent
  53661. */
  53662. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53663. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53664. };
  53665. /**
  53666. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53667. * @param scene the scene where the event occurred
  53668. * @param evt The original (browser) event
  53669. * @returns the new ActionEvent
  53670. */
  53671. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53672. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53673. };
  53674. /**
  53675. * Helper function to auto-create an ActionEvent from a primitive
  53676. * @param prim defines the target primitive
  53677. * @param pointerPos defines the pointer position
  53678. * @param evt The original (browser) event
  53679. * @param additionalData additional data for the event
  53680. * @returns the new ActionEvent
  53681. */
  53682. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53683. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53684. };
  53685. return ActionEvent;
  53686. }());
  53687. BABYLON.ActionEvent = ActionEvent;
  53688. /**
  53689. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53690. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53691. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53692. */
  53693. var ActionManager = /** @class */ (function () {
  53694. /**
  53695. * Creates a new action manager
  53696. * @param scene defines the hosting scene
  53697. */
  53698. function ActionManager(scene) {
  53699. // Members
  53700. /** Gets the list of actions */
  53701. this.actions = new Array();
  53702. /** Gets the cursor to use when hovering items */
  53703. this.hoverCursor = '';
  53704. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53705. scene.actionManagers.push(this);
  53706. }
  53707. // Methods
  53708. /**
  53709. * Releases all associated resources
  53710. */
  53711. ActionManager.prototype.dispose = function () {
  53712. var index = this._scene.actionManagers.indexOf(this);
  53713. for (var i = 0; i < this.actions.length; i++) {
  53714. var action = this.actions[i];
  53715. ActionManager.Triggers[action.trigger]--;
  53716. if (ActionManager.Triggers[action.trigger] === 0) {
  53717. delete ActionManager.Triggers[action.trigger];
  53718. }
  53719. }
  53720. if (index > -1) {
  53721. this._scene.actionManagers.splice(index, 1);
  53722. }
  53723. };
  53724. /**
  53725. * Gets hosting scene
  53726. * @returns the hosting scene
  53727. */
  53728. ActionManager.prototype.getScene = function () {
  53729. return this._scene;
  53730. };
  53731. /**
  53732. * Does this action manager handles actions of any of the given triggers
  53733. * @param triggers defines the triggers to be tested
  53734. * @return a boolean indicating whether one (or more) of the triggers is handled
  53735. */
  53736. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53737. for (var index = 0; index < this.actions.length; index++) {
  53738. var action = this.actions[index];
  53739. if (triggers.indexOf(action.trigger) > -1) {
  53740. return true;
  53741. }
  53742. }
  53743. return false;
  53744. };
  53745. /**
  53746. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  53747. * speed.
  53748. * @param triggerA defines the trigger to be tested
  53749. * @param triggerB defines the trigger to be tested
  53750. * @return a boolean indicating whether one (or more) of the triggers is handled
  53751. */
  53752. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53753. for (var index = 0; index < this.actions.length; index++) {
  53754. var action = this.actions[index];
  53755. if (triggerA == action.trigger || triggerB == action.trigger) {
  53756. return true;
  53757. }
  53758. }
  53759. return false;
  53760. };
  53761. /**
  53762. * Does this action manager handles actions of a given trigger
  53763. * @param trigger defines the trigger to be tested
  53764. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53765. * @return whether the trigger is handled
  53766. */
  53767. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53768. for (var index = 0; index < this.actions.length; index++) {
  53769. var action = this.actions[index];
  53770. if (action.trigger === trigger) {
  53771. if (parameterPredicate) {
  53772. if (parameterPredicate(action.getTriggerParameter())) {
  53773. return true;
  53774. }
  53775. }
  53776. else {
  53777. return true;
  53778. }
  53779. }
  53780. }
  53781. return false;
  53782. };
  53783. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53784. /**
  53785. * Does this action manager has pointer triggers
  53786. */
  53787. get: function () {
  53788. for (var index = 0; index < this.actions.length; index++) {
  53789. var action = this.actions[index];
  53790. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  53791. return true;
  53792. }
  53793. }
  53794. return false;
  53795. },
  53796. enumerable: true,
  53797. configurable: true
  53798. });
  53799. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53800. /**
  53801. * Does this action manager has pick triggers
  53802. */
  53803. get: function () {
  53804. for (var index = 0; index < this.actions.length; index++) {
  53805. var action = this.actions[index];
  53806. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  53807. return true;
  53808. }
  53809. }
  53810. return false;
  53811. },
  53812. enumerable: true,
  53813. configurable: true
  53814. });
  53815. Object.defineProperty(ActionManager, "HasTriggers", {
  53816. /**
  53817. * Does exist one action manager with at least one trigger
  53818. **/
  53819. get: function () {
  53820. for (var t in ActionManager.Triggers) {
  53821. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53822. return true;
  53823. }
  53824. }
  53825. return false;
  53826. },
  53827. enumerable: true,
  53828. configurable: true
  53829. });
  53830. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53831. /**
  53832. * Does exist one action manager with at least one pick trigger
  53833. **/
  53834. get: function () {
  53835. for (var t in ActionManager.Triggers) {
  53836. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53837. var t_int = parseInt(t);
  53838. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  53839. return true;
  53840. }
  53841. }
  53842. }
  53843. return false;
  53844. },
  53845. enumerable: true,
  53846. configurable: true
  53847. });
  53848. /**
  53849. * Does exist one action manager that handles actions of a given trigger
  53850. * @param trigger defines the trigger to be tested
  53851. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53852. **/
  53853. ActionManager.HasSpecificTrigger = function (trigger) {
  53854. for (var t in ActionManager.Triggers) {
  53855. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53856. var t_int = parseInt(t);
  53857. if (t_int === trigger) {
  53858. return true;
  53859. }
  53860. }
  53861. }
  53862. return false;
  53863. };
  53864. /**
  53865. * Registers an action to this action manager
  53866. * @param action defines the action to be registered
  53867. * @return the action amended (prepared) after registration
  53868. */
  53869. ActionManager.prototype.registerAction = function (action) {
  53870. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53871. if (this.getScene().actionManager !== this) {
  53872. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53873. return null;
  53874. }
  53875. }
  53876. this.actions.push(action);
  53877. if (ActionManager.Triggers[action.trigger]) {
  53878. ActionManager.Triggers[action.trigger]++;
  53879. }
  53880. else {
  53881. ActionManager.Triggers[action.trigger] = 1;
  53882. }
  53883. action._actionManager = this;
  53884. action._prepare();
  53885. return action;
  53886. };
  53887. /**
  53888. * Unregisters an action to this action manager
  53889. * @param action defines the action to be unregistered
  53890. * @return a boolean indicating whether the action has been unregistered
  53891. */
  53892. ActionManager.prototype.unregisterAction = function (action) {
  53893. var index = this.actions.indexOf(action);
  53894. if (index !== -1) {
  53895. this.actions.splice(index, 1);
  53896. ActionManager.Triggers[action.trigger] -= 1;
  53897. if (ActionManager.Triggers[action.trigger] === 0) {
  53898. delete ActionManager.Triggers[action.trigger];
  53899. }
  53900. delete action._actionManager;
  53901. return true;
  53902. }
  53903. return false;
  53904. };
  53905. /**
  53906. * Process a specific trigger
  53907. * @param trigger defines the trigger to process
  53908. * @param evt defines the event details to be processed
  53909. */
  53910. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53911. for (var index = 0; index < this.actions.length; index++) {
  53912. var action = this.actions[index];
  53913. if (action.trigger === trigger) {
  53914. if (evt) {
  53915. if (trigger === ActionManager.OnKeyUpTrigger
  53916. || trigger === ActionManager.OnKeyDownTrigger) {
  53917. var parameter = action.getTriggerParameter();
  53918. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53919. if (!parameter.toLowerCase) {
  53920. continue;
  53921. }
  53922. var lowerCase = parameter.toLowerCase();
  53923. if (lowerCase !== evt.sourceEvent.key) {
  53924. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53925. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53926. if (actualkey !== lowerCase) {
  53927. continue;
  53928. }
  53929. }
  53930. }
  53931. }
  53932. }
  53933. action._executeCurrent(evt);
  53934. }
  53935. }
  53936. };
  53937. /** @hidden */
  53938. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53939. var properties = propertyPath.split(".");
  53940. for (var index = 0; index < properties.length - 1; index++) {
  53941. target = target[properties[index]];
  53942. }
  53943. return target;
  53944. };
  53945. /** @hidden */
  53946. ActionManager.prototype._getProperty = function (propertyPath) {
  53947. var properties = propertyPath.split(".");
  53948. return properties[properties.length - 1];
  53949. };
  53950. /**
  53951. * Serialize this manager to a JSON object
  53952. * @param name defines the property name to store this manager
  53953. * @returns a JSON representation of this manager
  53954. */
  53955. ActionManager.prototype.serialize = function (name) {
  53956. var root = {
  53957. children: new Array(),
  53958. name: name,
  53959. type: 3,
  53960. properties: new Array() // Empty for root but required
  53961. };
  53962. for (var i = 0; i < this.actions.length; i++) {
  53963. var triggerObject = {
  53964. type: 0,
  53965. children: new Array(),
  53966. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53967. properties: new Array()
  53968. };
  53969. var triggerOptions = this.actions[i].triggerOptions;
  53970. if (triggerOptions && typeof triggerOptions !== "number") {
  53971. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53972. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53973. }
  53974. else {
  53975. var parameter = {};
  53976. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53977. if (triggerOptions.parameter.mesh) {
  53978. parameter._meshId = triggerOptions.parameter.mesh.id;
  53979. }
  53980. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53981. }
  53982. }
  53983. // Serialize child action, recursively
  53984. this.actions[i].serialize(triggerObject);
  53985. // Add serialized trigger
  53986. root.children.push(triggerObject);
  53987. }
  53988. return root;
  53989. };
  53990. /**
  53991. * Creates a new ActionManager from a JSON data
  53992. * @param parsedActions defines the JSON data to read from
  53993. * @param object defines the hosting mesh
  53994. * @param scene defines the hosting scene
  53995. */
  53996. ActionManager.Parse = function (parsedActions, object, scene) {
  53997. var actionManager = new ActionManager(scene);
  53998. if (object === null)
  53999. scene.actionManager = actionManager;
  54000. else
  54001. object.actionManager = actionManager;
  54002. // instanciate a new object
  54003. var instanciate = function (name, params) {
  54004. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54005. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54006. newInstance.constructor.apply(newInstance, params);
  54007. return newInstance;
  54008. };
  54009. var parseParameter = function (name, value, target, propertyPath) {
  54010. if (propertyPath === null) {
  54011. // String, boolean or float
  54012. var floatValue = parseFloat(value);
  54013. if (value === "true" || value === "false")
  54014. return value === "true";
  54015. else
  54016. return isNaN(floatValue) ? value : floatValue;
  54017. }
  54018. var effectiveTarget = propertyPath.split(".");
  54019. var values = value.split(",");
  54020. // Get effective Target
  54021. for (var i = 0; i < effectiveTarget.length; i++) {
  54022. target = target[effectiveTarget[i]];
  54023. }
  54024. // Return appropriate value with its type
  54025. if (typeof (target) === "boolean")
  54026. return values[0] === "true";
  54027. if (typeof (target) === "string")
  54028. return values[0];
  54029. // Parameters with multiple values such as Vector3 etc.
  54030. var split = new Array();
  54031. for (var i = 0; i < values.length; i++)
  54032. split.push(parseFloat(values[i]));
  54033. if (target instanceof BABYLON.Vector3)
  54034. return BABYLON.Vector3.FromArray(split);
  54035. if (target instanceof BABYLON.Vector4)
  54036. return BABYLON.Vector4.FromArray(split);
  54037. if (target instanceof BABYLON.Color3)
  54038. return BABYLON.Color3.FromArray(split);
  54039. if (target instanceof BABYLON.Color4)
  54040. return BABYLON.Color4.FromArray(split);
  54041. return parseFloat(values[0]);
  54042. };
  54043. // traverse graph per trigger
  54044. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54045. if (combineArray === void 0) { combineArray = null; }
  54046. if (parsedAction.detached)
  54047. return;
  54048. var parameters = new Array();
  54049. var target = null;
  54050. var propertyPath = null;
  54051. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54052. // Parameters
  54053. if (parsedAction.type === 2)
  54054. parameters.push(actionManager);
  54055. else
  54056. parameters.push(trigger);
  54057. if (combine) {
  54058. var actions = new Array();
  54059. for (var j = 0; j < parsedAction.combine.length; j++) {
  54060. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54061. }
  54062. parameters.push(actions);
  54063. }
  54064. else {
  54065. for (var i = 0; i < parsedAction.properties.length; i++) {
  54066. var value = parsedAction.properties[i].value;
  54067. var name = parsedAction.properties[i].name;
  54068. var targetType = parsedAction.properties[i].targetType;
  54069. if (name === "target")
  54070. if (targetType !== null && targetType === "SceneProperties")
  54071. value = target = scene;
  54072. else
  54073. value = target = scene.getNodeByName(value);
  54074. else if (name === "parent")
  54075. value = scene.getNodeByName(value);
  54076. else if (name === "sound") {
  54077. // Can not externalize to component, so only checks for the presence off the API.
  54078. if (scene.getSoundByName) {
  54079. value = scene.getSoundByName(value);
  54080. }
  54081. }
  54082. else if (name !== "propertyPath") {
  54083. if (parsedAction.type === 2 && name === "operator")
  54084. value = BABYLON.ValueCondition[value];
  54085. else
  54086. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54087. }
  54088. else {
  54089. propertyPath = value;
  54090. }
  54091. parameters.push(value);
  54092. }
  54093. }
  54094. if (combineArray === null) {
  54095. parameters.push(condition);
  54096. }
  54097. else {
  54098. parameters.push(null);
  54099. }
  54100. // If interpolate value action
  54101. if (parsedAction.name === "InterpolateValueAction") {
  54102. var param = parameters[parameters.length - 2];
  54103. parameters[parameters.length - 1] = param;
  54104. parameters[parameters.length - 2] = condition;
  54105. }
  54106. // Action or condition(s) and not CombineAction
  54107. var newAction = instanciate(parsedAction.name, parameters);
  54108. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54109. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54110. if (action)
  54111. action.then(nothing);
  54112. else
  54113. actionManager.registerAction(nothing);
  54114. action = nothing;
  54115. }
  54116. if (combineArray === null) {
  54117. if (newAction instanceof BABYLON.Condition) {
  54118. condition = newAction;
  54119. newAction = action;
  54120. }
  54121. else {
  54122. condition = null;
  54123. if (action)
  54124. action.then(newAction);
  54125. else
  54126. actionManager.registerAction(newAction);
  54127. }
  54128. }
  54129. else {
  54130. combineArray.push(newAction);
  54131. }
  54132. for (var i = 0; i < parsedAction.children.length; i++)
  54133. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54134. };
  54135. // triggers
  54136. for (var i = 0; i < parsedActions.children.length; i++) {
  54137. var triggerParams;
  54138. var trigger = parsedActions.children[i];
  54139. if (trigger.properties.length > 0) {
  54140. var param = trigger.properties[0].value;
  54141. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54142. if (value._meshId) {
  54143. value.mesh = scene.getMeshByID(value._meshId);
  54144. }
  54145. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54146. }
  54147. else
  54148. triggerParams = ActionManager[trigger.name];
  54149. for (var j = 0; j < trigger.children.length; j++) {
  54150. if (!trigger.detached)
  54151. traverse(trigger.children[j], triggerParams, null, null);
  54152. }
  54153. }
  54154. };
  54155. /**
  54156. * Get a trigger name by index
  54157. * @param trigger defines the trigger index
  54158. * @returns a trigger name
  54159. */
  54160. ActionManager.GetTriggerName = function (trigger) {
  54161. switch (trigger) {
  54162. case 0: return "NothingTrigger";
  54163. case 1: return "OnPickTrigger";
  54164. case 2: return "OnLeftPickTrigger";
  54165. case 3: return "OnRightPickTrigger";
  54166. case 4: return "OnCenterPickTrigger";
  54167. case 5: return "OnPickDownTrigger";
  54168. case 6: return "OnPickUpTrigger";
  54169. case 7: return "OnLongPressTrigger";
  54170. case 8: return "OnPointerOverTrigger";
  54171. case 9: return "OnPointerOutTrigger";
  54172. case 10: return "OnEveryFrameTrigger";
  54173. case 11: return "OnIntersectionEnterTrigger";
  54174. case 12: return "OnIntersectionExitTrigger";
  54175. case 13: return "OnKeyDownTrigger";
  54176. case 14: return "OnKeyUpTrigger";
  54177. case 15: return "OnPickOutTrigger";
  54178. default: return "";
  54179. }
  54180. };
  54181. /**
  54182. * Nothing
  54183. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54184. */
  54185. ActionManager.NothingTrigger = 0;
  54186. /**
  54187. * On pick
  54188. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54189. */
  54190. ActionManager.OnPickTrigger = 1;
  54191. /**
  54192. * On left pick
  54193. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54194. */
  54195. ActionManager.OnLeftPickTrigger = 2;
  54196. /**
  54197. * On right pick
  54198. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54199. */
  54200. ActionManager.OnRightPickTrigger = 3;
  54201. /**
  54202. * On center pick
  54203. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54204. */
  54205. ActionManager.OnCenterPickTrigger = 4;
  54206. /**
  54207. * On pick down
  54208. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54209. */
  54210. ActionManager.OnPickDownTrigger = 5;
  54211. /**
  54212. * On double pick
  54213. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54214. */
  54215. ActionManager.OnDoublePickTrigger = 6;
  54216. /**
  54217. * On pick up
  54218. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54219. */
  54220. ActionManager.OnPickUpTrigger = 7;
  54221. /**
  54222. * On pick out.
  54223. * This trigger will only be raised if you also declared a OnPickDown
  54224. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54225. */
  54226. ActionManager.OnPickOutTrigger = 16;
  54227. /**
  54228. * On long press
  54229. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54230. */
  54231. ActionManager.OnLongPressTrigger = 8;
  54232. /**
  54233. * On pointer over
  54234. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54235. */
  54236. ActionManager.OnPointerOverTrigger = 9;
  54237. /**
  54238. * On pointer out
  54239. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54240. */
  54241. ActionManager.OnPointerOutTrigger = 10;
  54242. /**
  54243. * On every frame
  54244. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54245. */
  54246. ActionManager.OnEveryFrameTrigger = 11;
  54247. /**
  54248. * On intersection enter
  54249. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54250. */
  54251. ActionManager.OnIntersectionEnterTrigger = 12;
  54252. /**
  54253. * On intersection exit
  54254. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54255. */
  54256. ActionManager.OnIntersectionExitTrigger = 13;
  54257. /**
  54258. * On key down
  54259. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54260. */
  54261. ActionManager.OnKeyDownTrigger = 14;
  54262. /**
  54263. * On key up
  54264. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54265. */
  54266. ActionManager.OnKeyUpTrigger = 15;
  54267. /** Gets the list of active triggers */
  54268. ActionManager.Triggers = {};
  54269. return ActionManager;
  54270. }());
  54271. BABYLON.ActionManager = ActionManager;
  54272. })(BABYLON || (BABYLON = {}));
  54273. //# sourceMappingURL=babylon.actionManager.js.map
  54274. var BABYLON;
  54275. (function (BABYLON) {
  54276. /**
  54277. * This defines an action responsible to change the value of a property
  54278. * by interpolating between its current value and the newly set one once triggered.
  54279. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54280. */
  54281. var InterpolateValueAction = /** @class */ (function (_super) {
  54282. __extends(InterpolateValueAction, _super);
  54283. /**
  54284. * Instantiate the action
  54285. * @param triggerOptions defines the trigger options
  54286. * @param target defines the object containing the value to interpolate
  54287. * @param propertyPath defines the path to the property in the target object
  54288. * @param value defines the target value at the end of the interpolation
  54289. * @param duration deines the time it will take for the property to interpolate to the value.
  54290. * @param condition defines the trigger related conditions
  54291. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  54292. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  54293. */
  54294. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54295. if (duration === void 0) { duration = 1000; }
  54296. var _this = _super.call(this, triggerOptions, condition) || this;
  54297. /**
  54298. * Defines the time it will take for the property to interpolate to the value.
  54299. */
  54300. _this.duration = 1000;
  54301. /**
  54302. * Observable triggered once the interpolation animation has been done.
  54303. */
  54304. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54305. _this.propertyPath = propertyPath;
  54306. _this.value = value;
  54307. _this.duration = duration;
  54308. _this.stopOtherAnimations = stopOtherAnimations;
  54309. _this.onInterpolationDone = onInterpolationDone;
  54310. _this._target = _this._effectiveTarget = target;
  54311. return _this;
  54312. }
  54313. /** @hidden */
  54314. InterpolateValueAction.prototype._prepare = function () {
  54315. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54316. this._property = this._getProperty(this.propertyPath);
  54317. };
  54318. /**
  54319. * Execute the action starts the value interpolation.
  54320. */
  54321. InterpolateValueAction.prototype.execute = function () {
  54322. var _this = this;
  54323. var scene = this._actionManager.getScene();
  54324. var keys = [
  54325. {
  54326. frame: 0,
  54327. value: this._effectiveTarget[this._property]
  54328. }, {
  54329. frame: 100,
  54330. value: this.value
  54331. }
  54332. ];
  54333. var dataType;
  54334. if (typeof this.value === "number") {
  54335. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54336. }
  54337. else if (this.value instanceof BABYLON.Color3) {
  54338. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54339. }
  54340. else if (this.value instanceof BABYLON.Vector3) {
  54341. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54342. }
  54343. else if (this.value instanceof BABYLON.Matrix) {
  54344. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54345. }
  54346. else if (this.value instanceof BABYLON.Quaternion) {
  54347. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54348. }
  54349. else {
  54350. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54351. return;
  54352. }
  54353. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54354. animation.setKeys(keys);
  54355. if (this.stopOtherAnimations) {
  54356. scene.stopAnimation(this._effectiveTarget);
  54357. }
  54358. var wrapper = function () {
  54359. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54360. if (_this.onInterpolationDone) {
  54361. _this.onInterpolationDone();
  54362. }
  54363. };
  54364. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54365. };
  54366. /**
  54367. * Serializes the actions and its related information.
  54368. * @param parent defines the object to serialize in
  54369. * @returns the serialized object
  54370. */
  54371. InterpolateValueAction.prototype.serialize = function (parent) {
  54372. return _super.prototype._serialize.call(this, {
  54373. name: "InterpolateValueAction",
  54374. properties: [
  54375. BABYLON.Action._GetTargetProperty(this._target),
  54376. { name: "propertyPath", value: this.propertyPath },
  54377. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54378. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54379. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54380. ]
  54381. }, parent);
  54382. };
  54383. return InterpolateValueAction;
  54384. }(BABYLON.Action));
  54385. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54386. })(BABYLON || (BABYLON = {}));
  54387. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54388. var BABYLON;
  54389. (function (BABYLON) {
  54390. /**
  54391. * This defines an action responsible to toggle a boolean once triggered.
  54392. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54393. */
  54394. var SwitchBooleanAction = /** @class */ (function (_super) {
  54395. __extends(SwitchBooleanAction, _super);
  54396. /**
  54397. * Instantiate the action
  54398. * @param triggerOptions defines the trigger options
  54399. * @param target defines the object containing the boolean
  54400. * @param propertyPath defines the path to the boolean property in the target object
  54401. * @param condition defines the trigger related conditions
  54402. */
  54403. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54404. var _this = _super.call(this, triggerOptions, condition) || this;
  54405. _this.propertyPath = propertyPath;
  54406. _this._target = _this._effectiveTarget = target;
  54407. return _this;
  54408. }
  54409. /** @hidden */
  54410. SwitchBooleanAction.prototype._prepare = function () {
  54411. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54412. this._property = this._getProperty(this.propertyPath);
  54413. };
  54414. /**
  54415. * Execute the action toggle the boolean value.
  54416. */
  54417. SwitchBooleanAction.prototype.execute = function () {
  54418. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54419. };
  54420. /**
  54421. * Serializes the actions and its related information.
  54422. * @param parent defines the object to serialize in
  54423. * @returns the serialized object
  54424. */
  54425. SwitchBooleanAction.prototype.serialize = function (parent) {
  54426. return _super.prototype._serialize.call(this, {
  54427. name: "SwitchBooleanAction",
  54428. properties: [
  54429. BABYLON.Action._GetTargetProperty(this._target),
  54430. { name: "propertyPath", value: this.propertyPath }
  54431. ]
  54432. }, parent);
  54433. };
  54434. return SwitchBooleanAction;
  54435. }(BABYLON.Action));
  54436. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54437. /**
  54438. * This defines an action responsible to set a the state field of the target
  54439. * to a desired value once triggered.
  54440. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54441. */
  54442. var SetStateAction = /** @class */ (function (_super) {
  54443. __extends(SetStateAction, _super);
  54444. /**
  54445. * Instantiate the action
  54446. * @param triggerOptions defines the trigger options
  54447. * @param target defines the object containing the state property
  54448. * @param value defines the value to store in the state field
  54449. * @param condition defines the trigger related conditions
  54450. */
  54451. function SetStateAction(triggerOptions, target, value, condition) {
  54452. var _this = _super.call(this, triggerOptions, condition) || this;
  54453. _this.value = value;
  54454. _this._target = target;
  54455. return _this;
  54456. }
  54457. /**
  54458. * Execute the action and store the value on the target state property.
  54459. */
  54460. SetStateAction.prototype.execute = function () {
  54461. this._target.state = this.value;
  54462. };
  54463. /**
  54464. * Serializes the actions and its related information.
  54465. * @param parent defines the object to serialize in
  54466. * @returns the serialized object
  54467. */
  54468. SetStateAction.prototype.serialize = function (parent) {
  54469. return _super.prototype._serialize.call(this, {
  54470. name: "SetStateAction",
  54471. properties: [
  54472. BABYLON.Action._GetTargetProperty(this._target),
  54473. { name: "value", value: this.value }
  54474. ]
  54475. }, parent);
  54476. };
  54477. return SetStateAction;
  54478. }(BABYLON.Action));
  54479. BABYLON.SetStateAction = SetStateAction;
  54480. /**
  54481. * This defines an action responsible to set a property of the target
  54482. * to a desired value once triggered.
  54483. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54484. */
  54485. var SetValueAction = /** @class */ (function (_super) {
  54486. __extends(SetValueAction, _super);
  54487. /**
  54488. * Instantiate the action
  54489. * @param triggerOptions defines the trigger options
  54490. * @param target defines the object containing the property
  54491. * @param propertyPath defines the path of the property to set in the target
  54492. * @param value defines the value to set in the property
  54493. * @param condition defines the trigger related conditions
  54494. */
  54495. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54496. var _this = _super.call(this, triggerOptions, condition) || this;
  54497. _this.propertyPath = propertyPath;
  54498. _this.value = value;
  54499. _this._target = _this._effectiveTarget = target;
  54500. return _this;
  54501. }
  54502. /** @hidden */
  54503. SetValueAction.prototype._prepare = function () {
  54504. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54505. this._property = this._getProperty(this.propertyPath);
  54506. };
  54507. /**
  54508. * Execute the action and set the targetted property to the desired value.
  54509. */
  54510. SetValueAction.prototype.execute = function () {
  54511. this._effectiveTarget[this._property] = this.value;
  54512. if (this._target.markAsDirty) {
  54513. this._target.markAsDirty(this._property);
  54514. }
  54515. };
  54516. /**
  54517. * Serializes the actions and its related information.
  54518. * @param parent defines the object to serialize in
  54519. * @returns the serialized object
  54520. */
  54521. SetValueAction.prototype.serialize = function (parent) {
  54522. return _super.prototype._serialize.call(this, {
  54523. name: "SetValueAction",
  54524. properties: [
  54525. BABYLON.Action._GetTargetProperty(this._target),
  54526. { name: "propertyPath", value: this.propertyPath },
  54527. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54528. ]
  54529. }, parent);
  54530. };
  54531. return SetValueAction;
  54532. }(BABYLON.Action));
  54533. BABYLON.SetValueAction = SetValueAction;
  54534. /**
  54535. * This defines an action responsible to increment the target value
  54536. * to a desired value once triggered.
  54537. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54538. */
  54539. var IncrementValueAction = /** @class */ (function (_super) {
  54540. __extends(IncrementValueAction, _super);
  54541. /**
  54542. * Instantiate the action
  54543. * @param triggerOptions defines the trigger options
  54544. * @param target defines the object containing the property
  54545. * @param propertyPath defines the path of the property to increment in the target
  54546. * @param value defines the value value we should increment the property by
  54547. * @param condition defines the trigger related conditions
  54548. */
  54549. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54550. var _this = _super.call(this, triggerOptions, condition) || this;
  54551. _this.propertyPath = propertyPath;
  54552. _this.value = value;
  54553. _this._target = _this._effectiveTarget = target;
  54554. return _this;
  54555. }
  54556. /** @hidden */
  54557. IncrementValueAction.prototype._prepare = function () {
  54558. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54559. this._property = this._getProperty(this.propertyPath);
  54560. if (typeof this._effectiveTarget[this._property] !== "number") {
  54561. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54562. }
  54563. };
  54564. /**
  54565. * Execute the action and increment the target of the value amount.
  54566. */
  54567. IncrementValueAction.prototype.execute = function () {
  54568. this._effectiveTarget[this._property] += this.value;
  54569. if (this._target.markAsDirty) {
  54570. this._target.markAsDirty(this._property);
  54571. }
  54572. };
  54573. /**
  54574. * Serializes the actions and its related information.
  54575. * @param parent defines the object to serialize in
  54576. * @returns the serialized object
  54577. */
  54578. IncrementValueAction.prototype.serialize = function (parent) {
  54579. return _super.prototype._serialize.call(this, {
  54580. name: "IncrementValueAction",
  54581. properties: [
  54582. BABYLON.Action._GetTargetProperty(this._target),
  54583. { name: "propertyPath", value: this.propertyPath },
  54584. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54585. ]
  54586. }, parent);
  54587. };
  54588. return IncrementValueAction;
  54589. }(BABYLON.Action));
  54590. BABYLON.IncrementValueAction = IncrementValueAction;
  54591. /**
  54592. * This defines an action responsible to start an animation once triggered.
  54593. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54594. */
  54595. var PlayAnimationAction = /** @class */ (function (_super) {
  54596. __extends(PlayAnimationAction, _super);
  54597. /**
  54598. * Instantiate the action
  54599. * @param triggerOptions defines the trigger options
  54600. * @param target defines the target animation or animation name
  54601. * @param from defines from where the animation should start (animation frame)
  54602. * @param end defines where the animation should stop (animation frame)
  54603. * @param loop defines if the animation should loop or stop after the first play
  54604. * @param condition defines the trigger related conditions
  54605. */
  54606. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54607. var _this = _super.call(this, triggerOptions, condition) || this;
  54608. _this.from = from;
  54609. _this.to = to;
  54610. _this.loop = loop;
  54611. _this._target = target;
  54612. return _this;
  54613. }
  54614. /** @hidden */
  54615. PlayAnimationAction.prototype._prepare = function () {
  54616. };
  54617. /**
  54618. * Execute the action and play the animation.
  54619. */
  54620. PlayAnimationAction.prototype.execute = function () {
  54621. var scene = this._actionManager.getScene();
  54622. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54623. };
  54624. /**
  54625. * Serializes the actions and its related information.
  54626. * @param parent defines the object to serialize in
  54627. * @returns the serialized object
  54628. */
  54629. PlayAnimationAction.prototype.serialize = function (parent) {
  54630. return _super.prototype._serialize.call(this, {
  54631. name: "PlayAnimationAction",
  54632. properties: [
  54633. BABYLON.Action._GetTargetProperty(this._target),
  54634. { name: "from", value: String(this.from) },
  54635. { name: "to", value: String(this.to) },
  54636. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54637. ]
  54638. }, parent);
  54639. };
  54640. return PlayAnimationAction;
  54641. }(BABYLON.Action));
  54642. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54643. /**
  54644. * This defines an action responsible to stop an animation once triggered.
  54645. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54646. */
  54647. var StopAnimationAction = /** @class */ (function (_super) {
  54648. __extends(StopAnimationAction, _super);
  54649. /**
  54650. * Instantiate the action
  54651. * @param triggerOptions defines the trigger options
  54652. * @param target defines the target animation or animation name
  54653. * @param condition defines the trigger related conditions
  54654. */
  54655. function StopAnimationAction(triggerOptions, target, condition) {
  54656. var _this = _super.call(this, triggerOptions, condition) || this;
  54657. _this._target = target;
  54658. return _this;
  54659. }
  54660. /** @hidden */
  54661. StopAnimationAction.prototype._prepare = function () {
  54662. };
  54663. /**
  54664. * Execute the action and stop the animation.
  54665. */
  54666. StopAnimationAction.prototype.execute = function () {
  54667. var scene = this._actionManager.getScene();
  54668. scene.stopAnimation(this._target);
  54669. };
  54670. /**
  54671. * Serializes the actions and its related information.
  54672. * @param parent defines the object to serialize in
  54673. * @returns the serialized object
  54674. */
  54675. StopAnimationAction.prototype.serialize = function (parent) {
  54676. return _super.prototype._serialize.call(this, {
  54677. name: "StopAnimationAction",
  54678. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54679. }, parent);
  54680. };
  54681. return StopAnimationAction;
  54682. }(BABYLON.Action));
  54683. BABYLON.StopAnimationAction = StopAnimationAction;
  54684. /**
  54685. * This defines an action responsible that does nothing once triggered.
  54686. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54687. */
  54688. var DoNothingAction = /** @class */ (function (_super) {
  54689. __extends(DoNothingAction, _super);
  54690. /**
  54691. * Instantiate the action
  54692. * @param triggerOptions defines the trigger options
  54693. * @param condition defines the trigger related conditions
  54694. */
  54695. function DoNothingAction(triggerOptions, condition) {
  54696. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54697. return _super.call(this, triggerOptions, condition) || this;
  54698. }
  54699. /**
  54700. * Execute the action and do nothing.
  54701. */
  54702. DoNothingAction.prototype.execute = function () {
  54703. };
  54704. /**
  54705. * Serializes the actions and its related information.
  54706. * @param parent defines the object to serialize in
  54707. * @returns the serialized object
  54708. */
  54709. DoNothingAction.prototype.serialize = function (parent) {
  54710. return _super.prototype._serialize.call(this, {
  54711. name: "DoNothingAction",
  54712. properties: []
  54713. }, parent);
  54714. };
  54715. return DoNothingAction;
  54716. }(BABYLON.Action));
  54717. BABYLON.DoNothingAction = DoNothingAction;
  54718. /**
  54719. * This defines an action responsible to trigger several actions once triggered.
  54720. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54721. */
  54722. var CombineAction = /** @class */ (function (_super) {
  54723. __extends(CombineAction, _super);
  54724. /**
  54725. * Instantiate the action
  54726. * @param triggerOptions defines the trigger options
  54727. * @param children defines the list of aggregated animations to run
  54728. * @param condition defines the trigger related conditions
  54729. */
  54730. function CombineAction(triggerOptions, children, condition) {
  54731. var _this = _super.call(this, triggerOptions, condition) || this;
  54732. _this.children = children;
  54733. return _this;
  54734. }
  54735. /** @hidden */
  54736. CombineAction.prototype._prepare = function () {
  54737. for (var index = 0; index < this.children.length; index++) {
  54738. this.children[index]._actionManager = this._actionManager;
  54739. this.children[index]._prepare();
  54740. }
  54741. };
  54742. /**
  54743. * Execute the action and executes all the aggregated actions.
  54744. */
  54745. CombineAction.prototype.execute = function (evt) {
  54746. for (var index = 0; index < this.children.length; index++) {
  54747. this.children[index].execute(evt);
  54748. }
  54749. };
  54750. /**
  54751. * Serializes the actions and its related information.
  54752. * @param parent defines the object to serialize in
  54753. * @returns the serialized object
  54754. */
  54755. CombineAction.prototype.serialize = function (parent) {
  54756. var serializationObject = _super.prototype._serialize.call(this, {
  54757. name: "CombineAction",
  54758. properties: [],
  54759. combine: []
  54760. }, parent);
  54761. for (var i = 0; i < this.children.length; i++) {
  54762. serializationObject.combine.push(this.children[i].serialize(null));
  54763. }
  54764. return serializationObject;
  54765. };
  54766. return CombineAction;
  54767. }(BABYLON.Action));
  54768. BABYLON.CombineAction = CombineAction;
  54769. /**
  54770. * This defines an action responsible to run code (external event) once triggered.
  54771. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54772. */
  54773. var ExecuteCodeAction = /** @class */ (function (_super) {
  54774. __extends(ExecuteCodeAction, _super);
  54775. /**
  54776. * Instantiate the action
  54777. * @param triggerOptions defines the trigger options
  54778. * @param func defines the callback function to run
  54779. * @param condition defines the trigger related conditions
  54780. */
  54781. function ExecuteCodeAction(triggerOptions, func, condition) {
  54782. var _this = _super.call(this, triggerOptions, condition) || this;
  54783. _this.func = func;
  54784. return _this;
  54785. }
  54786. /**
  54787. * Execute the action and run the attached code.
  54788. */
  54789. ExecuteCodeAction.prototype.execute = function (evt) {
  54790. this.func(evt);
  54791. };
  54792. return ExecuteCodeAction;
  54793. }(BABYLON.Action));
  54794. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54795. /**
  54796. * This defines an action responsible to set the parent property of the target once triggered.
  54797. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54798. */
  54799. var SetParentAction = /** @class */ (function (_super) {
  54800. __extends(SetParentAction, _super);
  54801. /**
  54802. * Instantiate the action
  54803. * @param triggerOptions defines the trigger options
  54804. * @param target defines the target containing the parent property
  54805. * @param parent defines from where the animation should start (animation frame)
  54806. * @param condition defines the trigger related conditions
  54807. */
  54808. function SetParentAction(triggerOptions, target, parent, condition) {
  54809. var _this = _super.call(this, triggerOptions, condition) || this;
  54810. _this._target = target;
  54811. _this._parent = parent;
  54812. return _this;
  54813. }
  54814. /** @hidden */
  54815. SetParentAction.prototype._prepare = function () {
  54816. };
  54817. /**
  54818. * Execute the action and set the parent property.
  54819. */
  54820. SetParentAction.prototype.execute = function () {
  54821. if (this._target.parent === this._parent) {
  54822. return;
  54823. }
  54824. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54825. invertParentWorldMatrix.invert();
  54826. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54827. this._target.parent = this._parent;
  54828. };
  54829. /**
  54830. * Serializes the actions and its related information.
  54831. * @param parent defines the object to serialize in
  54832. * @returns the serialized object
  54833. */
  54834. SetParentAction.prototype.serialize = function (parent) {
  54835. return _super.prototype._serialize.call(this, {
  54836. name: "SetParentAction",
  54837. properties: [
  54838. BABYLON.Action._GetTargetProperty(this._target),
  54839. BABYLON.Action._GetTargetProperty(this._parent),
  54840. ]
  54841. }, parent);
  54842. };
  54843. return SetParentAction;
  54844. }(BABYLON.Action));
  54845. BABYLON.SetParentAction = SetParentAction;
  54846. })(BABYLON || (BABYLON = {}));
  54847. //# sourceMappingURL=babylon.directActions.js.map
  54848. var BABYLON;
  54849. (function (BABYLON) {
  54850. var SpriteManager = /** @class */ (function () {
  54851. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54852. if (epsilon === void 0) { epsilon = 0.01; }
  54853. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54854. this.name = name;
  54855. this.sprites = new Array();
  54856. this.renderingGroupId = 0;
  54857. this.layerMask = 0x0FFFFFFF;
  54858. this.fogEnabled = true;
  54859. this.isPickable = false;
  54860. /**
  54861. * An event triggered when the manager is disposed.
  54862. */
  54863. this.onDisposeObservable = new BABYLON.Observable();
  54864. this._vertexBuffers = {};
  54865. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  54866. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  54867. }
  54868. this._capacity = capacity;
  54869. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54870. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54871. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54872. if (cellSize.width && cellSize.height) {
  54873. this.cellWidth = cellSize.width;
  54874. this.cellHeight = cellSize.height;
  54875. }
  54876. else if (cellSize !== undefined) {
  54877. this.cellWidth = cellSize;
  54878. this.cellHeight = cellSize;
  54879. }
  54880. else {
  54881. return;
  54882. }
  54883. this._epsilon = epsilon;
  54884. this._scene = scene;
  54885. this._scene.spriteManagers.push(this);
  54886. var indices = [];
  54887. var index = 0;
  54888. for (var count = 0; count < capacity; count++) {
  54889. indices.push(index);
  54890. indices.push(index + 1);
  54891. indices.push(index + 2);
  54892. indices.push(index);
  54893. indices.push(index + 2);
  54894. indices.push(index + 3);
  54895. index += 4;
  54896. }
  54897. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54898. // VBO
  54899. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54900. this._vertexData = new Float32Array(capacity * 16 * 4);
  54901. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54902. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54903. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54904. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54905. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54906. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54907. this._vertexBuffers["options"] = options;
  54908. this._vertexBuffers["cellInfo"] = cellInfo;
  54909. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54910. // Effects
  54911. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54912. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54913. }
  54914. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54915. set: function (callback) {
  54916. if (this._onDisposeObserver) {
  54917. this.onDisposeObservable.remove(this._onDisposeObserver);
  54918. }
  54919. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54920. },
  54921. enumerable: true,
  54922. configurable: true
  54923. });
  54924. Object.defineProperty(SpriteManager.prototype, "texture", {
  54925. get: function () {
  54926. return this._spriteTexture;
  54927. },
  54928. set: function (value) {
  54929. this._spriteTexture = value;
  54930. },
  54931. enumerable: true,
  54932. configurable: true
  54933. });
  54934. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54935. var arrayOffset = index * 16;
  54936. if (offsetX === 0)
  54937. offsetX = this._epsilon;
  54938. else if (offsetX === 1)
  54939. offsetX = 1 - this._epsilon;
  54940. if (offsetY === 0)
  54941. offsetY = this._epsilon;
  54942. else if (offsetY === 1)
  54943. offsetY = 1 - this._epsilon;
  54944. this._vertexData[arrayOffset] = sprite.position.x;
  54945. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54946. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54947. this._vertexData[arrayOffset + 3] = sprite.angle;
  54948. this._vertexData[arrayOffset + 4] = sprite.width;
  54949. this._vertexData[arrayOffset + 5] = sprite.height;
  54950. this._vertexData[arrayOffset + 6] = offsetX;
  54951. this._vertexData[arrayOffset + 7] = offsetY;
  54952. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54953. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54954. var offset = (sprite.cellIndex / rowSize) >> 0;
  54955. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54956. this._vertexData[arrayOffset + 11] = offset;
  54957. // Color
  54958. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54959. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54960. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54961. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54962. };
  54963. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54964. var count = Math.min(this._capacity, this.sprites.length);
  54965. var min = BABYLON.Vector3.Zero();
  54966. var max = BABYLON.Vector3.Zero();
  54967. var distance = Number.MAX_VALUE;
  54968. var currentSprite = null;
  54969. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54970. var cameraView = camera.getViewMatrix();
  54971. for (var index = 0; index < count; index++) {
  54972. var sprite = this.sprites[index];
  54973. if (!sprite) {
  54974. continue;
  54975. }
  54976. if (predicate) {
  54977. if (!predicate(sprite)) {
  54978. continue;
  54979. }
  54980. }
  54981. else if (!sprite.isPickable) {
  54982. continue;
  54983. }
  54984. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54985. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54986. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54987. if (ray.intersectsBoxMinMax(min, max)) {
  54988. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54989. if (distance > currentDistance) {
  54990. distance = currentDistance;
  54991. currentSprite = sprite;
  54992. if (fastCheck) {
  54993. break;
  54994. }
  54995. }
  54996. }
  54997. }
  54998. if (currentSprite) {
  54999. var result = new BABYLON.PickingInfo();
  55000. result.hit = true;
  55001. result.pickedSprite = currentSprite;
  55002. result.distance = distance;
  55003. return result;
  55004. }
  55005. return null;
  55006. };
  55007. SpriteManager.prototype.render = function () {
  55008. // Check
  55009. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  55010. return;
  55011. var engine = this._scene.getEngine();
  55012. var baseSize = this._spriteTexture.getBaseSize();
  55013. // Sprites
  55014. var deltaTime = engine.getDeltaTime();
  55015. var max = Math.min(this._capacity, this.sprites.length);
  55016. var rowSize = baseSize.width / this.cellWidth;
  55017. var offset = 0;
  55018. for (var index = 0; index < max; index++) {
  55019. var sprite = this.sprites[index];
  55020. if (!sprite || !sprite.isVisible) {
  55021. continue;
  55022. }
  55023. sprite._animate(deltaTime);
  55024. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  55025. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  55026. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  55027. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  55028. }
  55029. this._buffer.update(this._vertexData);
  55030. // Render
  55031. var effect = this._effectBase;
  55032. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55033. effect = this._effectFog;
  55034. }
  55035. engine.enableEffect(effect);
  55036. var viewMatrix = this._scene.getViewMatrix();
  55037. effect.setTexture("diffuseSampler", this._spriteTexture);
  55038. effect.setMatrix("view", viewMatrix);
  55039. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55040. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  55041. // Fog
  55042. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55043. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  55044. effect.setColor3("vFogColor", this._scene.fogColor);
  55045. }
  55046. // VBOs
  55047. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55048. // Draw order
  55049. engine.setDepthFunctionToLessOrEqual();
  55050. effect.setBool("alphaTest", true);
  55051. engine.setColorWrite(false);
  55052. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55053. engine.setColorWrite(true);
  55054. effect.setBool("alphaTest", false);
  55055. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55056. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55057. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55058. };
  55059. SpriteManager.prototype.dispose = function () {
  55060. if (this._buffer) {
  55061. this._buffer.dispose();
  55062. this._buffer = null;
  55063. }
  55064. if (this._indexBuffer) {
  55065. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55066. this._indexBuffer = null;
  55067. }
  55068. if (this._spriteTexture) {
  55069. this._spriteTexture.dispose();
  55070. this._spriteTexture = null;
  55071. }
  55072. // Remove from scene
  55073. var index = this._scene.spriteManagers.indexOf(this);
  55074. this._scene.spriteManagers.splice(index, 1);
  55075. // Callback
  55076. this.onDisposeObservable.notifyObservers(this);
  55077. this.onDisposeObservable.clear();
  55078. };
  55079. return SpriteManager;
  55080. }());
  55081. BABYLON.SpriteManager = SpriteManager;
  55082. })(BABYLON || (BABYLON = {}));
  55083. //# sourceMappingURL=babylon.spriteManager.js.map
  55084. var BABYLON;
  55085. (function (BABYLON) {
  55086. var Sprite = /** @class */ (function () {
  55087. function Sprite(name, manager) {
  55088. this.name = name;
  55089. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55090. this.width = 1.0;
  55091. this.height = 1.0;
  55092. this.angle = 0;
  55093. this.cellIndex = 0;
  55094. this.invertU = 0;
  55095. this.invertV = 0;
  55096. this.animations = new Array();
  55097. this.isPickable = false;
  55098. this._animationStarted = false;
  55099. this._loopAnimation = false;
  55100. this._fromIndex = 0;
  55101. this._toIndex = 0;
  55102. this._delay = 0;
  55103. this._direction = 1;
  55104. this._time = 0;
  55105. /**
  55106. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  55107. */
  55108. this.isVisible = true;
  55109. this._manager = manager;
  55110. this._manager.sprites.push(this);
  55111. this.position = BABYLON.Vector3.Zero();
  55112. }
  55113. Object.defineProperty(Sprite.prototype, "size", {
  55114. get: function () {
  55115. return this.width;
  55116. },
  55117. set: function (value) {
  55118. this.width = value;
  55119. this.height = value;
  55120. },
  55121. enumerable: true,
  55122. configurable: true
  55123. });
  55124. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55125. this._fromIndex = from;
  55126. this._toIndex = to;
  55127. this._loopAnimation = loop;
  55128. this._delay = delay;
  55129. this._animationStarted = true;
  55130. this._direction = from < to ? 1 : -1;
  55131. this.cellIndex = from;
  55132. this._time = 0;
  55133. this._onAnimationEnd = onAnimationEnd;
  55134. };
  55135. Sprite.prototype.stopAnimation = function () {
  55136. this._animationStarted = false;
  55137. };
  55138. /** @hidden */
  55139. Sprite.prototype._animate = function (deltaTime) {
  55140. if (!this._animationStarted)
  55141. return;
  55142. this._time += deltaTime;
  55143. if (this._time > this._delay) {
  55144. this._time = this._time % this._delay;
  55145. this.cellIndex += this._direction;
  55146. if (this.cellIndex > this._toIndex) {
  55147. if (this._loopAnimation) {
  55148. this.cellIndex = this._fromIndex;
  55149. }
  55150. else {
  55151. this.cellIndex = this._toIndex;
  55152. this._animationStarted = false;
  55153. if (this._onAnimationEnd) {
  55154. this._onAnimationEnd();
  55155. }
  55156. if (this.disposeWhenFinishedAnimating) {
  55157. this.dispose();
  55158. }
  55159. }
  55160. }
  55161. }
  55162. };
  55163. Sprite.prototype.dispose = function () {
  55164. for (var i = 0; i < this._manager.sprites.length; i++) {
  55165. if (this._manager.sprites[i] == this) {
  55166. this._manager.sprites.splice(i, 1);
  55167. }
  55168. }
  55169. };
  55170. return Sprite;
  55171. }());
  55172. BABYLON.Sprite = Sprite;
  55173. })(BABYLON || (BABYLON = {}));
  55174. //# sourceMappingURL=babylon.sprite.js.map
  55175. var BABYLON;
  55176. (function (BABYLON) {
  55177. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  55178. if (!BABYLON.PickingInfo) {
  55179. return null;
  55180. }
  55181. var pickingInfo = null;
  55182. if (!camera) {
  55183. if (!this.activeCamera) {
  55184. return null;
  55185. }
  55186. camera = this.activeCamera;
  55187. }
  55188. if (this.spriteManagers.length > 0) {
  55189. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  55190. var spriteManager = this.spriteManagers[spriteIndex];
  55191. if (!spriteManager.isPickable) {
  55192. continue;
  55193. }
  55194. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  55195. if (!result || !result.hit)
  55196. continue;
  55197. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  55198. continue;
  55199. pickingInfo = result;
  55200. if (fastCheck) {
  55201. break;
  55202. }
  55203. }
  55204. }
  55205. return pickingInfo || new BABYLON.PickingInfo();
  55206. };
  55207. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  55208. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  55209. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55210. };
  55211. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  55212. if (!this._tempSpritePickingRay) {
  55213. return null;
  55214. }
  55215. if (!camera) {
  55216. if (!this.activeCamera) {
  55217. return null;
  55218. }
  55219. camera = this.activeCamera;
  55220. }
  55221. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  55222. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55223. };
  55224. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  55225. if (this._pointerOverSprite === sprite) {
  55226. return;
  55227. }
  55228. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55229. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55230. }
  55231. this._pointerOverSprite = sprite;
  55232. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55233. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55234. }
  55235. };
  55236. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  55237. return this._pointerOverSprite;
  55238. };
  55239. /**
  55240. * Defines the sprite scene component responsible to manage sprites
  55241. * in a given scene.
  55242. */
  55243. var SpriteSceneComponent = /** @class */ (function () {
  55244. /**
  55245. * Creates a new instance of the component for the given scene
  55246. * @param scene Defines the scene to register the component in
  55247. */
  55248. function SpriteSceneComponent(scene) {
  55249. /**
  55250. * The component name helpfull to identify the component in the list of scene components.
  55251. */
  55252. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  55253. this.scene = scene;
  55254. this.scene.spriteManagers = new Array();
  55255. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  55256. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  55257. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  55258. this._spritePredicate = function (sprite) {
  55259. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  55260. };
  55261. }
  55262. /**
  55263. * Registers the component in a given scene
  55264. */
  55265. SpriteSceneComponent.prototype.register = function () {
  55266. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  55267. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  55268. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  55269. };
  55270. /**
  55271. * Rebuilds the elements related to this component in case of
  55272. * context lost for instance.
  55273. */
  55274. SpriteSceneComponent.prototype.rebuild = function () {
  55275. /** Nothing to do for sprites */
  55276. };
  55277. /**
  55278. * Disposes the component and the associated ressources.
  55279. */
  55280. SpriteSceneComponent.prototype.dispose = function () {
  55281. this.scene.onBeforeSpritesRenderingObservable.clear();
  55282. this.scene.onAfterSpritesRenderingObservable.clear();
  55283. var spriteManagers = this.scene.spriteManagers;
  55284. while (spriteManagers.length) {
  55285. spriteManagers[0].dispose();
  55286. }
  55287. };
  55288. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  55289. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  55290. if (result) {
  55291. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  55292. }
  55293. return result;
  55294. };
  55295. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  55296. var scene = this.scene;
  55297. if (isMeshPicked) {
  55298. scene.setPointerOverSprite(null);
  55299. }
  55300. else {
  55301. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  55302. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55303. scene.setPointerOverSprite(pickResult.pickedSprite);
  55304. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  55305. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  55306. }
  55307. else {
  55308. canvas.style.cursor = scene.hoverCursor;
  55309. }
  55310. }
  55311. else {
  55312. scene.setPointerOverSprite(null);
  55313. }
  55314. }
  55315. return pickResult;
  55316. };
  55317. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55318. var scene = this.scene;
  55319. scene._pickedDownSprite = null;
  55320. if (scene.spriteManagers.length > 0) {
  55321. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55322. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55323. if (pickResult.pickedSprite.actionManager) {
  55324. scene._pickedDownSprite = pickResult.pickedSprite;
  55325. switch (evt.button) {
  55326. case 0:
  55327. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55328. break;
  55329. case 1:
  55330. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55331. break;
  55332. case 2:
  55333. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55334. break;
  55335. }
  55336. if (pickResult.pickedSprite.actionManager) {
  55337. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55338. }
  55339. }
  55340. }
  55341. }
  55342. return pickResult;
  55343. };
  55344. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55345. var scene = this.scene;
  55346. if (scene.spriteManagers.length > 0) {
  55347. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55348. if (spritePickResult) {
  55349. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  55350. if (spritePickResult.pickedSprite.actionManager) {
  55351. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55352. if (spritePickResult.pickedSprite.actionManager) {
  55353. if (!this.scene._isPointerSwiping()) {
  55354. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55355. }
  55356. }
  55357. }
  55358. }
  55359. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  55360. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  55361. }
  55362. }
  55363. }
  55364. return pickResult;
  55365. };
  55366. return SpriteSceneComponent;
  55367. }());
  55368. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  55369. })(BABYLON || (BABYLON = {}));
  55370. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  55371. var BABYLON;
  55372. (function (BABYLON) {
  55373. /**
  55374. * @hidden
  55375. */
  55376. var IntersectionInfo = /** @class */ (function () {
  55377. function IntersectionInfo(bu, bv, distance) {
  55378. this.bu = bu;
  55379. this.bv = bv;
  55380. this.distance = distance;
  55381. this.faceId = 0;
  55382. this.subMeshId = 0;
  55383. }
  55384. return IntersectionInfo;
  55385. }());
  55386. BABYLON.IntersectionInfo = IntersectionInfo;
  55387. /**
  55388. * Information about the result of picking within a scene
  55389. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  55390. */
  55391. var PickingInfo = /** @class */ (function () {
  55392. function PickingInfo() {
  55393. /**
  55394. * If the pick collided with an object
  55395. */
  55396. this.hit = false;
  55397. /**
  55398. * Distance away where the pick collided
  55399. */
  55400. this.distance = 0;
  55401. /**
  55402. * The location of pick collision
  55403. */
  55404. this.pickedPoint = null;
  55405. /**
  55406. * The mesh corresponding the the pick collision
  55407. */
  55408. this.pickedMesh = null;
  55409. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55410. this.bu = 0;
  55411. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55412. this.bv = 0;
  55413. /** The id of the face on the mesh that was picked */
  55414. this.faceId = -1;
  55415. /** Id of the the submesh that was picked */
  55416. this.subMeshId = 0;
  55417. /** If a sprite was picked, this will be the sprite the pick collided with */
  55418. this.pickedSprite = null;
  55419. /**
  55420. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55421. */
  55422. this.originMesh = null;
  55423. /**
  55424. * The ray that was used to perform the picking.
  55425. */
  55426. this.ray = null;
  55427. }
  55428. /**
  55429. * Gets the normal correspodning to the face the pick collided with
  55430. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55431. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55432. * @returns The normal correspodning to the face the pick collided with
  55433. */
  55434. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55435. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55436. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55437. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55438. return null;
  55439. }
  55440. var indices = this.pickedMesh.getIndices();
  55441. if (!indices) {
  55442. return null;
  55443. }
  55444. var result;
  55445. if (useVerticesNormals) {
  55446. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55447. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55448. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55449. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55450. normal0 = normal0.scale(this.bu);
  55451. normal1 = normal1.scale(this.bv);
  55452. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55453. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55454. }
  55455. else {
  55456. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55457. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55458. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55459. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55460. var p1p2 = vertex1.subtract(vertex2);
  55461. var p3p2 = vertex3.subtract(vertex2);
  55462. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55463. }
  55464. if (useWorldCoordinates) {
  55465. var wm = this.pickedMesh.getWorldMatrix();
  55466. if (this.pickedMesh.nonUniformScaling) {
  55467. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  55468. wm = BABYLON.Tmp.Matrix[0];
  55469. wm.setTranslationFromFloats(0, 0, 0);
  55470. wm.invert();
  55471. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  55472. wm = BABYLON.Tmp.Matrix[1];
  55473. }
  55474. result = BABYLON.Vector3.TransformNormal(result, wm);
  55475. }
  55476. result.normalize();
  55477. return result;
  55478. };
  55479. /**
  55480. * Gets the texture coordinates of where the pick occured
  55481. * @returns the vector containing the coordnates of the texture
  55482. */
  55483. PickingInfo.prototype.getTextureCoordinates = function () {
  55484. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55485. return null;
  55486. }
  55487. var indices = this.pickedMesh.getIndices();
  55488. if (!indices) {
  55489. return null;
  55490. }
  55491. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55492. if (!uvs) {
  55493. return null;
  55494. }
  55495. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55496. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55497. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55498. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55499. uv1 = uv1.scale(this.bu);
  55500. uv2 = uv2.scale(this.bv);
  55501. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55502. };
  55503. return PickingInfo;
  55504. }());
  55505. BABYLON.PickingInfo = PickingInfo;
  55506. })(BABYLON || (BABYLON = {}));
  55507. //# sourceMappingURL=babylon.pickingInfo.js.map
  55508. var BABYLON;
  55509. (function (BABYLON) {
  55510. var Ray = /** @class */ (function () {
  55511. function Ray(origin, direction, length) {
  55512. if (length === void 0) { length = Number.MAX_VALUE; }
  55513. this.origin = origin;
  55514. this.direction = direction;
  55515. this.length = length;
  55516. }
  55517. // Methods
  55518. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55519. var d = 0.0;
  55520. var maxValue = Number.MAX_VALUE;
  55521. var inv;
  55522. var min;
  55523. var max;
  55524. var temp;
  55525. if (Math.abs(this.direction.x) < 0.0000001) {
  55526. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55527. return false;
  55528. }
  55529. }
  55530. else {
  55531. inv = 1.0 / this.direction.x;
  55532. min = (minimum.x - this.origin.x) * inv;
  55533. max = (maximum.x - this.origin.x) * inv;
  55534. if (max === -Infinity) {
  55535. max = Infinity;
  55536. }
  55537. if (min > max) {
  55538. temp = min;
  55539. min = max;
  55540. max = temp;
  55541. }
  55542. d = Math.max(min, d);
  55543. maxValue = Math.min(max, maxValue);
  55544. if (d > maxValue) {
  55545. return false;
  55546. }
  55547. }
  55548. if (Math.abs(this.direction.y) < 0.0000001) {
  55549. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55550. return false;
  55551. }
  55552. }
  55553. else {
  55554. inv = 1.0 / this.direction.y;
  55555. min = (minimum.y - this.origin.y) * inv;
  55556. max = (maximum.y - this.origin.y) * inv;
  55557. if (max === -Infinity) {
  55558. max = Infinity;
  55559. }
  55560. if (min > max) {
  55561. temp = min;
  55562. min = max;
  55563. max = temp;
  55564. }
  55565. d = Math.max(min, d);
  55566. maxValue = Math.min(max, maxValue);
  55567. if (d > maxValue) {
  55568. return false;
  55569. }
  55570. }
  55571. if (Math.abs(this.direction.z) < 0.0000001) {
  55572. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55573. return false;
  55574. }
  55575. }
  55576. else {
  55577. inv = 1.0 / this.direction.z;
  55578. min = (minimum.z - this.origin.z) * inv;
  55579. max = (maximum.z - this.origin.z) * inv;
  55580. if (max === -Infinity) {
  55581. max = Infinity;
  55582. }
  55583. if (min > max) {
  55584. temp = min;
  55585. min = max;
  55586. max = temp;
  55587. }
  55588. d = Math.max(min, d);
  55589. maxValue = Math.min(max, maxValue);
  55590. if (d > maxValue) {
  55591. return false;
  55592. }
  55593. }
  55594. return true;
  55595. };
  55596. Ray.prototype.intersectsBox = function (box) {
  55597. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55598. };
  55599. Ray.prototype.intersectsSphere = function (sphere) {
  55600. var x = sphere.center.x - this.origin.x;
  55601. var y = sphere.center.y - this.origin.y;
  55602. var z = sphere.center.z - this.origin.z;
  55603. var pyth = (x * x) + (y * y) + (z * z);
  55604. var rr = sphere.radius * sphere.radius;
  55605. if (pyth <= rr) {
  55606. return true;
  55607. }
  55608. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55609. if (dot < 0.0) {
  55610. return false;
  55611. }
  55612. var temp = pyth - (dot * dot);
  55613. return temp <= rr;
  55614. };
  55615. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55616. if (!this._edge1) {
  55617. this._edge1 = BABYLON.Vector3.Zero();
  55618. this._edge2 = BABYLON.Vector3.Zero();
  55619. this._pvec = BABYLON.Vector3.Zero();
  55620. this._tvec = BABYLON.Vector3.Zero();
  55621. this._qvec = BABYLON.Vector3.Zero();
  55622. }
  55623. vertex1.subtractToRef(vertex0, this._edge1);
  55624. vertex2.subtractToRef(vertex0, this._edge2);
  55625. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55626. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55627. if (det === 0) {
  55628. return null;
  55629. }
  55630. var invdet = 1 / det;
  55631. this.origin.subtractToRef(vertex0, this._tvec);
  55632. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55633. if (bu < 0 || bu > 1.0) {
  55634. return null;
  55635. }
  55636. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55637. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55638. if (bv < 0 || bu + bv > 1.0) {
  55639. return null;
  55640. }
  55641. //check if the distance is longer than the predefined length.
  55642. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55643. if (distance > this.length) {
  55644. return null;
  55645. }
  55646. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55647. };
  55648. Ray.prototype.intersectsPlane = function (plane) {
  55649. var distance;
  55650. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55651. if (Math.abs(result1) < 9.99999997475243E-07) {
  55652. return null;
  55653. }
  55654. else {
  55655. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55656. distance = (-plane.d - result2) / result1;
  55657. if (distance < 0.0) {
  55658. if (distance < -9.99999997475243E-07) {
  55659. return null;
  55660. }
  55661. else {
  55662. return 0;
  55663. }
  55664. }
  55665. return distance;
  55666. }
  55667. };
  55668. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55669. var tm = BABYLON.Tmp.Matrix[0];
  55670. mesh.getWorldMatrix().invertToRef(tm);
  55671. if (this._tmpRay) {
  55672. Ray.TransformToRef(this, tm, this._tmpRay);
  55673. }
  55674. else {
  55675. this._tmpRay = Ray.Transform(this, tm);
  55676. }
  55677. return mesh.intersects(this._tmpRay, fastCheck);
  55678. };
  55679. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55680. if (results) {
  55681. results.length = 0;
  55682. }
  55683. else {
  55684. results = [];
  55685. }
  55686. for (var i = 0; i < meshes.length; i++) {
  55687. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55688. if (pickInfo.hit) {
  55689. results.push(pickInfo);
  55690. }
  55691. }
  55692. results.sort(this._comparePickingInfo);
  55693. return results;
  55694. };
  55695. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55696. if (pickingInfoA.distance < pickingInfoB.distance) {
  55697. return -1;
  55698. }
  55699. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55700. return 1;
  55701. }
  55702. else {
  55703. return 0;
  55704. }
  55705. };
  55706. /**
  55707. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55708. * @param sega the first point of the segment to test the intersection against
  55709. * @param segb the second point of the segment to test the intersection against
  55710. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55711. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55712. */
  55713. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55714. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55715. var u = segb.subtract(sega);
  55716. var v = rsegb.subtract(this.origin);
  55717. var w = sega.subtract(this.origin);
  55718. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55719. var b = BABYLON.Vector3.Dot(u, v);
  55720. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55721. var d = BABYLON.Vector3.Dot(u, w);
  55722. var e = BABYLON.Vector3.Dot(v, w);
  55723. var D = a * c - b * b; // always >= 0
  55724. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55725. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55726. // compute the line parameters of the two closest points
  55727. if (D < Ray.smallnum) { // the lines are almost parallel
  55728. sN = 0.0; // force using point P0 on segment S1
  55729. sD = 1.0; // to prevent possible division by 0.0 later
  55730. tN = e;
  55731. tD = c;
  55732. }
  55733. else { // get the closest points on the infinite lines
  55734. sN = (b * e - c * d);
  55735. tN = (a * e - b * d);
  55736. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55737. sN = 0.0;
  55738. tN = e;
  55739. tD = c;
  55740. }
  55741. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55742. sN = sD;
  55743. tN = e + b;
  55744. tD = c;
  55745. }
  55746. }
  55747. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55748. tN = 0.0;
  55749. // recompute sc for this edge
  55750. if (-d < 0.0) {
  55751. sN = 0.0;
  55752. }
  55753. else if (-d > a)
  55754. sN = sD;
  55755. else {
  55756. sN = -d;
  55757. sD = a;
  55758. }
  55759. }
  55760. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55761. tN = tD;
  55762. // recompute sc for this edge
  55763. if ((-d + b) < 0.0) {
  55764. sN = 0;
  55765. }
  55766. else if ((-d + b) > a) {
  55767. sN = sD;
  55768. }
  55769. else {
  55770. sN = (-d + b);
  55771. sD = a;
  55772. }
  55773. }
  55774. // finally do the division to get sc and tc
  55775. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55776. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55777. // get the difference of the two closest points
  55778. var qtc = v.multiplyByFloats(tc, tc, tc);
  55779. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55780. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55781. if (isIntersected) {
  55782. return qtc.length();
  55783. }
  55784. return -1;
  55785. };
  55786. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55787. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55788. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55789. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55790. this.direction.normalize();
  55791. return this;
  55792. };
  55793. // Statics
  55794. Ray.Zero = function () {
  55795. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55796. };
  55797. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55798. var result = Ray.Zero();
  55799. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55800. };
  55801. /**
  55802. * 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
  55803. * transformed to the given world matrix.
  55804. * @param origin The origin point
  55805. * @param end The end point
  55806. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55807. */
  55808. Ray.CreateNewFromTo = function (origin, end, world) {
  55809. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55810. var direction = end.subtract(origin);
  55811. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55812. direction.normalize();
  55813. return Ray.Transform(new Ray(origin, direction, length), world);
  55814. };
  55815. Ray.Transform = function (ray, matrix) {
  55816. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55817. Ray.TransformToRef(ray, matrix, result);
  55818. return result;
  55819. };
  55820. Ray.TransformToRef = function (ray, matrix, result) {
  55821. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55822. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55823. result.length = ray.length;
  55824. var dir = result.direction;
  55825. var len = dir.length();
  55826. if (!(len === 0 || len === 1)) {
  55827. var num = 1.0 / len;
  55828. dir.x *= num;
  55829. dir.y *= num;
  55830. dir.z *= num;
  55831. result.length *= len;
  55832. }
  55833. };
  55834. Ray.smallnum = 0.00000001;
  55835. Ray.rayl = 10e8;
  55836. return Ray;
  55837. }());
  55838. BABYLON.Ray = Ray;
  55839. })(BABYLON || (BABYLON = {}));
  55840. //# sourceMappingURL=babylon.ray.js.map
  55841. var BABYLON;
  55842. (function (BABYLON) {
  55843. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55844. if (boxMin.x > sphereCenter.x + sphereRadius)
  55845. return false;
  55846. if (sphereCenter.x - sphereRadius > boxMax.x)
  55847. return false;
  55848. if (boxMin.y > sphereCenter.y + sphereRadius)
  55849. return false;
  55850. if (sphereCenter.y - sphereRadius > boxMax.y)
  55851. return false;
  55852. if (boxMin.z > sphereCenter.z + sphereRadius)
  55853. return false;
  55854. if (sphereCenter.z - sphereRadius > boxMax.z)
  55855. return false;
  55856. return true;
  55857. };
  55858. var getLowestRoot = (function () {
  55859. var result = { root: 0, found: false };
  55860. return function (a, b, c, maxR) {
  55861. result.root = 0;
  55862. result.found = false;
  55863. var determinant = b * b - 4.0 * a * c;
  55864. if (determinant < 0)
  55865. return result;
  55866. var sqrtD = Math.sqrt(determinant);
  55867. var r1 = (-b - sqrtD) / (2.0 * a);
  55868. var r2 = (-b + sqrtD) / (2.0 * a);
  55869. if (r1 > r2) {
  55870. var temp = r2;
  55871. r2 = r1;
  55872. r1 = temp;
  55873. }
  55874. if (r1 > 0 && r1 < maxR) {
  55875. result.root = r1;
  55876. result.found = true;
  55877. return result;
  55878. }
  55879. if (r2 > 0 && r2 < maxR) {
  55880. result.root = r2;
  55881. result.found = true;
  55882. return result;
  55883. }
  55884. return result;
  55885. };
  55886. })();
  55887. /** @hidden */
  55888. var Collider = /** @class */ (function () {
  55889. function Collider() {
  55890. this._collisionPoint = BABYLON.Vector3.Zero();
  55891. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55892. this._tempVector = BABYLON.Vector3.Zero();
  55893. this._tempVector2 = BABYLON.Vector3.Zero();
  55894. this._tempVector3 = BABYLON.Vector3.Zero();
  55895. this._tempVector4 = BABYLON.Vector3.Zero();
  55896. this._edge = BABYLON.Vector3.Zero();
  55897. this._baseToVertex = BABYLON.Vector3.Zero();
  55898. this._destinationPoint = BABYLON.Vector3.Zero();
  55899. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55900. this._displacementVector = BABYLON.Vector3.Zero();
  55901. /** @hidden */
  55902. this._radius = BABYLON.Vector3.One();
  55903. /** @hidden */
  55904. this._retry = 0;
  55905. /** @hidden */
  55906. this._basePointWorld = BABYLON.Vector3.Zero();
  55907. this._velocityWorld = BABYLON.Vector3.Zero();
  55908. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55909. this._collisionMask = -1;
  55910. }
  55911. Object.defineProperty(Collider.prototype, "collisionMask", {
  55912. get: function () {
  55913. return this._collisionMask;
  55914. },
  55915. set: function (mask) {
  55916. this._collisionMask = !isNaN(mask) ? mask : -1;
  55917. },
  55918. enumerable: true,
  55919. configurable: true
  55920. });
  55921. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55922. /**
  55923. * Gets the plane normal used to compute the sliding response (in local space)
  55924. */
  55925. get: function () {
  55926. return this._slidePlaneNormal;
  55927. },
  55928. enumerable: true,
  55929. configurable: true
  55930. });
  55931. // Methods
  55932. /** @hidden */
  55933. Collider.prototype._initialize = function (source, dir, e) {
  55934. this._velocity = dir;
  55935. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55936. this._basePoint = source;
  55937. source.multiplyToRef(this._radius, this._basePointWorld);
  55938. dir.multiplyToRef(this._radius, this._velocityWorld);
  55939. this._velocityWorldLength = this._velocityWorld.length();
  55940. this._epsilon = e;
  55941. this.collisionFound = false;
  55942. };
  55943. /** @hidden */
  55944. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55945. pa.subtractToRef(point, this._tempVector);
  55946. pb.subtractToRef(point, this._tempVector2);
  55947. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55948. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55949. if (d < 0)
  55950. return false;
  55951. pc.subtractToRef(point, this._tempVector3);
  55952. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55953. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55954. if (d < 0)
  55955. return false;
  55956. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55957. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55958. return d >= 0;
  55959. };
  55960. /** @hidden */
  55961. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55962. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55963. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55964. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55965. return false;
  55966. }
  55967. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55968. return false;
  55969. return true;
  55970. };
  55971. /** @hidden */
  55972. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55973. var t0;
  55974. var embeddedInPlane = false;
  55975. //defensive programming, actually not needed.
  55976. if (!trianglePlaneArray) {
  55977. trianglePlaneArray = [];
  55978. }
  55979. if (!trianglePlaneArray[faceIndex]) {
  55980. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55981. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55982. }
  55983. var trianglePlane = trianglePlaneArray[faceIndex];
  55984. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55985. return;
  55986. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55987. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55988. if (normalDotVelocity == 0) {
  55989. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55990. return;
  55991. embeddedInPlane = true;
  55992. t0 = 0;
  55993. }
  55994. else {
  55995. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55996. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55997. if (t0 > t1) {
  55998. var temp = t1;
  55999. t1 = t0;
  56000. t0 = temp;
  56001. }
  56002. if (t0 > 1.0 || t1 < 0.0)
  56003. return;
  56004. if (t0 < 0)
  56005. t0 = 0;
  56006. if (t0 > 1.0)
  56007. t0 = 1.0;
  56008. }
  56009. this._collisionPoint.copyFromFloats(0, 0, 0);
  56010. var found = false;
  56011. var t = 1.0;
  56012. if (!embeddedInPlane) {
  56013. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  56014. this._velocity.scaleToRef(t0, this._tempVector);
  56015. this._planeIntersectionPoint.addInPlace(this._tempVector);
  56016. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  56017. found = true;
  56018. t = t0;
  56019. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  56020. }
  56021. }
  56022. if (!found) {
  56023. var velocitySquaredLength = this._velocity.lengthSquared();
  56024. var a = velocitySquaredLength;
  56025. this._basePoint.subtractToRef(p1, this._tempVector);
  56026. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56027. var c = this._tempVector.lengthSquared() - 1.0;
  56028. var lowestRoot = getLowestRoot(a, b, c, t);
  56029. if (lowestRoot.found) {
  56030. t = lowestRoot.root;
  56031. found = true;
  56032. this._collisionPoint.copyFrom(p1);
  56033. }
  56034. this._basePoint.subtractToRef(p2, this._tempVector);
  56035. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56036. c = this._tempVector.lengthSquared() - 1.0;
  56037. lowestRoot = getLowestRoot(a, b, c, t);
  56038. if (lowestRoot.found) {
  56039. t = lowestRoot.root;
  56040. found = true;
  56041. this._collisionPoint.copyFrom(p2);
  56042. }
  56043. this._basePoint.subtractToRef(p3, this._tempVector);
  56044. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56045. c = this._tempVector.lengthSquared() - 1.0;
  56046. lowestRoot = getLowestRoot(a, b, c, t);
  56047. if (lowestRoot.found) {
  56048. t = lowestRoot.root;
  56049. found = true;
  56050. this._collisionPoint.copyFrom(p3);
  56051. }
  56052. p2.subtractToRef(p1, this._edge);
  56053. p1.subtractToRef(this._basePoint, this._baseToVertex);
  56054. var edgeSquaredLength = this._edge.lengthSquared();
  56055. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56056. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56057. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56058. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56059. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56060. lowestRoot = getLowestRoot(a, b, c, t);
  56061. if (lowestRoot.found) {
  56062. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56063. if (f >= 0.0 && f <= 1.0) {
  56064. t = lowestRoot.root;
  56065. found = true;
  56066. this._edge.scaleInPlace(f);
  56067. p1.addToRef(this._edge, this._collisionPoint);
  56068. }
  56069. }
  56070. p3.subtractToRef(p2, this._edge);
  56071. p2.subtractToRef(this._basePoint, this._baseToVertex);
  56072. edgeSquaredLength = this._edge.lengthSquared();
  56073. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56074. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56075. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56076. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56077. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56078. lowestRoot = getLowestRoot(a, b, c, t);
  56079. if (lowestRoot.found) {
  56080. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56081. if (f >= 0.0 && f <= 1.0) {
  56082. t = lowestRoot.root;
  56083. found = true;
  56084. this._edge.scaleInPlace(f);
  56085. p2.addToRef(this._edge, this._collisionPoint);
  56086. }
  56087. }
  56088. p1.subtractToRef(p3, this._edge);
  56089. p3.subtractToRef(this._basePoint, this._baseToVertex);
  56090. edgeSquaredLength = this._edge.lengthSquared();
  56091. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56092. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56093. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56094. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56095. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56096. lowestRoot = getLowestRoot(a, b, c, t);
  56097. if (lowestRoot.found) {
  56098. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56099. if (f >= 0.0 && f <= 1.0) {
  56100. t = lowestRoot.root;
  56101. found = true;
  56102. this._edge.scaleInPlace(f);
  56103. p3.addToRef(this._edge, this._collisionPoint);
  56104. }
  56105. }
  56106. }
  56107. if (found) {
  56108. var distToCollision = t * this._velocity.length();
  56109. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  56110. if (!this.intersectionPoint) {
  56111. this.intersectionPoint = this._collisionPoint.clone();
  56112. }
  56113. else {
  56114. this.intersectionPoint.copyFrom(this._collisionPoint);
  56115. }
  56116. this._nearestDistance = distToCollision;
  56117. this.collisionFound = true;
  56118. }
  56119. }
  56120. };
  56121. /** @hidden */
  56122. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  56123. for (var i = indexStart; i < indexEnd; i += 3) {
  56124. var p1 = pts[indices[i] - decal];
  56125. var p2 = pts[indices[i + 1] - decal];
  56126. var p3 = pts[indices[i + 2] - decal];
  56127. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  56128. }
  56129. };
  56130. /** @hidden */
  56131. Collider.prototype._getResponse = function (pos, vel) {
  56132. pos.addToRef(vel, this._destinationPoint);
  56133. vel.scaleInPlace((this._nearestDistance / vel.length()));
  56134. this._basePoint.addToRef(vel, pos);
  56135. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  56136. this._slidePlaneNormal.normalize();
  56137. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  56138. pos.addInPlace(this._displacementVector);
  56139. this.intersectionPoint.addInPlace(this._displacementVector);
  56140. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  56141. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  56142. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  56143. };
  56144. return Collider;
  56145. }());
  56146. BABYLON.Collider = Collider;
  56147. })(BABYLON || (BABYLON = {}));
  56148. //# sourceMappingURL=babylon.collider.js.map
  56149. var BABYLON;
  56150. (function (BABYLON) {
  56151. //WebWorker code will be inserted to this variable.
  56152. /** @hidden */
  56153. BABYLON.CollisionWorker = "";
  56154. /** Defines supported task for worker process */
  56155. var WorkerTaskType;
  56156. (function (WorkerTaskType) {
  56157. /** Initialization */
  56158. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  56159. /** Update of geometry */
  56160. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  56161. /** Evaluate collision */
  56162. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  56163. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  56164. /** Defines kind of replies returned by worker */
  56165. var WorkerReplyType;
  56166. (function (WorkerReplyType) {
  56167. /** Success */
  56168. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  56169. /** Unkown error */
  56170. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  56171. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  56172. /** @hidden */
  56173. var CollisionCoordinatorWorker = /** @class */ (function () {
  56174. function CollisionCoordinatorWorker() {
  56175. var _this = this;
  56176. this._scaledPosition = BABYLON.Vector3.Zero();
  56177. this._scaledVelocity = BABYLON.Vector3.Zero();
  56178. this.onMeshUpdated = function (transformNode) {
  56179. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  56180. };
  56181. this.onGeometryUpdated = function (geometry) {
  56182. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  56183. };
  56184. this._afterRender = function () {
  56185. if (!_this._init)
  56186. return;
  56187. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  56188. return;
  56189. }
  56190. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  56191. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  56192. if (_this._runningUpdated > 4) {
  56193. return;
  56194. }
  56195. ++_this._runningUpdated;
  56196. var payload = {
  56197. updatedMeshes: _this._addUpdateMeshesList,
  56198. updatedGeometries: _this._addUpdateGeometriesList,
  56199. removedGeometries: _this._toRemoveGeometryArray,
  56200. removedMeshes: _this._toRemoveMeshesArray
  56201. };
  56202. var message = {
  56203. payload: payload,
  56204. taskType: WorkerTaskType.UPDATE
  56205. };
  56206. var serializable = [];
  56207. for (var id in payload.updatedGeometries) {
  56208. if (payload.updatedGeometries.hasOwnProperty(id)) {
  56209. //prepare transferables
  56210. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  56211. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  56212. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  56213. }
  56214. }
  56215. _this._worker.postMessage(message, serializable);
  56216. _this._addUpdateMeshesList = {};
  56217. _this._addUpdateGeometriesList = {};
  56218. _this._toRemoveGeometryArray = [];
  56219. _this._toRemoveMeshesArray = [];
  56220. };
  56221. this._onMessageFromWorker = function (e) {
  56222. var returnData = e.data;
  56223. if (returnData.error != WorkerReplyType.SUCCESS) {
  56224. //TODO what errors can be returned from the worker?
  56225. BABYLON.Tools.Warn("error returned from worker!");
  56226. return;
  56227. }
  56228. switch (returnData.taskType) {
  56229. case WorkerTaskType.INIT:
  56230. _this._init = true;
  56231. //Update the worked with ALL of the scene's current state
  56232. _this._scene.meshes.forEach(function (mesh) {
  56233. _this.onMeshAdded(mesh);
  56234. });
  56235. _this._scene.getGeometries().forEach(function (geometry) {
  56236. _this.onGeometryAdded(geometry);
  56237. });
  56238. break;
  56239. case WorkerTaskType.UPDATE:
  56240. _this._runningUpdated--;
  56241. break;
  56242. case WorkerTaskType.COLLIDE:
  56243. var returnPayload = returnData.payload;
  56244. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  56245. return;
  56246. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  56247. if (callback) {
  56248. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  56249. if (mesh) {
  56250. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  56251. }
  56252. }
  56253. //cleanup
  56254. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  56255. break;
  56256. }
  56257. };
  56258. this._collisionsCallbackArray = [];
  56259. this._init = false;
  56260. this._runningUpdated = 0;
  56261. this._addUpdateMeshesList = {};
  56262. this._addUpdateGeometriesList = {};
  56263. this._toRemoveGeometryArray = [];
  56264. this._toRemoveMeshesArray = [];
  56265. }
  56266. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56267. if (!this._init)
  56268. return;
  56269. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  56270. return;
  56271. position.divideToRef(collider._radius, this._scaledPosition);
  56272. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56273. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  56274. var payload = {
  56275. collider: {
  56276. position: this._scaledPosition.asArray(),
  56277. velocity: this._scaledVelocity.asArray(),
  56278. radius: collider._radius.asArray()
  56279. },
  56280. collisionId: collisionIndex,
  56281. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  56282. maximumRetry: maximumRetry
  56283. };
  56284. var message = {
  56285. payload: payload,
  56286. taskType: WorkerTaskType.COLLIDE
  56287. };
  56288. this._worker.postMessage(message);
  56289. };
  56290. CollisionCoordinatorWorker.prototype.init = function (scene) {
  56291. this._scene = scene;
  56292. this._scene.registerAfterRender(this._afterRender);
  56293. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  56294. this._worker = new Worker(workerUrl);
  56295. this._worker.onmessage = this._onMessageFromWorker;
  56296. var message = {
  56297. payload: {},
  56298. taskType: WorkerTaskType.INIT
  56299. };
  56300. this._worker.postMessage(message);
  56301. };
  56302. CollisionCoordinatorWorker.prototype.destroy = function () {
  56303. this._scene.unregisterAfterRender(this._afterRender);
  56304. this._worker.terminate();
  56305. };
  56306. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  56307. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  56308. this.onMeshUpdated(mesh);
  56309. };
  56310. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  56311. this._toRemoveMeshesArray.push(mesh.uniqueId);
  56312. };
  56313. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  56314. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  56315. geometry.onGeometryUpdated = this.onGeometryUpdated;
  56316. this.onGeometryUpdated(geometry);
  56317. };
  56318. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  56319. this._toRemoveGeometryArray.push(geometry.id);
  56320. };
  56321. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  56322. var submeshes = [];
  56323. if (mesh.subMeshes) {
  56324. submeshes = mesh.subMeshes.map(function (sm, idx) {
  56325. var boundingInfo = sm.getBoundingInfo();
  56326. return {
  56327. position: idx,
  56328. verticesStart: sm.verticesStart,
  56329. verticesCount: sm.verticesCount,
  56330. indexStart: sm.indexStart,
  56331. indexCount: sm.indexCount,
  56332. hasMaterial: !!sm.getMaterial(),
  56333. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56334. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56335. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56336. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  56337. };
  56338. });
  56339. }
  56340. var geometryId = null;
  56341. if (mesh instanceof BABYLON.Mesh) {
  56342. var geometry = mesh.geometry;
  56343. geometryId = geometry ? geometry.id : null;
  56344. }
  56345. else if (mesh instanceof BABYLON.InstancedMesh) {
  56346. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56347. geometryId = geometry ? geometry.id : null;
  56348. }
  56349. var boundingInfo = mesh.getBoundingInfo();
  56350. return {
  56351. uniqueId: mesh.uniqueId,
  56352. id: mesh.id,
  56353. name: mesh.name,
  56354. geometryId: geometryId,
  56355. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56356. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56357. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56358. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56359. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56360. subMeshes: submeshes,
  56361. checkCollisions: mesh.checkCollisions
  56362. };
  56363. };
  56364. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56365. return {
  56366. id: geometry.id,
  56367. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56368. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56369. indices: new Uint32Array(geometry.getIndices() || []),
  56370. };
  56371. };
  56372. return CollisionCoordinatorWorker;
  56373. }());
  56374. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56375. /** @hidden */
  56376. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56377. function CollisionCoordinatorLegacy() {
  56378. this._scaledPosition = BABYLON.Vector3.Zero();
  56379. this._scaledVelocity = BABYLON.Vector3.Zero();
  56380. this._finalPosition = BABYLON.Vector3.Zero();
  56381. }
  56382. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56383. position.divideToRef(collider._radius, this._scaledPosition);
  56384. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56385. collider.collidedMesh = null;
  56386. collider._retry = 0;
  56387. collider._initialVelocity = this._scaledVelocity;
  56388. collider._initialPosition = this._scaledPosition;
  56389. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56390. this._finalPosition.multiplyInPlace(collider._radius);
  56391. //run the callback
  56392. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56393. };
  56394. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56395. this._scene = scene;
  56396. };
  56397. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56398. //Legacy need no destruction method.
  56399. };
  56400. //No update in legacy mode
  56401. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56402. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56403. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56404. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56405. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56406. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56407. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56408. if (excludedMesh === void 0) { excludedMesh = null; }
  56409. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56410. if (collider._retry >= maximumRetry) {
  56411. finalPosition.copyFrom(position);
  56412. return;
  56413. }
  56414. // Check if this is a mesh else camera or -1
  56415. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56416. collider._initialize(position, velocity, closeDistance);
  56417. // Check all meshes
  56418. for (var index = 0; index < this._scene.meshes.length; index++) {
  56419. var mesh = this._scene.meshes[index];
  56420. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56421. mesh._checkCollision(collider);
  56422. }
  56423. }
  56424. if (!collider.collisionFound) {
  56425. position.addToRef(velocity, finalPosition);
  56426. return;
  56427. }
  56428. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56429. collider._getResponse(position, velocity);
  56430. }
  56431. if (velocity.length() <= closeDistance) {
  56432. finalPosition.copyFrom(position);
  56433. return;
  56434. }
  56435. collider._retry++;
  56436. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56437. };
  56438. return CollisionCoordinatorLegacy;
  56439. }());
  56440. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56441. })(BABYLON || (BABYLON = {}));
  56442. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56443. var BABYLON;
  56444. (function (BABYLON) {
  56445. /**
  56446. * A particle represents one of the element emitted by a particle system.
  56447. * This is mainly define by its coordinates, direction, velocity and age.
  56448. */
  56449. var Particle = /** @class */ (function () {
  56450. /**
  56451. * Creates a new instance Particle
  56452. * @param particleSystem the particle system the particle belongs to
  56453. */
  56454. function Particle(
  56455. /**
  56456. * The particle system the particle belongs to.
  56457. */
  56458. particleSystem) {
  56459. this.particleSystem = particleSystem;
  56460. /**
  56461. * The world position of the particle in the scene.
  56462. */
  56463. this.position = BABYLON.Vector3.Zero();
  56464. /**
  56465. * The world direction of the particle in the scene.
  56466. */
  56467. this.direction = BABYLON.Vector3.Zero();
  56468. /**
  56469. * The color of the particle.
  56470. */
  56471. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56472. /**
  56473. * The color change of the particle per step.
  56474. */
  56475. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56476. /**
  56477. * Defines how long will the life of the particle be.
  56478. */
  56479. this.lifeTime = 1.0;
  56480. /**
  56481. * The current age of the particle.
  56482. */
  56483. this.age = 0;
  56484. /**
  56485. * The current size of the particle.
  56486. */
  56487. this.size = 0;
  56488. /**
  56489. * The current scale of the particle.
  56490. */
  56491. this.scale = new BABYLON.Vector2(1, 1);
  56492. /**
  56493. * The current angle of the particle.
  56494. */
  56495. this.angle = 0;
  56496. /**
  56497. * Defines how fast is the angle changing.
  56498. */
  56499. this.angularSpeed = 0;
  56500. /**
  56501. * Defines the cell index used by the particle to be rendered from a sprite.
  56502. */
  56503. this.cellIndex = 0;
  56504. /** @hidden */
  56505. this._attachedSubEmitters = null;
  56506. /** @hidden */
  56507. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  56508. /** @hidden */
  56509. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  56510. /** @hidden */
  56511. this._currentSize1 = 0;
  56512. /** @hidden */
  56513. this._currentSize2 = 0;
  56514. /** @hidden */
  56515. this._currentAngularSpeed1 = 0;
  56516. /** @hidden */
  56517. this._currentAngularSpeed2 = 0;
  56518. /** @hidden */
  56519. this._currentVelocity1 = 0;
  56520. /** @hidden */
  56521. this._currentVelocity2 = 0;
  56522. /** @hidden */
  56523. this._currentLimitVelocity1 = 0;
  56524. /** @hidden */
  56525. this._currentLimitVelocity2 = 0;
  56526. /** @hidden */
  56527. this._currentDrag1 = 0;
  56528. /** @hidden */
  56529. this._currentDrag2 = 0;
  56530. this.id = Particle._Count++;
  56531. if (!this.particleSystem.isAnimationSheetEnabled) {
  56532. return;
  56533. }
  56534. this.updateCellInfoFromSystem();
  56535. }
  56536. Particle.prototype.updateCellInfoFromSystem = function () {
  56537. this.cellIndex = this.particleSystem.startSpriteCellID;
  56538. };
  56539. /**
  56540. * Defines how the sprite cell index is updated for the particle
  56541. */
  56542. Particle.prototype.updateCellIndex = function () {
  56543. var offsetAge = this.age;
  56544. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  56545. if (this.particleSystem.spriteRandomStartCell) {
  56546. if (this._randomCellOffset === undefined) {
  56547. this._randomCellOffset = Math.random() * this.lifeTime;
  56548. }
  56549. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  56550. changeSpeed = 1;
  56551. offsetAge = this._randomCellOffset;
  56552. }
  56553. else {
  56554. offsetAge += this._randomCellOffset;
  56555. }
  56556. }
  56557. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  56558. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  56559. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  56560. };
  56561. /** @hidden */
  56562. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  56563. if (subEmitter.particleSystem.emitter.position) {
  56564. var emitterMesh = subEmitter.particleSystem.emitter;
  56565. emitterMesh.position.copyFrom(this.position);
  56566. if (subEmitter.inheritDirection) {
  56567. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  56568. // Look at using Y as forward
  56569. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56570. }
  56571. }
  56572. else {
  56573. var emitterPosition = subEmitter.particleSystem.emitter;
  56574. emitterPosition.copyFrom(this.position);
  56575. }
  56576. // Set inheritedVelocityOffset to be used when new particles are created
  56577. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56578. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56579. };
  56580. /** @hidden */
  56581. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  56582. var _this = this;
  56583. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  56584. this._attachedSubEmitters.forEach(function (subEmitter) {
  56585. _this._inheritParticleInfoToSubEmitter(subEmitter);
  56586. });
  56587. }
  56588. };
  56589. /** @hidden */
  56590. Particle.prototype._reset = function () {
  56591. this.age = 0;
  56592. this._currentColorGradient = null;
  56593. this._currentSizeGradient = null;
  56594. this._currentAngularSpeedGradient = null;
  56595. this._currentVelocityGradient = null;
  56596. this._currentLimitVelocityGradient = null;
  56597. this._currentDragGradient = null;
  56598. this.cellIndex = this.particleSystem.startSpriteCellID;
  56599. this._randomCellOffset = undefined;
  56600. };
  56601. /**
  56602. * Copy the properties of particle to another one.
  56603. * @param other the particle to copy the information to.
  56604. */
  56605. Particle.prototype.copyTo = function (other) {
  56606. other.position.copyFrom(this.position);
  56607. if (this._initialDirection) {
  56608. if (other._initialDirection) {
  56609. other._initialDirection.copyFrom(this._initialDirection);
  56610. }
  56611. else {
  56612. other._initialDirection = this._initialDirection.clone();
  56613. }
  56614. }
  56615. else {
  56616. other._initialDirection = null;
  56617. }
  56618. other.direction.copyFrom(this.direction);
  56619. other.color.copyFrom(this.color);
  56620. other.colorStep.copyFrom(this.colorStep);
  56621. other.lifeTime = this.lifeTime;
  56622. other.age = this.age;
  56623. other._randomCellOffset = this._randomCellOffset;
  56624. other.size = this.size;
  56625. other.scale.copyFrom(this.scale);
  56626. other.angle = this.angle;
  56627. other.angularSpeed = this.angularSpeed;
  56628. other.particleSystem = this.particleSystem;
  56629. other.cellIndex = this.cellIndex;
  56630. other.id = this.id;
  56631. other._attachedSubEmitters = this._attachedSubEmitters;
  56632. if (this._currentColorGradient) {
  56633. other._currentColorGradient = this._currentColorGradient;
  56634. other._currentColor1.copyFrom(this._currentColor1);
  56635. other._currentColor2.copyFrom(this._currentColor2);
  56636. }
  56637. if (this._currentSizeGradient) {
  56638. other._currentSizeGradient = this._currentSizeGradient;
  56639. other._currentSize1 = this._currentSize1;
  56640. other._currentSize2 = this._currentSize2;
  56641. }
  56642. if (this._currentAngularSpeedGradient) {
  56643. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  56644. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  56645. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  56646. }
  56647. if (this._currentVelocityGradient) {
  56648. other._currentVelocityGradient = this._currentVelocityGradient;
  56649. other._currentVelocity1 = this._currentVelocity1;
  56650. other._currentVelocity2 = this._currentVelocity2;
  56651. }
  56652. if (this._currentLimitVelocityGradient) {
  56653. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  56654. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  56655. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  56656. }
  56657. if (this._currentDragGradient) {
  56658. other._currentDragGradient = this._currentDragGradient;
  56659. other._currentDrag1 = this._currentDrag1;
  56660. other._currentDrag2 = this._currentDrag2;
  56661. }
  56662. if (this.particleSystem.isAnimationSheetEnabled) {
  56663. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  56664. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  56665. }
  56666. if (this.particleSystem.useRampGradients) {
  56667. other.remapData.copyFrom(this.remapData);
  56668. }
  56669. if (this._randomNoiseCoordinates1) {
  56670. if (other._randomNoiseCoordinates1) {
  56671. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  56672. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  56673. }
  56674. else {
  56675. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  56676. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  56677. }
  56678. }
  56679. };
  56680. Particle._Count = 0;
  56681. return Particle;
  56682. }());
  56683. BABYLON.Particle = Particle;
  56684. })(BABYLON || (BABYLON = {}));
  56685. //# sourceMappingURL=babylon.particle.js.map
  56686. var BABYLON;
  56687. (function (BABYLON) {
  56688. /**
  56689. * This represents the base class for particle system in Babylon.
  56690. * 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.
  56691. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56692. * @example https://doc.babylonjs.com/babylon101/particles
  56693. */
  56694. var BaseParticleSystem = /** @class */ (function () {
  56695. /**
  56696. * Instantiates a particle system.
  56697. * 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.
  56698. * @param name The name of the particle system
  56699. */
  56700. function BaseParticleSystem(name) {
  56701. /**
  56702. * List of animations used by the particle system.
  56703. */
  56704. this.animations = [];
  56705. /**
  56706. * The rendering group used by the Particle system to chose when to render.
  56707. */
  56708. this.renderingGroupId = 0;
  56709. /**
  56710. * The emitter represents the Mesh or position we are attaching the particle system to.
  56711. */
  56712. this.emitter = null;
  56713. /**
  56714. * The maximum number of particles to emit per frame
  56715. */
  56716. this.emitRate = 10;
  56717. /**
  56718. * If you want to launch only a few particles at once, that can be done, as well.
  56719. */
  56720. this.manualEmitCount = -1;
  56721. /**
  56722. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56723. */
  56724. this.updateSpeed = 0.01;
  56725. /**
  56726. * The amount of time the particle system is running (depends of the overall update speed).
  56727. */
  56728. this.targetStopDuration = 0;
  56729. /**
  56730. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56731. */
  56732. this.disposeOnStop = false;
  56733. /**
  56734. * Minimum power of emitting particles.
  56735. */
  56736. this.minEmitPower = 1;
  56737. /**
  56738. * Maximum power of emitting particles.
  56739. */
  56740. this.maxEmitPower = 1;
  56741. /**
  56742. * Minimum life time of emitting particles.
  56743. */
  56744. this.minLifeTime = 1;
  56745. /**
  56746. * Maximum life time of emitting particles.
  56747. */
  56748. this.maxLifeTime = 1;
  56749. /**
  56750. * Minimum Size of emitting particles.
  56751. */
  56752. this.minSize = 1;
  56753. /**
  56754. * Maximum Size of emitting particles.
  56755. */
  56756. this.maxSize = 1;
  56757. /**
  56758. * Minimum scale of emitting particles on X axis.
  56759. */
  56760. this.minScaleX = 1;
  56761. /**
  56762. * Maximum scale of emitting particles on X axis.
  56763. */
  56764. this.maxScaleX = 1;
  56765. /**
  56766. * Minimum scale of emitting particles on Y axis.
  56767. */
  56768. this.minScaleY = 1;
  56769. /**
  56770. * Maximum scale of emitting particles on Y axis.
  56771. */
  56772. this.maxScaleY = 1;
  56773. /**
  56774. * Gets or sets the minimal initial rotation in radians.
  56775. */
  56776. this.minInitialRotation = 0;
  56777. /**
  56778. * Gets or sets the maximal initial rotation in radians.
  56779. */
  56780. this.maxInitialRotation = 0;
  56781. /**
  56782. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56783. */
  56784. this.minAngularSpeed = 0;
  56785. /**
  56786. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56787. */
  56788. this.maxAngularSpeed = 0;
  56789. /**
  56790. * The layer mask we are rendering the particles through.
  56791. */
  56792. this.layerMask = 0x0FFFFFFF;
  56793. /**
  56794. * This can help using your own shader to render the particle system.
  56795. * The according effect will be created
  56796. */
  56797. this.customShader = null;
  56798. /**
  56799. * By default particle system starts as soon as they are created. This prevents the
  56800. * automatic start to happen and let you decide when to start emitting particles.
  56801. */
  56802. this.preventAutoStart = false;
  56803. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  56804. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  56805. /**
  56806. * Callback triggered when the particle animation is ending.
  56807. */
  56808. this.onAnimationEnd = null;
  56809. /**
  56810. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56811. */
  56812. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56813. /**
  56814. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56815. * to override the particles.
  56816. */
  56817. this.forceDepthWrite = false;
  56818. /** 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 */
  56819. this.preWarmCycles = 0;
  56820. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56821. this.preWarmStepOffset = 1;
  56822. /**
  56823. * 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)
  56824. */
  56825. this.spriteCellChangeSpeed = 1;
  56826. /**
  56827. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  56828. */
  56829. this.startSpriteCellID = 0;
  56830. /**
  56831. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  56832. */
  56833. this.endSpriteCellID = 0;
  56834. /**
  56835. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  56836. */
  56837. this.spriteCellWidth = 0;
  56838. /**
  56839. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  56840. */
  56841. this.spriteCellHeight = 0;
  56842. /**
  56843. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  56844. */
  56845. this.spriteRandomStartCell = false;
  56846. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  56847. this.translationPivot = new BABYLON.Vector2(0, 0);
  56848. /**
  56849. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  56850. */
  56851. this.beginAnimationOnStart = false;
  56852. /**
  56853. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  56854. */
  56855. this.beginAnimationFrom = 0;
  56856. /**
  56857. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  56858. */
  56859. this.beginAnimationTo = 60;
  56860. /**
  56861. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  56862. */
  56863. this.beginAnimationLoop = false;
  56864. /**
  56865. * You can use gravity if you want to give an orientation to your particles.
  56866. */
  56867. this.gravity = BABYLON.Vector3.Zero();
  56868. this._colorGradients = null;
  56869. this._sizeGradients = null;
  56870. this._lifeTimeGradients = null;
  56871. this._angularSpeedGradients = null;
  56872. this._velocityGradients = null;
  56873. this._limitVelocityGradients = null;
  56874. this._dragGradients = null;
  56875. this._emitRateGradients = null;
  56876. this._startSizeGradients = null;
  56877. this._rampGradients = null;
  56878. this._colorRemapGradients = null;
  56879. this._alphaRemapGradients = null;
  56880. /**
  56881. * Defines the delay in milliseconds before starting the system (0 by default)
  56882. */
  56883. this.startDelay = 0;
  56884. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  56885. this.limitVelocityDamping = 0.4;
  56886. /**
  56887. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56888. */
  56889. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56890. /**
  56891. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56892. */
  56893. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56894. /**
  56895. * Color the particle will have at the end of its lifetime
  56896. */
  56897. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56898. /**
  56899. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  56900. */
  56901. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56902. /** @hidden */
  56903. this._isSubEmitter = false;
  56904. /**
  56905. * Gets or sets the billboard mode to use when isBillboardBased = true.
  56906. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  56907. */
  56908. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  56909. this._isBillboardBased = true;
  56910. /**
  56911. * Local cache of defines for image processing.
  56912. */
  56913. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  56914. this.id = name;
  56915. this.name = name;
  56916. }
  56917. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  56918. /**
  56919. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  56920. */
  56921. get: function () {
  56922. return this._isAnimationSheetEnabled;
  56923. },
  56924. set: function (value) {
  56925. if (this._isAnimationSheetEnabled == value) {
  56926. return;
  56927. }
  56928. this._isAnimationSheetEnabled = value;
  56929. this._reset();
  56930. },
  56931. enumerable: true,
  56932. configurable: true
  56933. });
  56934. /**
  56935. * Get hosting scene
  56936. * @returns the scene
  56937. */
  56938. BaseParticleSystem.prototype.getScene = function () {
  56939. return this._scene;
  56940. };
  56941. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  56942. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  56943. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  56944. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  56945. };
  56946. /**
  56947. * Gets the current list of drag gradients.
  56948. * You must use addDragGradient and removeDragGradient to udpate this list
  56949. * @returns the list of drag gradients
  56950. */
  56951. BaseParticleSystem.prototype.getDragGradients = function () {
  56952. return this._dragGradients;
  56953. };
  56954. /**
  56955. * Gets the current list of limit velocity gradients.
  56956. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  56957. * @returns the list of limit velocity gradients
  56958. */
  56959. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  56960. return this._limitVelocityGradients;
  56961. };
  56962. /**
  56963. * Gets the current list of color gradients.
  56964. * You must use addColorGradient and removeColorGradient to udpate this list
  56965. * @returns the list of color gradients
  56966. */
  56967. BaseParticleSystem.prototype.getColorGradients = function () {
  56968. return this._colorGradients;
  56969. };
  56970. /**
  56971. * Gets the current list of size gradients.
  56972. * You must use addSizeGradient and removeSizeGradient to udpate this list
  56973. * @returns the list of size gradients
  56974. */
  56975. BaseParticleSystem.prototype.getSizeGradients = function () {
  56976. return this._sizeGradients;
  56977. };
  56978. /**
  56979. * Gets the current list of color remap gradients.
  56980. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  56981. * @returns the list of color remap gradients
  56982. */
  56983. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  56984. return this._colorRemapGradients;
  56985. };
  56986. /**
  56987. * Gets the current list of alpha remap gradients.
  56988. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  56989. * @returns the list of alpha remap gradients
  56990. */
  56991. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  56992. return this._alphaRemapGradients;
  56993. };
  56994. /**
  56995. * Gets the current list of life time gradients.
  56996. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  56997. * @returns the list of life time gradients
  56998. */
  56999. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  57000. return this._lifeTimeGradients;
  57001. };
  57002. /**
  57003. * Gets the current list of angular speed gradients.
  57004. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57005. * @returns the list of angular speed gradients
  57006. */
  57007. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  57008. return this._angularSpeedGradients;
  57009. };
  57010. /**
  57011. * Gets the current list of velocity gradients.
  57012. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57013. * @returns the list of velocity gradients
  57014. */
  57015. BaseParticleSystem.prototype.getVelocityGradients = function () {
  57016. return this._velocityGradients;
  57017. };
  57018. /**
  57019. * Gets the current list of start size gradients.
  57020. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  57021. * @returns the list of start size gradients
  57022. */
  57023. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  57024. return this._startSizeGradients;
  57025. };
  57026. /**
  57027. * Gets the current list of emit rate gradients.
  57028. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  57029. * @returns the list of emit rate gradients
  57030. */
  57031. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  57032. return this._emitRateGradients;
  57033. };
  57034. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  57035. /**
  57036. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57037. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57038. */
  57039. get: function () {
  57040. if (this.particleEmitterType.direction1) {
  57041. return this.particleEmitterType.direction1;
  57042. }
  57043. return BABYLON.Vector3.Zero();
  57044. },
  57045. set: function (value) {
  57046. if (this.particleEmitterType.direction1) {
  57047. this.particleEmitterType.direction1 = value;
  57048. }
  57049. },
  57050. enumerable: true,
  57051. configurable: true
  57052. });
  57053. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  57054. /**
  57055. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57056. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57057. */
  57058. get: function () {
  57059. if (this.particleEmitterType.direction2) {
  57060. return this.particleEmitterType.direction2;
  57061. }
  57062. return BABYLON.Vector3.Zero();
  57063. },
  57064. set: function (value) {
  57065. if (this.particleEmitterType.direction2) {
  57066. this.particleEmitterType.direction2 = value;
  57067. }
  57068. },
  57069. enumerable: true,
  57070. configurable: true
  57071. });
  57072. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  57073. /**
  57074. * 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.
  57075. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57076. */
  57077. get: function () {
  57078. if (this.particleEmitterType.minEmitBox) {
  57079. return this.particleEmitterType.minEmitBox;
  57080. }
  57081. return BABYLON.Vector3.Zero();
  57082. },
  57083. set: function (value) {
  57084. if (this.particleEmitterType.minEmitBox) {
  57085. this.particleEmitterType.minEmitBox = value;
  57086. }
  57087. },
  57088. enumerable: true,
  57089. configurable: true
  57090. });
  57091. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  57092. /**
  57093. * 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.
  57094. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57095. */
  57096. get: function () {
  57097. if (this.particleEmitterType.maxEmitBox) {
  57098. return this.particleEmitterType.maxEmitBox;
  57099. }
  57100. return BABYLON.Vector3.Zero();
  57101. },
  57102. set: function (value) {
  57103. if (this.particleEmitterType.maxEmitBox) {
  57104. this.particleEmitterType.maxEmitBox = value;
  57105. }
  57106. },
  57107. enumerable: true,
  57108. configurable: true
  57109. });
  57110. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  57111. /**
  57112. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57113. */
  57114. get: function () {
  57115. return this._isBillboardBased;
  57116. },
  57117. set: function (value) {
  57118. if (this._isBillboardBased === value) {
  57119. return;
  57120. }
  57121. this._isBillboardBased = value;
  57122. this._reset();
  57123. },
  57124. enumerable: true,
  57125. configurable: true
  57126. });
  57127. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  57128. /**
  57129. * Gets the image processing configuration used either in this material.
  57130. */
  57131. get: function () {
  57132. return this._imageProcessingConfiguration;
  57133. },
  57134. /**
  57135. * Sets the Default image processing configuration used either in the this material.
  57136. *
  57137. * If sets to null, the scene one is in use.
  57138. */
  57139. set: function (value) {
  57140. this._attachImageProcessingConfiguration(value);
  57141. },
  57142. enumerable: true,
  57143. configurable: true
  57144. });
  57145. /**
  57146. * Attaches a new image processing configuration to the Standard Material.
  57147. * @param configuration
  57148. */
  57149. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  57150. if (configuration === this._imageProcessingConfiguration) {
  57151. return;
  57152. }
  57153. // Pick the scene configuration if needed.
  57154. if (!configuration) {
  57155. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  57156. }
  57157. else {
  57158. this._imageProcessingConfiguration = configuration;
  57159. }
  57160. };
  57161. /** @hidden */
  57162. BaseParticleSystem.prototype._reset = function () {
  57163. };
  57164. /** @hidden */
  57165. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  57166. if (!gradients) {
  57167. return this;
  57168. }
  57169. var index = 0;
  57170. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57171. var valueGradient = gradients_1[_i];
  57172. if (valueGradient.gradient === gradient) {
  57173. gradients.splice(index, 1);
  57174. break;
  57175. }
  57176. index++;
  57177. }
  57178. if (texture) {
  57179. texture.dispose();
  57180. }
  57181. return this;
  57182. };
  57183. /**
  57184. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  57185. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57186. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57187. * @returns the emitter
  57188. */
  57189. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  57190. var particleEmitter = new BABYLON.PointParticleEmitter();
  57191. particleEmitter.direction1 = direction1;
  57192. particleEmitter.direction2 = direction2;
  57193. this.particleEmitterType = particleEmitter;
  57194. return particleEmitter;
  57195. };
  57196. /**
  57197. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  57198. * @param radius The radius of the hemisphere to emit from
  57199. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57200. * @returns the emitter
  57201. */
  57202. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  57203. if (radius === void 0) { radius = 1; }
  57204. if (radiusRange === void 0) { radiusRange = 1; }
  57205. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  57206. this.particleEmitterType = particleEmitter;
  57207. return particleEmitter;
  57208. };
  57209. /**
  57210. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  57211. * @param radius The radius of the sphere to emit from
  57212. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57213. * @returns the emitter
  57214. */
  57215. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  57216. if (radius === void 0) { radius = 1; }
  57217. if (radiusRange === void 0) { radiusRange = 1; }
  57218. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  57219. this.particleEmitterType = particleEmitter;
  57220. return particleEmitter;
  57221. };
  57222. /**
  57223. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  57224. * @param radius The radius of the sphere to emit from
  57225. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57226. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57227. * @returns the emitter
  57228. */
  57229. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57230. if (radius === void 0) { radius = 1; }
  57231. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57232. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57233. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57234. this.particleEmitterType = particleEmitter;
  57235. return particleEmitter;
  57236. };
  57237. /**
  57238. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  57239. * @param radius The radius of the emission cylinder
  57240. * @param height The height of the emission cylinder
  57241. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  57242. * @param directionRandomizer How much to randomize the particle direction [0-1]
  57243. * @returns the emitter
  57244. */
  57245. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  57246. if (radius === void 0) { radius = 1; }
  57247. if (height === void 0) { height = 1; }
  57248. if (radiusRange === void 0) { radiusRange = 1; }
  57249. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57250. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  57251. this.particleEmitterType = particleEmitter;
  57252. return particleEmitter;
  57253. };
  57254. /**
  57255. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  57256. * @param radius The radius of the cylinder to emit from
  57257. * @param height The height of the emission cylinder
  57258. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57259. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  57260. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  57261. * @returns the emitter
  57262. */
  57263. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  57264. if (radius === void 0) { radius = 1; }
  57265. if (height === void 0) { height = 1; }
  57266. if (radiusRange === void 0) { radiusRange = 1; }
  57267. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57268. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57269. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  57270. this.particleEmitterType = particleEmitter;
  57271. return particleEmitter;
  57272. };
  57273. /**
  57274. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  57275. * @param radius The radius of the cone to emit from
  57276. * @param angle The base angle of the cone
  57277. * @returns the emitter
  57278. */
  57279. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57280. if (radius === void 0) { radius = 1; }
  57281. if (angle === void 0) { angle = Math.PI / 4; }
  57282. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57283. this.particleEmitterType = particleEmitter;
  57284. return particleEmitter;
  57285. };
  57286. /**
  57287. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57288. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57289. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57290. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57291. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57292. * @returns the emitter
  57293. */
  57294. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57295. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57296. this.particleEmitterType = particleEmitter;
  57297. this.direction1 = direction1;
  57298. this.direction2 = direction2;
  57299. this.minEmitBox = minEmitBox;
  57300. this.maxEmitBox = maxEmitBox;
  57301. return particleEmitter;
  57302. };
  57303. /**
  57304. * Source color is added to the destination color without alpha affecting the result
  57305. */
  57306. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  57307. /**
  57308. * Blend current color and particle color using particle’s alpha
  57309. */
  57310. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  57311. /**
  57312. * Add current color and particle color multiplied by particle’s alpha
  57313. */
  57314. BaseParticleSystem.BLENDMODE_ADD = 2;
  57315. /**
  57316. * Multiply current color with particle color
  57317. */
  57318. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  57319. /**
  57320. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  57321. */
  57322. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  57323. return BaseParticleSystem;
  57324. }());
  57325. BABYLON.BaseParticleSystem = BaseParticleSystem;
  57326. })(BABYLON || (BABYLON = {}));
  57327. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  57328. var BABYLON;
  57329. (function (BABYLON) {
  57330. /**
  57331. * This represents a particle system in Babylon.
  57332. * 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.
  57333. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57334. * @example https://doc.babylonjs.com/babylon101/particles
  57335. */
  57336. var ParticleSystem = /** @class */ (function (_super) {
  57337. __extends(ParticleSystem, _super);
  57338. /**
  57339. * Instantiates a particle system.
  57340. * 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.
  57341. * @param name The name of the particle system
  57342. * @param capacity The max number of particles alive at the same time
  57343. * @param scene The scene the particle system belongs to
  57344. * @param customEffect a custom effect used to change the way particles are rendered by default
  57345. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57346. * @param epsilon Offset used to render the particles
  57347. */
  57348. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  57349. if (customEffect === void 0) { customEffect = null; }
  57350. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57351. if (epsilon === void 0) { epsilon = 0.01; }
  57352. var _this = _super.call(this, name) || this;
  57353. /**
  57354. * @hidden
  57355. */
  57356. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  57357. /**
  57358. * An event triggered when the system is disposed
  57359. */
  57360. _this.onDisposeObservable = new BABYLON.Observable();
  57361. _this._particles = new Array();
  57362. _this._stockParticles = new Array();
  57363. _this._newPartsExcess = 0;
  57364. _this._vertexBuffers = {};
  57365. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  57366. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  57367. _this._scaledDirection = BABYLON.Vector3.Zero();
  57368. _this._scaledGravity = BABYLON.Vector3.Zero();
  57369. _this._currentRenderId = -1;
  57370. _this._useInstancing = false;
  57371. _this._started = false;
  57372. _this._stopped = false;
  57373. _this._actualFrame = 0;
  57374. /** @hidden */
  57375. _this._currentEmitRate1 = 0;
  57376. /** @hidden */
  57377. _this._currentEmitRate2 = 0;
  57378. /** @hidden */
  57379. _this._currentStartSize1 = 0;
  57380. /** @hidden */
  57381. _this._currentStartSize2 = 0;
  57382. _this._rawTextureWidth = 256;
  57383. _this._useRampGradients = false;
  57384. /**
  57385. * @hidden
  57386. * If the particle systems emitter should be disposed when the particle system is disposed
  57387. */
  57388. _this._disposeEmitterOnDispose = false;
  57389. // start of sub system methods
  57390. /**
  57391. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  57392. * Its lifetime will start back at 0.
  57393. */
  57394. _this.recycleParticle = function (particle) {
  57395. // move particle from activeParticle list to stock particles
  57396. var lastParticle = _this._particles.pop();
  57397. if (lastParticle !== particle) {
  57398. lastParticle.copyTo(particle);
  57399. }
  57400. _this._stockParticles.push(lastParticle);
  57401. };
  57402. _this._createParticle = function () {
  57403. var particle;
  57404. if (_this._stockParticles.length !== 0) {
  57405. particle = _this._stockParticles.pop();
  57406. particle._reset();
  57407. }
  57408. else {
  57409. particle = new BABYLON.Particle(_this);
  57410. }
  57411. // Attach emitters
  57412. if (_this._subEmitters && _this._subEmitters.length > 0) {
  57413. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  57414. particle._attachedSubEmitters = [];
  57415. subEmitters.forEach(function (subEmitter) {
  57416. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  57417. var newEmitter = subEmitter.clone();
  57418. particle._attachedSubEmitters.push(newEmitter);
  57419. newEmitter.particleSystem.start();
  57420. }
  57421. });
  57422. }
  57423. return particle;
  57424. };
  57425. _this._emitFromParticle = function (particle) {
  57426. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  57427. return;
  57428. }
  57429. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  57430. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  57431. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  57432. var subSystem = subEmitter.clone();
  57433. particle._inheritParticleInfoToSubEmitter(subSystem);
  57434. subSystem.particleSystem._rootParticleSystem = _this;
  57435. _this.activeSubSystems.push(subSystem.particleSystem);
  57436. subSystem.particleSystem.start();
  57437. }
  57438. });
  57439. };
  57440. _this._capacity = capacity;
  57441. _this._epsilon = epsilon;
  57442. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57443. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57444. // Setup the default processing configuration to the scene.
  57445. _this._attachImageProcessingConfiguration(null);
  57446. _this._customEffect = customEffect;
  57447. _this._scene.particleSystems.push(_this);
  57448. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  57449. _this._createIndexBuffer();
  57450. _this._createVertexBuffers();
  57451. // Default emitter type
  57452. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57453. // Update
  57454. _this.updateFunction = function (particles) {
  57455. var noiseTextureSize = null;
  57456. var noiseTextureData = null;
  57457. if (_this.noiseTexture) { // We need to get texture data back to CPU
  57458. noiseTextureSize = _this.noiseTexture.getSize();
  57459. noiseTextureData = (_this.noiseTexture.getContent());
  57460. }
  57461. var _loop_1 = function () {
  57462. particle = particles[index];
  57463. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  57464. var previousAge = particle.age;
  57465. particle.age += scaledUpdateSpeed;
  57466. // Evaluate step to death
  57467. if (particle.age > particle.lifeTime) {
  57468. var diff = particle.age - previousAge;
  57469. var oldDiff = particle.lifeTime - previousAge;
  57470. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  57471. particle.age = particle.lifeTime;
  57472. }
  57473. var ratio = particle.age / particle.lifeTime;
  57474. // Color
  57475. if (_this._colorGradients && _this._colorGradients.length > 0) {
  57476. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  57477. if (currentGradient !== particle._currentColorGradient) {
  57478. particle._currentColor1.copyFrom(particle._currentColor2);
  57479. nextGradient.getColorToRef(particle._currentColor2);
  57480. particle._currentColorGradient = currentGradient;
  57481. }
  57482. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  57483. });
  57484. }
  57485. else {
  57486. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  57487. particle.color.addInPlace(_this._scaledColorStep);
  57488. if (particle.color.a < 0) {
  57489. particle.color.a = 0;
  57490. }
  57491. }
  57492. // Angular speed
  57493. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  57494. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  57495. if (currentGradient !== particle._currentAngularSpeedGradient) {
  57496. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  57497. particle._currentAngularSpeed2 = nextGradient.getFactor();
  57498. particle._currentAngularSpeedGradient = currentGradient;
  57499. }
  57500. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  57501. });
  57502. }
  57503. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  57504. // Direction
  57505. var directionScale = scaledUpdateSpeed;
  57506. /// Velocity
  57507. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  57508. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  57509. if (currentGradient !== particle._currentVelocityGradient) {
  57510. particle._currentVelocity1 = particle._currentVelocity2;
  57511. particle._currentVelocity2 = nextGradient.getFactor();
  57512. particle._currentVelocityGradient = currentGradient;
  57513. }
  57514. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  57515. });
  57516. }
  57517. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  57518. /// Limit velocity
  57519. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  57520. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  57521. if (currentGradient !== particle._currentLimitVelocityGradient) {
  57522. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  57523. particle._currentLimitVelocity2 = nextGradient.getFactor();
  57524. particle._currentLimitVelocityGradient = currentGradient;
  57525. }
  57526. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  57527. var currentVelocity = particle.direction.length();
  57528. if (currentVelocity > limitVelocity) {
  57529. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  57530. }
  57531. });
  57532. }
  57533. /// Drag
  57534. if (_this._dragGradients && _this._dragGradients.length > 0) {
  57535. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  57536. if (currentGradient !== particle._currentDragGradient) {
  57537. particle._currentDrag1 = particle._currentDrag2;
  57538. particle._currentDrag2 = nextGradient.getFactor();
  57539. particle._currentDragGradient = currentGradient;
  57540. }
  57541. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  57542. _this._scaledDirection.scaleInPlace(1.0 - drag);
  57543. });
  57544. }
  57545. particle.position.addInPlace(_this._scaledDirection);
  57546. // Noise
  57547. if (noiseTextureData && noiseTextureSize) {
  57548. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57549. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57550. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57551. var force = BABYLON.Tmp.Vector3[0];
  57552. var scaledForce = BABYLON.Tmp.Vector3[1];
  57553. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  57554. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  57555. particle.direction.addInPlace(scaledForce);
  57556. }
  57557. // Gravity
  57558. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  57559. particle.direction.addInPlace(_this._scaledGravity);
  57560. // Size
  57561. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  57562. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57563. if (currentGradient !== particle._currentSizeGradient) {
  57564. particle._currentSize1 = particle._currentSize2;
  57565. particle._currentSize2 = nextGradient.getFactor();
  57566. particle._currentSizeGradient = currentGradient;
  57567. }
  57568. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  57569. });
  57570. }
  57571. // Remap data
  57572. if (_this._useRampGradients) {
  57573. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  57574. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  57575. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57576. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57577. particle.remapData.x = min;
  57578. particle.remapData.y = max - min;
  57579. });
  57580. }
  57581. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  57582. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  57583. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57584. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57585. particle.remapData.z = min;
  57586. particle.remapData.w = max - min;
  57587. });
  57588. }
  57589. }
  57590. if (_this._isAnimationSheetEnabled) {
  57591. particle.updateCellIndex();
  57592. }
  57593. // Update the position of the attached sub-emitters to match their attached particle
  57594. particle._inheritParticleInfoToSubEmitters();
  57595. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  57596. _this._emitFromParticle(particle);
  57597. if (particle._attachedSubEmitters) {
  57598. particle._attachedSubEmitters.forEach(function (subEmitter) {
  57599. subEmitter.particleSystem.disposeOnStop = true;
  57600. subEmitter.particleSystem.stop();
  57601. });
  57602. particle._attachedSubEmitters = null;
  57603. }
  57604. _this.recycleParticle(particle);
  57605. index--;
  57606. return "continue";
  57607. }
  57608. };
  57609. var particle;
  57610. for (var index = 0; index < particles.length; index++) {
  57611. _loop_1();
  57612. }
  57613. };
  57614. return _this;
  57615. }
  57616. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  57617. /**
  57618. * Sets a callback that will be triggered when the system is disposed
  57619. */
  57620. set: function (callback) {
  57621. if (this._onDisposeObserver) {
  57622. this.onDisposeObservable.remove(this._onDisposeObserver);
  57623. }
  57624. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57625. },
  57626. enumerable: true,
  57627. configurable: true
  57628. });
  57629. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  57630. /** Gets or sets a boolean indicating that ramp gradients must be used
  57631. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  57632. */
  57633. get: function () {
  57634. return this._useRampGradients;
  57635. },
  57636. set: function (value) {
  57637. if (this._useRampGradients === value) {
  57638. return;
  57639. }
  57640. this._useRampGradients = value;
  57641. this._resetEffect();
  57642. },
  57643. enumerable: true,
  57644. configurable: true
  57645. });
  57646. Object.defineProperty(ParticleSystem.prototype, "particles", {
  57647. //end of Sub-emitter
  57648. /**
  57649. * Gets the current list of active particles
  57650. */
  57651. get: function () {
  57652. return this._particles;
  57653. },
  57654. enumerable: true,
  57655. configurable: true
  57656. });
  57657. /**
  57658. * Returns the string "ParticleSystem"
  57659. * @returns a string containing the class name
  57660. */
  57661. ParticleSystem.prototype.getClassName = function () {
  57662. return "ParticleSystem";
  57663. };
  57664. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  57665. var newGradient = new BABYLON.FactorGradient();
  57666. newGradient.gradient = gradient;
  57667. newGradient.factor1 = factor;
  57668. newGradient.factor2 = factor2;
  57669. factorGradients.push(newGradient);
  57670. factorGradients.sort(function (a, b) {
  57671. if (a.gradient < b.gradient) {
  57672. return -1;
  57673. }
  57674. else if (a.gradient > b.gradient) {
  57675. return 1;
  57676. }
  57677. return 0;
  57678. });
  57679. };
  57680. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  57681. if (!factorGradients) {
  57682. return;
  57683. }
  57684. var index = 0;
  57685. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  57686. var factorGradient = factorGradients_1[_i];
  57687. if (factorGradient.gradient === gradient) {
  57688. factorGradients.splice(index, 1);
  57689. break;
  57690. }
  57691. index++;
  57692. }
  57693. };
  57694. /**
  57695. * Adds a new life time gradient
  57696. * @param gradient defines the gradient to use (between 0 and 1)
  57697. * @param factor defines the life time factor to affect to the specified gradient
  57698. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57699. * @returns the current particle system
  57700. */
  57701. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  57702. if (!this._lifeTimeGradients) {
  57703. this._lifeTimeGradients = [];
  57704. }
  57705. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  57706. return this;
  57707. };
  57708. /**
  57709. * Remove a specific life time gradient
  57710. * @param gradient defines the gradient to remove
  57711. * @returns the current particle system
  57712. */
  57713. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  57714. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  57715. return this;
  57716. };
  57717. /**
  57718. * Adds a new size gradient
  57719. * @param gradient defines the gradient to use (between 0 and 1)
  57720. * @param factor defines the size factor to affect to the specified gradient
  57721. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57722. * @returns the current particle system
  57723. */
  57724. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  57725. if (!this._sizeGradients) {
  57726. this._sizeGradients = [];
  57727. }
  57728. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  57729. return this;
  57730. };
  57731. /**
  57732. * Remove a specific size gradient
  57733. * @param gradient defines the gradient to remove
  57734. * @returns the current particle system
  57735. */
  57736. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57737. this._removeFactorGradient(this._sizeGradients, gradient);
  57738. return this;
  57739. };
  57740. /**
  57741. * Adds a new color remap gradient
  57742. * @param gradient defines the gradient to use (between 0 and 1)
  57743. * @param min defines the color remap minimal range
  57744. * @param max defines the color remap maximal range
  57745. * @returns the current particle system
  57746. */
  57747. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  57748. if (!this._colorRemapGradients) {
  57749. this._colorRemapGradients = [];
  57750. }
  57751. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  57752. return this;
  57753. };
  57754. /**
  57755. * Remove a specific color remap gradient
  57756. * @param gradient defines the gradient to remove
  57757. * @returns the current particle system
  57758. */
  57759. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  57760. this._removeFactorGradient(this._colorRemapGradients, gradient);
  57761. return this;
  57762. };
  57763. /**
  57764. * Adds a new alpha remap gradient
  57765. * @param gradient defines the gradient to use (between 0 and 1)
  57766. * @param min defines the alpha remap minimal range
  57767. * @param max defines the alpha remap maximal range
  57768. * @returns the current particle system
  57769. */
  57770. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  57771. if (!this._alphaRemapGradients) {
  57772. this._alphaRemapGradients = [];
  57773. }
  57774. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  57775. return this;
  57776. };
  57777. /**
  57778. * Remove a specific alpha remap gradient
  57779. * @param gradient defines the gradient to remove
  57780. * @returns the current particle system
  57781. */
  57782. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  57783. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  57784. return this;
  57785. };
  57786. /**
  57787. * Adds a new angular speed gradient
  57788. * @param gradient defines the gradient to use (between 0 and 1)
  57789. * @param factor defines the angular speed to affect to the specified gradient
  57790. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57791. * @returns the current particle system
  57792. */
  57793. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  57794. if (!this._angularSpeedGradients) {
  57795. this._angularSpeedGradients = [];
  57796. }
  57797. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  57798. return this;
  57799. };
  57800. /**
  57801. * Remove a specific angular speed gradient
  57802. * @param gradient defines the gradient to remove
  57803. * @returns the current particle system
  57804. */
  57805. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57806. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  57807. return this;
  57808. };
  57809. /**
  57810. * Adds a new velocity gradient
  57811. * @param gradient defines the gradient to use (between 0 and 1)
  57812. * @param factor defines the velocity to affect to the specified gradient
  57813. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57814. * @returns the current particle system
  57815. */
  57816. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  57817. if (!this._velocityGradients) {
  57818. this._velocityGradients = [];
  57819. }
  57820. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  57821. return this;
  57822. };
  57823. /**
  57824. * Remove a specific velocity gradient
  57825. * @param gradient defines the gradient to remove
  57826. * @returns the current particle system
  57827. */
  57828. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57829. this._removeFactorGradient(this._velocityGradients, gradient);
  57830. return this;
  57831. };
  57832. /**
  57833. * Adds a new limit velocity gradient
  57834. * @param gradient defines the gradient to use (between 0 and 1)
  57835. * @param factor defines the limit velocity value to affect to the specified gradient
  57836. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57837. * @returns the current particle system
  57838. */
  57839. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  57840. if (!this._limitVelocityGradients) {
  57841. this._limitVelocityGradients = [];
  57842. }
  57843. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  57844. return this;
  57845. };
  57846. /**
  57847. * Remove a specific limit velocity gradient
  57848. * @param gradient defines the gradient to remove
  57849. * @returns the current particle system
  57850. */
  57851. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  57852. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  57853. return this;
  57854. };
  57855. /**
  57856. * Adds a new drag gradient
  57857. * @param gradient defines the gradient to use (between 0 and 1)
  57858. * @param factor defines the drag value to affect to the specified gradient
  57859. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57860. * @returns the current particle system
  57861. */
  57862. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  57863. if (!this._dragGradients) {
  57864. this._dragGradients = [];
  57865. }
  57866. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  57867. return this;
  57868. };
  57869. /**
  57870. * Remove a specific drag gradient
  57871. * @param gradient defines the gradient to remove
  57872. * @returns the current particle system
  57873. */
  57874. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  57875. this._removeFactorGradient(this._dragGradients, gradient);
  57876. return this;
  57877. };
  57878. /**
  57879. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  57880. * @param gradient defines the gradient to use (between 0 and 1)
  57881. * @param factor defines the emit rate value to affect to the specified gradient
  57882. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57883. * @returns the current particle system
  57884. */
  57885. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  57886. if (!this._emitRateGradients) {
  57887. this._emitRateGradients = [];
  57888. }
  57889. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  57890. if (!this._currentEmitRateGradient) {
  57891. this._currentEmitRateGradient = this._emitRateGradients[0];
  57892. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  57893. this._currentEmitRate2 = this._currentEmitRate1;
  57894. }
  57895. if (this._emitRateGradients.length === 2) {
  57896. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  57897. }
  57898. return this;
  57899. };
  57900. /**
  57901. * Remove a specific emit rate gradient
  57902. * @param gradient defines the gradient to remove
  57903. * @returns the current particle system
  57904. */
  57905. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  57906. this._removeFactorGradient(this._emitRateGradients, gradient);
  57907. return this;
  57908. };
  57909. /**
  57910. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  57911. * @param gradient defines the gradient to use (between 0 and 1)
  57912. * @param factor defines the start size value to affect to the specified gradient
  57913. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57914. * @returns the current particle system
  57915. */
  57916. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  57917. if (!this._startSizeGradients) {
  57918. this._startSizeGradients = [];
  57919. }
  57920. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  57921. if (!this._currentStartSizeGradient) {
  57922. this._currentStartSizeGradient = this._startSizeGradients[0];
  57923. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  57924. this._currentStartSize2 = this._currentStartSize1;
  57925. }
  57926. if (this._startSizeGradients.length === 2) {
  57927. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  57928. }
  57929. return this;
  57930. };
  57931. /**
  57932. * Remove a specific start size gradient
  57933. * @param gradient defines the gradient to remove
  57934. * @returns the current particle system
  57935. */
  57936. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  57937. this._removeFactorGradient(this._emitRateGradients, gradient);
  57938. return this;
  57939. };
  57940. ParticleSystem.prototype._createRampGradientTexture = function () {
  57941. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  57942. return;
  57943. }
  57944. var data = new Uint8Array(this._rawTextureWidth * 4);
  57945. var tmpColor = BABYLON.Tmp.Color3[0];
  57946. for (var x = 0; x < this._rawTextureWidth; x++) {
  57947. var ratio = x / this._rawTextureWidth;
  57948. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  57949. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  57950. data[x * 4] = tmpColor.r * 255;
  57951. data[x * 4 + 1] = tmpColor.g * 255;
  57952. data[x * 4 + 2] = tmpColor.b * 255;
  57953. data[x * 4 + 3] = 255;
  57954. });
  57955. }
  57956. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57957. };
  57958. /**
  57959. * Gets the current list of ramp gradients.
  57960. * You must use addRampGradient and removeRampGradient to udpate this list
  57961. * @returns the list of ramp gradients
  57962. */
  57963. ParticleSystem.prototype.getRampGradients = function () {
  57964. return this._rampGradients;
  57965. };
  57966. /**
  57967. * Adds a new ramp gradient used to remap particle colors
  57968. * @param gradient defines the gradient to use (between 0 and 1)
  57969. * @param color defines the color to affect to the specified gradient
  57970. * @returns the current particle system
  57971. */
  57972. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  57973. if (!this._rampGradients) {
  57974. this._rampGradients = [];
  57975. }
  57976. var rampGradient = new BABYLON.Color3Gradient();
  57977. rampGradient.gradient = gradient;
  57978. rampGradient.color = color;
  57979. this._rampGradients.push(rampGradient);
  57980. this._rampGradients.sort(function (a, b) {
  57981. if (a.gradient < b.gradient) {
  57982. return -1;
  57983. }
  57984. else if (a.gradient > b.gradient) {
  57985. return 1;
  57986. }
  57987. return 0;
  57988. });
  57989. if (this._rampGradientsTexture) {
  57990. this._rampGradientsTexture.dispose();
  57991. this._rampGradientsTexture = null;
  57992. }
  57993. this._createRampGradientTexture();
  57994. return this;
  57995. };
  57996. /**
  57997. * Remove a specific ramp gradient
  57998. * @param gradient defines the gradient to remove
  57999. * @returns the current particle system
  58000. */
  58001. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  58002. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  58003. this._rampGradientsTexture = null;
  58004. if (this._rampGradients && this._rampGradients.length > 0) {
  58005. this._createRampGradientTexture();
  58006. }
  58007. return this;
  58008. };
  58009. /**
  58010. * Adds a new color gradient
  58011. * @param gradient defines the gradient to use (between 0 and 1)
  58012. * @param color1 defines the color to affect to the specified gradient
  58013. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  58014. */
  58015. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  58016. if (!this._colorGradients) {
  58017. this._colorGradients = [];
  58018. }
  58019. var colorGradient = new BABYLON.ColorGradient();
  58020. colorGradient.gradient = gradient;
  58021. colorGradient.color1 = color1;
  58022. colorGradient.color2 = color2;
  58023. this._colorGradients.push(colorGradient);
  58024. this._colorGradients.sort(function (a, b) {
  58025. if (a.gradient < b.gradient) {
  58026. return -1;
  58027. }
  58028. else if (a.gradient > b.gradient) {
  58029. return 1;
  58030. }
  58031. return 0;
  58032. });
  58033. return this;
  58034. };
  58035. /**
  58036. * Remove a specific color gradient
  58037. * @param gradient defines the gradient to remove
  58038. */
  58039. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  58040. if (!this._colorGradients) {
  58041. return this;
  58042. }
  58043. var index = 0;
  58044. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  58045. var colorGradient = _a[_i];
  58046. if (colorGradient.gradient === gradient) {
  58047. this._colorGradients.splice(index, 1);
  58048. break;
  58049. }
  58050. index++;
  58051. }
  58052. return this;
  58053. };
  58054. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  58055. u = Math.abs(u) * 0.5 + 0.5;
  58056. v = Math.abs(v) * 0.5 + 0.5;
  58057. var wrappedU = ((u * width) % width) | 0;
  58058. var wrappedV = ((v * height) % height) | 0;
  58059. var position = (wrappedU + wrappedV * width) * 4;
  58060. return pixels[position] / 255;
  58061. };
  58062. ParticleSystem.prototype._reset = function () {
  58063. this._resetEffect();
  58064. };
  58065. ParticleSystem.prototype._resetEffect = function () {
  58066. if (this._vertexBuffer) {
  58067. this._vertexBuffer.dispose();
  58068. this._vertexBuffer = null;
  58069. }
  58070. if (this._spriteBuffer) {
  58071. this._spriteBuffer.dispose();
  58072. this._spriteBuffer = null;
  58073. }
  58074. this._createVertexBuffers();
  58075. };
  58076. ParticleSystem.prototype._createVertexBuffers = function () {
  58077. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  58078. if (this._isAnimationSheetEnabled) {
  58079. this._vertexBufferSize += 1;
  58080. }
  58081. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58082. this._vertexBufferSize += 3;
  58083. }
  58084. if (this._useRampGradients) {
  58085. this._vertexBufferSize += 4;
  58086. }
  58087. var engine = this._scene.getEngine();
  58088. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  58089. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  58090. var dataOffset = 0;
  58091. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58092. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  58093. dataOffset += 3;
  58094. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58095. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  58096. dataOffset += 4;
  58097. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58098. this._vertexBuffers["angle"] = options;
  58099. dataOffset += 1;
  58100. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58101. this._vertexBuffers["size"] = size;
  58102. dataOffset += 2;
  58103. if (this._isAnimationSheetEnabled) {
  58104. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58105. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  58106. dataOffset += 1;
  58107. }
  58108. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58109. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58110. this._vertexBuffers["direction"] = directionBuffer;
  58111. dataOffset += 3;
  58112. }
  58113. if (this._useRampGradients) {
  58114. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58115. this._vertexBuffers["remapData"] = rampDataBuffer;
  58116. dataOffset += 4;
  58117. }
  58118. var offsets;
  58119. if (this._useInstancing) {
  58120. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  58121. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  58122. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  58123. }
  58124. else {
  58125. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58126. dataOffset += 2;
  58127. }
  58128. this._vertexBuffers["offset"] = offsets;
  58129. };
  58130. ParticleSystem.prototype._createIndexBuffer = function () {
  58131. if (this._useInstancing) {
  58132. return;
  58133. }
  58134. var indices = [];
  58135. var index = 0;
  58136. for (var count = 0; count < this._capacity; count++) {
  58137. indices.push(index);
  58138. indices.push(index + 1);
  58139. indices.push(index + 2);
  58140. indices.push(index);
  58141. indices.push(index + 2);
  58142. indices.push(index + 3);
  58143. index += 4;
  58144. }
  58145. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  58146. };
  58147. /**
  58148. * Gets the maximum number of particles active at the same time.
  58149. * @returns The max number of active particles.
  58150. */
  58151. ParticleSystem.prototype.getCapacity = function () {
  58152. return this._capacity;
  58153. };
  58154. /**
  58155. * Gets whether there are still active particles in the system.
  58156. * @returns True if it is alive, otherwise false.
  58157. */
  58158. ParticleSystem.prototype.isAlive = function () {
  58159. return this._alive;
  58160. };
  58161. /**
  58162. * Gets if the system has been started. (Note: this will still be true after stop is called)
  58163. * @returns True if it has been started, otherwise false.
  58164. */
  58165. ParticleSystem.prototype.isStarted = function () {
  58166. return this._started;
  58167. };
  58168. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  58169. var _this = this;
  58170. this._subEmitters = new Array();
  58171. if (this.subEmitters) {
  58172. this.subEmitters.forEach(function (subEmitter) {
  58173. if (subEmitter instanceof ParticleSystem) {
  58174. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  58175. }
  58176. else if (subEmitter instanceof BABYLON.SubEmitter) {
  58177. _this._subEmitters.push([subEmitter]);
  58178. }
  58179. else if (subEmitter instanceof Array) {
  58180. _this._subEmitters.push(subEmitter);
  58181. }
  58182. });
  58183. }
  58184. };
  58185. /**
  58186. * Starts the particle system and begins to emit
  58187. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  58188. */
  58189. ParticleSystem.prototype.start = function (delay) {
  58190. var _this = this;
  58191. if (delay === void 0) { delay = this.startDelay; }
  58192. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  58193. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  58194. }
  58195. if (delay) {
  58196. setTimeout(function () {
  58197. _this.start(0);
  58198. }, delay);
  58199. return;
  58200. }
  58201. // Convert the subEmitters field to the constant type field _subEmitters
  58202. this._prepareSubEmitterInternalArray();
  58203. this._started = true;
  58204. this._stopped = false;
  58205. this._actualFrame = 0;
  58206. if (this._subEmitters && this._subEmitters.length != 0) {
  58207. this.activeSubSystems = new Array();
  58208. }
  58209. if (this.preWarmCycles) {
  58210. if (this.emitter instanceof BABYLON.AbstractMesh) {
  58211. this.emitter.computeWorldMatrix(true);
  58212. }
  58213. var noiseTextureAsProcedural_1 = this.noiseTexture;
  58214. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  58215. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  58216. setTimeout(function () {
  58217. for (var index = 0; index < _this.preWarmCycles; index++) {
  58218. _this.animate(true);
  58219. noiseTextureAsProcedural_1.render();
  58220. }
  58221. });
  58222. });
  58223. }
  58224. else {
  58225. for (var index = 0; index < this.preWarmCycles; index++) {
  58226. this.animate(true);
  58227. }
  58228. }
  58229. }
  58230. // Animations
  58231. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  58232. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  58233. }
  58234. };
  58235. /**
  58236. * Stops the particle system.
  58237. * @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.
  58238. */
  58239. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  58240. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  58241. this._stopped = true;
  58242. if (stopSubEmitters) {
  58243. this._stopSubEmitters();
  58244. }
  58245. };
  58246. // animation sheet
  58247. /**
  58248. * Remove all active particles
  58249. */
  58250. ParticleSystem.prototype.reset = function () {
  58251. this._stockParticles = [];
  58252. this._particles = [];
  58253. };
  58254. /**
  58255. * @hidden (for internal use only)
  58256. */
  58257. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  58258. var offset = index * this._vertexBufferSize;
  58259. this._vertexData[offset++] = particle.position.x;
  58260. this._vertexData[offset++] = particle.position.y;
  58261. this._vertexData[offset++] = particle.position.z;
  58262. this._vertexData[offset++] = particle.color.r;
  58263. this._vertexData[offset++] = particle.color.g;
  58264. this._vertexData[offset++] = particle.color.b;
  58265. this._vertexData[offset++] = particle.color.a;
  58266. this._vertexData[offset++] = particle.angle;
  58267. this._vertexData[offset++] = particle.scale.x * particle.size;
  58268. this._vertexData[offset++] = particle.scale.y * particle.size;
  58269. if (this._isAnimationSheetEnabled) {
  58270. this._vertexData[offset++] = particle.cellIndex;
  58271. }
  58272. if (!this._isBillboardBased) {
  58273. if (particle._initialDirection) {
  58274. this._vertexData[offset++] = particle._initialDirection.x;
  58275. this._vertexData[offset++] = particle._initialDirection.y;
  58276. this._vertexData[offset++] = particle._initialDirection.z;
  58277. }
  58278. else {
  58279. this._vertexData[offset++] = particle.direction.x;
  58280. this._vertexData[offset++] = particle.direction.y;
  58281. this._vertexData[offset++] = particle.direction.z;
  58282. }
  58283. }
  58284. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58285. this._vertexData[offset++] = particle.direction.x;
  58286. this._vertexData[offset++] = particle.direction.y;
  58287. this._vertexData[offset++] = particle.direction.z;
  58288. }
  58289. if (this._useRampGradients) {
  58290. this._vertexData[offset++] = particle.remapData.x;
  58291. this._vertexData[offset++] = particle.remapData.y;
  58292. this._vertexData[offset++] = particle.remapData.z;
  58293. this._vertexData[offset++] = particle.remapData.w;
  58294. }
  58295. if (!this._useInstancing) {
  58296. if (this._isAnimationSheetEnabled) {
  58297. if (offsetX === 0)
  58298. offsetX = this._epsilon;
  58299. else if (offsetX === 1)
  58300. offsetX = 1 - this._epsilon;
  58301. if (offsetY === 0)
  58302. offsetY = this._epsilon;
  58303. else if (offsetY === 1)
  58304. offsetY = 1 - this._epsilon;
  58305. }
  58306. this._vertexData[offset++] = offsetX;
  58307. this._vertexData[offset++] = offsetY;
  58308. }
  58309. };
  58310. ParticleSystem.prototype._stopSubEmitters = function () {
  58311. if (!this.activeSubSystems) {
  58312. return;
  58313. }
  58314. this.activeSubSystems.forEach(function (subSystem) {
  58315. subSystem.stop(true);
  58316. });
  58317. this.activeSubSystems = new Array();
  58318. };
  58319. ParticleSystem.prototype._removeFromRoot = function () {
  58320. if (!this._rootParticleSystem) {
  58321. return;
  58322. }
  58323. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  58324. if (index !== -1) {
  58325. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  58326. }
  58327. this._rootParticleSystem = null;
  58328. };
  58329. // End of sub system methods
  58330. ParticleSystem.prototype._update = function (newParticles) {
  58331. var _this = this;
  58332. // Update current
  58333. this._alive = this._particles.length > 0;
  58334. if (this.emitter.position) {
  58335. var emitterMesh = this.emitter;
  58336. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  58337. }
  58338. else {
  58339. var emitterPosition = this.emitter;
  58340. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58341. }
  58342. this.updateFunction(this._particles);
  58343. // Add new ones
  58344. var particle;
  58345. var _loop_2 = function () {
  58346. if (this_1._particles.length === this_1._capacity) {
  58347. return "break";
  58348. }
  58349. particle = this_1._createParticle();
  58350. this_1._particles.push(particle);
  58351. // Emitter
  58352. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  58353. if (this_1.startPositionFunction) {
  58354. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58355. }
  58356. else {
  58357. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58358. }
  58359. if (this_1.startDirectionFunction) {
  58360. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58361. }
  58362. else {
  58363. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58364. }
  58365. if (emitPower === 0) {
  58366. if (!particle._initialDirection) {
  58367. particle._initialDirection = particle.direction.clone();
  58368. }
  58369. else {
  58370. particle._initialDirection.copyFrom(particle.direction);
  58371. }
  58372. }
  58373. else {
  58374. particle._initialDirection = null;
  58375. }
  58376. particle.direction.scaleInPlace(emitPower);
  58377. // Life time
  58378. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  58379. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  58380. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  58381. var factorGradient1 = currentGradient;
  58382. var factorGradient2 = nextGradient;
  58383. var lifeTime1 = factorGradient1.getFactor();
  58384. var lifeTime2 = factorGradient2.getFactor();
  58385. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  58386. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  58387. });
  58388. }
  58389. else {
  58390. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  58391. }
  58392. // Size
  58393. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  58394. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  58395. }
  58396. else {
  58397. particle._currentSizeGradient = this_1._sizeGradients[0];
  58398. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  58399. particle.size = particle._currentSize1;
  58400. if (this_1._sizeGradients.length > 1) {
  58401. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  58402. }
  58403. else {
  58404. particle._currentSize2 = particle._currentSize1;
  58405. }
  58406. }
  58407. // Size and scale
  58408. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  58409. // Adjust scale by start size
  58410. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  58411. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  58412. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  58413. if (currentGradient !== _this._currentStartSizeGradient) {
  58414. _this._currentStartSize1 = _this._currentStartSize2;
  58415. _this._currentStartSize2 = nextGradient.getFactor();
  58416. _this._currentStartSizeGradient = currentGradient;
  58417. }
  58418. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  58419. particle.scale.scaleInPlace(value);
  58420. });
  58421. }
  58422. // Angle
  58423. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  58424. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  58425. }
  58426. else {
  58427. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  58428. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  58429. particle._currentAngularSpeed1 = particle.angularSpeed;
  58430. if (this_1._angularSpeedGradients.length > 1) {
  58431. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  58432. }
  58433. else {
  58434. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  58435. }
  58436. }
  58437. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  58438. // Velocity
  58439. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  58440. particle._currentVelocityGradient = this_1._velocityGradients[0];
  58441. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  58442. if (this_1._velocityGradients.length > 1) {
  58443. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  58444. }
  58445. else {
  58446. particle._currentVelocity2 = particle._currentVelocity1;
  58447. }
  58448. }
  58449. // Limit velocity
  58450. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  58451. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  58452. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  58453. if (this_1._limitVelocityGradients.length > 1) {
  58454. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  58455. }
  58456. else {
  58457. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  58458. }
  58459. }
  58460. // Drag
  58461. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  58462. particle._currentDragGradient = this_1._dragGradients[0];
  58463. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  58464. if (this_1._dragGradients.length > 1) {
  58465. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  58466. }
  58467. else {
  58468. particle._currentDrag2 = particle._currentDrag1;
  58469. }
  58470. }
  58471. // Color
  58472. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  58473. step = BABYLON.Scalar.RandomRange(0, 1.0);
  58474. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  58475. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  58476. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  58477. }
  58478. else {
  58479. particle._currentColorGradient = this_1._colorGradients[0];
  58480. particle._currentColorGradient.getColorToRef(particle.color);
  58481. particle._currentColor1.copyFrom(particle.color);
  58482. if (this_1._colorGradients.length > 1) {
  58483. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  58484. }
  58485. else {
  58486. particle._currentColor2.copyFrom(particle.color);
  58487. }
  58488. }
  58489. // Sheet
  58490. if (this_1._isAnimationSheetEnabled) {
  58491. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  58492. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  58493. }
  58494. // Inherited Velocity
  58495. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  58496. // Ramp
  58497. if (this_1._useRampGradients) {
  58498. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  58499. }
  58500. // Noise texture coordinates
  58501. if (this_1.noiseTexture) {
  58502. if (particle._randomNoiseCoordinates1) {
  58503. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  58504. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  58505. }
  58506. else {
  58507. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58508. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58509. }
  58510. }
  58511. // Update the position of the attached sub-emitters to match their attached particle
  58512. particle._inheritParticleInfoToSubEmitters();
  58513. };
  58514. var this_1 = this, step;
  58515. for (var index = 0; index < newParticles; index++) {
  58516. var state_1 = _loop_2();
  58517. if (state_1 === "break")
  58518. break;
  58519. }
  58520. };
  58521. /** @hidden */
  58522. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  58523. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58524. if (isBillboardBased === void 0) { isBillboardBased = false; }
  58525. if (useRampGradients === void 0) { useRampGradients = false; }
  58526. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  58527. if (isAnimationSheetEnabled) {
  58528. attributeNamesOrOptions.push("cellIndex");
  58529. }
  58530. if (!isBillboardBased) {
  58531. attributeNamesOrOptions.push("direction");
  58532. }
  58533. if (useRampGradients) {
  58534. attributeNamesOrOptions.push("remapData");
  58535. }
  58536. return attributeNamesOrOptions;
  58537. };
  58538. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  58539. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58540. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  58541. if (isAnimationSheetEnabled) {
  58542. effectCreationOption.push("particlesInfos");
  58543. }
  58544. return effectCreationOption;
  58545. };
  58546. ParticleSystem.prototype._getEffect = function (blendMode) {
  58547. if (this._customEffect) {
  58548. return this._customEffect;
  58549. }
  58550. ;
  58551. var defines = [];
  58552. if (this._scene.clipPlane) {
  58553. defines.push("#define CLIPPLANE");
  58554. }
  58555. if (this._scene.clipPlane2) {
  58556. defines.push("#define CLIPPLANE2");
  58557. }
  58558. if (this._scene.clipPlane3) {
  58559. defines.push("#define CLIPPLANE3");
  58560. }
  58561. if (this._scene.clipPlane4) {
  58562. defines.push("#define CLIPPLANE4");
  58563. }
  58564. if (this._isAnimationSheetEnabled) {
  58565. defines.push("#define ANIMATESHEET");
  58566. }
  58567. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  58568. defines.push("#define BLENDMULTIPLYMODE");
  58569. }
  58570. if (this._useRampGradients) {
  58571. defines.push("#define RAMPGRADIENT");
  58572. }
  58573. if (this._isBillboardBased) {
  58574. defines.push("#define BILLBOARD");
  58575. switch (this.billboardMode) {
  58576. case ParticleSystem.BILLBOARDMODE_Y:
  58577. defines.push("#define BILLBOARDY");
  58578. break;
  58579. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  58580. defines.push("#define BILLBOARDSTRETCHED");
  58581. break;
  58582. case ParticleSystem.BILLBOARDMODE_ALL:
  58583. default:
  58584. break;
  58585. }
  58586. }
  58587. if (this._imageProcessingConfiguration) {
  58588. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  58589. defines.push(this._imageProcessingConfigurationDefines.toString());
  58590. }
  58591. // Effect
  58592. var join = defines.join("\n");
  58593. if (this._cachedDefines !== join) {
  58594. this._cachedDefines = join;
  58595. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  58596. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  58597. var samplers = ["diffuseSampler", "rampSampler"];
  58598. if (BABYLON.ImageProcessingConfiguration) {
  58599. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  58600. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  58601. }
  58602. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  58603. }
  58604. return this._effect;
  58605. };
  58606. /**
  58607. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58608. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  58609. */
  58610. ParticleSystem.prototype.animate = function (preWarmOnly) {
  58611. var _this = this;
  58612. if (preWarmOnly === void 0) { preWarmOnly = false; }
  58613. if (!this._started)
  58614. return;
  58615. if (!preWarmOnly) {
  58616. // Check
  58617. if (!this.isReady())
  58618. return;
  58619. if (this._currentRenderId === this._scene.getRenderId()) {
  58620. return;
  58621. }
  58622. this._currentRenderId = this._scene.getRenderId();
  58623. }
  58624. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  58625. // Determine the number of particles we need to create
  58626. var newParticles;
  58627. if (this.manualEmitCount > -1) {
  58628. newParticles = this.manualEmitCount;
  58629. this._newPartsExcess = 0;
  58630. this.manualEmitCount = 0;
  58631. }
  58632. else {
  58633. var rate_1 = this.emitRate;
  58634. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  58635. var ratio = this._actualFrame / this.targetStopDuration;
  58636. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  58637. if (currentGradient !== _this._currentEmitRateGradient) {
  58638. _this._currentEmitRate1 = _this._currentEmitRate2;
  58639. _this._currentEmitRate2 = nextGradient.getFactor();
  58640. _this._currentEmitRateGradient = currentGradient;
  58641. }
  58642. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  58643. });
  58644. }
  58645. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  58646. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  58647. }
  58648. if (this._newPartsExcess > 1.0) {
  58649. newParticles += this._newPartsExcess >> 0;
  58650. this._newPartsExcess -= this._newPartsExcess >> 0;
  58651. }
  58652. this._alive = false;
  58653. if (!this._stopped) {
  58654. this._actualFrame += this._scaledUpdateSpeed;
  58655. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  58656. this.stop();
  58657. }
  58658. else {
  58659. newParticles = 0;
  58660. }
  58661. this._update(newParticles);
  58662. // Stopped?
  58663. if (this._stopped) {
  58664. if (!this._alive) {
  58665. this._started = false;
  58666. if (this.onAnimationEnd) {
  58667. this.onAnimationEnd();
  58668. }
  58669. if (this.disposeOnStop) {
  58670. this._scene._toBeDisposed.push(this);
  58671. }
  58672. }
  58673. }
  58674. if (!preWarmOnly) {
  58675. // Update VBO
  58676. var offset = 0;
  58677. for (var index = 0; index < this._particles.length; index++) {
  58678. var particle = this._particles[index];
  58679. this._appendParticleVertices(offset, particle);
  58680. offset += this._useInstancing ? 1 : 4;
  58681. }
  58682. if (this._vertexBuffer) {
  58683. this._vertexBuffer.update(this._vertexData);
  58684. }
  58685. }
  58686. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  58687. this.stop();
  58688. }
  58689. };
  58690. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  58691. this._appendParticleVertex(offset++, particle, 0, 0);
  58692. if (!this._useInstancing) {
  58693. this._appendParticleVertex(offset++, particle, 1, 0);
  58694. this._appendParticleVertex(offset++, particle, 1, 1);
  58695. this._appendParticleVertex(offset++, particle, 0, 1);
  58696. }
  58697. };
  58698. /**
  58699. * Rebuilds the particle system.
  58700. */
  58701. ParticleSystem.prototype.rebuild = function () {
  58702. this._createIndexBuffer();
  58703. if (this._vertexBuffer) {
  58704. this._vertexBuffer._rebuild();
  58705. }
  58706. };
  58707. /**
  58708. * Is this system ready to be used/rendered
  58709. * @return true if the system is ready
  58710. */
  58711. ParticleSystem.prototype.isReady = function () {
  58712. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  58713. return false;
  58714. }
  58715. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58716. if (!this._getEffect(this.blendMode).isReady()) {
  58717. return false;
  58718. }
  58719. }
  58720. else {
  58721. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  58722. return false;
  58723. }
  58724. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  58725. return false;
  58726. }
  58727. }
  58728. return true;
  58729. };
  58730. ParticleSystem.prototype._render = function (blendMode) {
  58731. var effect = this._getEffect(blendMode);
  58732. var engine = this._scene.getEngine();
  58733. // Render
  58734. engine.enableEffect(effect);
  58735. var viewMatrix = this._scene.getViewMatrix();
  58736. effect.setTexture("diffuseSampler", this.particleTexture);
  58737. effect.setMatrix("view", viewMatrix);
  58738. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  58739. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58740. var baseSize = this.particleTexture.getBaseSize();
  58741. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58742. }
  58743. effect.setVector2("translationPivot", this.translationPivot);
  58744. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  58745. if (this._isBillboardBased) {
  58746. var camera = this._scene.activeCamera;
  58747. effect.setVector3("eyePosition", camera.globalPosition);
  58748. }
  58749. if (this._rampGradientsTexture) {
  58750. effect.setTexture("rampSampler", this._rampGradientsTexture);
  58751. }
  58752. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  58753. var invView = viewMatrix.clone();
  58754. invView.invert();
  58755. effect.setMatrix("invView", invView);
  58756. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  58757. }
  58758. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  58759. // image processing
  58760. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  58761. this._imageProcessingConfiguration.bind(effect);
  58762. }
  58763. // Draw order
  58764. switch (blendMode) {
  58765. case ParticleSystem.BLENDMODE_ADD:
  58766. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58767. break;
  58768. case ParticleSystem.BLENDMODE_ONEONE:
  58769. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58770. break;
  58771. case ParticleSystem.BLENDMODE_STANDARD:
  58772. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58773. break;
  58774. case ParticleSystem.BLENDMODE_MULTIPLY:
  58775. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  58776. break;
  58777. }
  58778. if (this._useInstancing) {
  58779. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  58780. }
  58781. else {
  58782. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  58783. }
  58784. return this._particles.length;
  58785. };
  58786. /**
  58787. * Renders the particle system in its current state.
  58788. * @returns the current number of particles
  58789. */
  58790. ParticleSystem.prototype.render = function () {
  58791. // Check
  58792. if (!this.isReady() || !this._particles.length) {
  58793. return 0;
  58794. }
  58795. var engine = this._scene.getEngine();
  58796. engine.setState(false);
  58797. if (this.forceDepthWrite) {
  58798. engine.setDepthWrite(true);
  58799. }
  58800. var outparticles = 0;
  58801. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58802. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  58803. }
  58804. outparticles = this._render(this.blendMode);
  58805. engine.unbindInstanceAttributes();
  58806. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58807. return outparticles;
  58808. };
  58809. /**
  58810. * Disposes the particle system and free the associated resources
  58811. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58812. */
  58813. ParticleSystem.prototype.dispose = function (disposeTexture) {
  58814. if (disposeTexture === void 0) { disposeTexture = true; }
  58815. if (this._vertexBuffer) {
  58816. this._vertexBuffer.dispose();
  58817. this._vertexBuffer = null;
  58818. }
  58819. if (this._spriteBuffer) {
  58820. this._spriteBuffer.dispose();
  58821. this._spriteBuffer = null;
  58822. }
  58823. if (this._indexBuffer) {
  58824. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58825. this._indexBuffer = null;
  58826. }
  58827. if (disposeTexture && this.particleTexture) {
  58828. this.particleTexture.dispose();
  58829. this.particleTexture = null;
  58830. }
  58831. if (disposeTexture && this.noiseTexture) {
  58832. this.noiseTexture.dispose();
  58833. this.noiseTexture = null;
  58834. }
  58835. if (this._rampGradientsTexture) {
  58836. this._rampGradientsTexture.dispose();
  58837. this._rampGradientsTexture = null;
  58838. }
  58839. this._removeFromRoot();
  58840. if (this._subEmitters && this._subEmitters.length) {
  58841. for (var index = 0; index < this._subEmitters.length; index++) {
  58842. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  58843. var subEmitter = _a[_i];
  58844. subEmitter.dispose();
  58845. }
  58846. }
  58847. this._subEmitters = [];
  58848. this.subEmitters = [];
  58849. }
  58850. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  58851. this.emitter.dispose(true);
  58852. }
  58853. // Remove from scene
  58854. var index = this._scene.particleSystems.indexOf(this);
  58855. if (index > -1) {
  58856. this._scene.particleSystems.splice(index, 1);
  58857. }
  58858. this._scene._activeParticleSystems.dispose();
  58859. // Callback
  58860. this.onDisposeObservable.notifyObservers(this);
  58861. this.onDisposeObservable.clear();
  58862. this.reset();
  58863. };
  58864. // Clone
  58865. /**
  58866. * Clones the particle system.
  58867. * @param name The name of the cloned object
  58868. * @param newEmitter The new emitter to use
  58869. * @returns the cloned particle system
  58870. */
  58871. ParticleSystem.prototype.clone = function (name, newEmitter) {
  58872. var custom = null;
  58873. var program = null;
  58874. if (this.customShader != null) {
  58875. program = this.customShader;
  58876. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58877. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58878. }
  58879. else if (this._customEffect) {
  58880. custom = this._customEffect;
  58881. }
  58882. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  58883. result.customShader = program;
  58884. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  58885. if (newEmitter === undefined) {
  58886. newEmitter = this.emitter;
  58887. }
  58888. result.noiseTexture = this.noiseTexture;
  58889. result.emitter = newEmitter;
  58890. if (this.particleTexture) {
  58891. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58892. }
  58893. // Clone gradients
  58894. if (this._colorGradients) {
  58895. this._colorGradients.forEach(function (v) {
  58896. result.addColorGradient(v.gradient, v.color1, v.color2);
  58897. });
  58898. }
  58899. if (this._dragGradients) {
  58900. this._dragGradients.forEach(function (v) {
  58901. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  58902. });
  58903. }
  58904. if (this._angularSpeedGradients) {
  58905. this._angularSpeedGradients.forEach(function (v) {
  58906. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  58907. });
  58908. }
  58909. if (this._emitRateGradients) {
  58910. this._emitRateGradients.forEach(function (v) {
  58911. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  58912. });
  58913. }
  58914. if (this._lifeTimeGradients) {
  58915. this._lifeTimeGradients.forEach(function (v) {
  58916. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  58917. });
  58918. }
  58919. if (this._limitVelocityGradients) {
  58920. this._limitVelocityGradients.forEach(function (v) {
  58921. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  58922. });
  58923. }
  58924. if (this._sizeGradients) {
  58925. this._sizeGradients.forEach(function (v) {
  58926. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  58927. });
  58928. }
  58929. if (this._startSizeGradients) {
  58930. this._startSizeGradients.forEach(function (v) {
  58931. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  58932. });
  58933. }
  58934. if (this._velocityGradients) {
  58935. this._velocityGradients.forEach(function (v) {
  58936. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  58937. });
  58938. }
  58939. if (this._rampGradients) {
  58940. this._rampGradients.forEach(function (v) {
  58941. result.addRampGradient(v.gradient, v.color);
  58942. });
  58943. }
  58944. if (this._colorRemapGradients) {
  58945. this._colorRemapGradients.forEach(function (v) {
  58946. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  58947. });
  58948. }
  58949. if (this._alphaRemapGradients) {
  58950. this._alphaRemapGradients.forEach(function (v) {
  58951. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  58952. });
  58953. }
  58954. if (!this.preventAutoStart) {
  58955. result.start();
  58956. }
  58957. return result;
  58958. };
  58959. /**
  58960. * Serializes the particle system to a JSON object.
  58961. * @returns the JSON object
  58962. */
  58963. ParticleSystem.prototype.serialize = function () {
  58964. var serializationObject = {};
  58965. ParticleSystem._Serialize(serializationObject, this);
  58966. serializationObject.textureMask = this.textureMask.asArray();
  58967. serializationObject.customShader = this.customShader;
  58968. serializationObject.preventAutoStart = this.preventAutoStart;
  58969. // SubEmitters
  58970. if (this.subEmitters) {
  58971. serializationObject.subEmitters = [];
  58972. if (!this._subEmitters) {
  58973. this._prepareSubEmitterInternalArray();
  58974. }
  58975. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  58976. var subs = _a[_i];
  58977. var cell = [];
  58978. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  58979. var sub = subs_1[_b];
  58980. cell.push(sub.serialize());
  58981. }
  58982. serializationObject.subEmitters.push(cell);
  58983. }
  58984. }
  58985. return serializationObject;
  58986. };
  58987. /** @hidden */
  58988. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  58989. serializationObject.name = particleSystem.name;
  58990. serializationObject.id = particleSystem.id;
  58991. serializationObject.capacity = particleSystem.getCapacity();
  58992. // Emitter
  58993. if (particleSystem.emitter.position) {
  58994. var emitterMesh = particleSystem.emitter;
  58995. serializationObject.emitterId = emitterMesh.id;
  58996. }
  58997. else {
  58998. var emitterPosition = particleSystem.emitter;
  58999. serializationObject.emitter = emitterPosition.asArray();
  59000. }
  59001. // Emitter
  59002. if (particleSystem.particleEmitterType) {
  59003. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  59004. }
  59005. if (particleSystem.particleTexture) {
  59006. serializationObject.textureName = particleSystem.particleTexture.name;
  59007. serializationObject.invertY = particleSystem.particleTexture._invertY;
  59008. }
  59009. // Animations
  59010. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  59011. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  59012. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  59013. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  59014. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  59015. // Particle system
  59016. serializationObject.startDelay = particleSystem.startDelay;
  59017. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  59018. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  59019. serializationObject.billboardMode = particleSystem.billboardMode;
  59020. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  59021. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  59022. serializationObject.minSize = particleSystem.minSize;
  59023. serializationObject.maxSize = particleSystem.maxSize;
  59024. serializationObject.minScaleX = particleSystem.minScaleX;
  59025. serializationObject.maxScaleX = particleSystem.maxScaleX;
  59026. serializationObject.minScaleY = particleSystem.minScaleY;
  59027. serializationObject.maxScaleY = particleSystem.maxScaleY;
  59028. serializationObject.minEmitPower = particleSystem.minEmitPower;
  59029. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  59030. serializationObject.minLifeTime = particleSystem.minLifeTime;
  59031. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  59032. serializationObject.emitRate = particleSystem.emitRate;
  59033. serializationObject.gravity = particleSystem.gravity.asArray();
  59034. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  59035. serializationObject.color1 = particleSystem.color1.asArray();
  59036. serializationObject.color2 = particleSystem.color2.asArray();
  59037. serializationObject.colorDead = particleSystem.colorDead.asArray();
  59038. serializationObject.updateSpeed = particleSystem.updateSpeed;
  59039. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  59040. serializationObject.blendMode = particleSystem.blendMode;
  59041. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  59042. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  59043. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  59044. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  59045. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  59046. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  59047. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  59048. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  59049. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  59050. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  59051. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  59052. var colorGradients = particleSystem.getColorGradients();
  59053. if (colorGradients) {
  59054. serializationObject.colorGradients = [];
  59055. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  59056. var colorGradient = colorGradients_1[_i];
  59057. var serializedGradient = {
  59058. gradient: colorGradient.gradient,
  59059. color1: colorGradient.color1.asArray()
  59060. };
  59061. if (colorGradient.color2) {
  59062. serializedGradient.color2 = colorGradient.color2.asArray();
  59063. }
  59064. serializationObject.colorGradients.push(serializedGradient);
  59065. }
  59066. }
  59067. var rampGradients = particleSystem.getRampGradients();
  59068. if (rampGradients) {
  59069. serializationObject.rampGradients = [];
  59070. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  59071. var rampGradient = rampGradients_1[_a];
  59072. var serializedGradient = {
  59073. gradient: rampGradient.gradient,
  59074. color: rampGradient.color.asArray()
  59075. };
  59076. serializationObject.rampGradients.push(serializedGradient);
  59077. }
  59078. serializationObject.useRampGradients = particleSystem.useRampGradients;
  59079. }
  59080. var colorRemapGradients = particleSystem.getColorRemapGradients();
  59081. if (colorRemapGradients) {
  59082. serializationObject.colorRemapGradients = [];
  59083. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  59084. var colorRemapGradient = colorRemapGradients_1[_b];
  59085. var serializedGradient = {
  59086. gradient: colorRemapGradient.gradient,
  59087. factor1: colorRemapGradient.factor1
  59088. };
  59089. if (colorRemapGradient.factor2 !== undefined) {
  59090. serializedGradient.factor2 = colorRemapGradient.factor2;
  59091. }
  59092. serializationObject.colorRemapGradients.push(serializedGradient);
  59093. }
  59094. }
  59095. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  59096. if (alphaRemapGradients) {
  59097. serializationObject.alphaRemapGradients = [];
  59098. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  59099. var alphaRemapGradient = alphaRemapGradients_1[_c];
  59100. var serializedGradient = {
  59101. gradient: alphaRemapGradient.gradient,
  59102. factor1: alphaRemapGradient.factor1
  59103. };
  59104. if (alphaRemapGradient.factor2 !== undefined) {
  59105. serializedGradient.factor2 = alphaRemapGradient.factor2;
  59106. }
  59107. serializationObject.alphaRemapGradients.push(serializedGradient);
  59108. }
  59109. }
  59110. var sizeGradients = particleSystem.getSizeGradients();
  59111. if (sizeGradients) {
  59112. serializationObject.sizeGradients = [];
  59113. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  59114. var sizeGradient = sizeGradients_1[_d];
  59115. var serializedGradient = {
  59116. gradient: sizeGradient.gradient,
  59117. factor1: sizeGradient.factor1
  59118. };
  59119. if (sizeGradient.factor2 !== undefined) {
  59120. serializedGradient.factor2 = sizeGradient.factor2;
  59121. }
  59122. serializationObject.sizeGradients.push(serializedGradient);
  59123. }
  59124. }
  59125. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  59126. if (angularSpeedGradients) {
  59127. serializationObject.angularSpeedGradients = [];
  59128. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  59129. var angularSpeedGradient = angularSpeedGradients_1[_e];
  59130. var serializedGradient = {
  59131. gradient: angularSpeedGradient.gradient,
  59132. factor1: angularSpeedGradient.factor1
  59133. };
  59134. if (angularSpeedGradient.factor2 !== undefined) {
  59135. serializedGradient.factor2 = angularSpeedGradient.factor2;
  59136. }
  59137. serializationObject.angularSpeedGradients.push(serializedGradient);
  59138. }
  59139. }
  59140. var velocityGradients = particleSystem.getVelocityGradients();
  59141. if (velocityGradients) {
  59142. serializationObject.velocityGradients = [];
  59143. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  59144. var velocityGradient = velocityGradients_1[_f];
  59145. var serializedGradient = {
  59146. gradient: velocityGradient.gradient,
  59147. factor1: velocityGradient.factor1
  59148. };
  59149. if (velocityGradient.factor2 !== undefined) {
  59150. serializedGradient.factor2 = velocityGradient.factor2;
  59151. }
  59152. serializationObject.velocityGradients.push(serializedGradient);
  59153. }
  59154. }
  59155. var dragGradients = particleSystem.getDragGradients();
  59156. if (dragGradients) {
  59157. serializationObject.dragyGradients = [];
  59158. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  59159. var dragGradient = dragGradients_1[_g];
  59160. var serializedGradient = {
  59161. gradient: dragGradient.gradient,
  59162. factor1: dragGradient.factor1
  59163. };
  59164. if (dragGradient.factor2 !== undefined) {
  59165. serializedGradient.factor2 = dragGradient.factor2;
  59166. }
  59167. serializationObject.dragGradients.push(serializedGradient);
  59168. }
  59169. }
  59170. var emitRateGradients = particleSystem.getEmitRateGradients();
  59171. if (emitRateGradients) {
  59172. serializationObject.emitRateGradients = [];
  59173. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  59174. var emitRateGradient = emitRateGradients_1[_h];
  59175. var serializedGradient = {
  59176. gradient: emitRateGradient.gradient,
  59177. factor1: emitRateGradient.factor1
  59178. };
  59179. if (emitRateGradient.factor2 !== undefined) {
  59180. serializedGradient.factor2 = emitRateGradient.factor2;
  59181. }
  59182. serializationObject.emitRateGradients.push(serializedGradient);
  59183. }
  59184. }
  59185. var startSizeGradients = particleSystem.getStartSizeGradients();
  59186. if (startSizeGradients) {
  59187. serializationObject.startSizeGradients = [];
  59188. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  59189. var startSizeGradient = startSizeGradients_1[_j];
  59190. var serializedGradient = {
  59191. gradient: startSizeGradient.gradient,
  59192. factor1: startSizeGradient.factor1
  59193. };
  59194. if (startSizeGradient.factor2 !== undefined) {
  59195. serializedGradient.factor2 = startSizeGradient.factor2;
  59196. }
  59197. serializationObject.startSizeGradients.push(serializedGradient);
  59198. }
  59199. }
  59200. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  59201. if (lifeTimeGradients) {
  59202. serializationObject.lifeTimeGradients = [];
  59203. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  59204. var lifeTimeGradient = lifeTimeGradients_1[_k];
  59205. var serializedGradient = {
  59206. gradient: lifeTimeGradient.gradient,
  59207. factor1: lifeTimeGradient.factor1
  59208. };
  59209. if (lifeTimeGradient.factor2 !== undefined) {
  59210. serializedGradient.factor2 = lifeTimeGradient.factor2;
  59211. }
  59212. serializationObject.lifeTimeGradients.push(serializedGradient);
  59213. }
  59214. }
  59215. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  59216. if (limitVelocityGradients) {
  59217. serializationObject.limitVelocityGradients = [];
  59218. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  59219. var limitVelocityGradient = limitVelocityGradients_1[_l];
  59220. var serializedGradient = {
  59221. gradient: limitVelocityGradient.gradient,
  59222. factor1: limitVelocityGradient.factor1
  59223. };
  59224. if (limitVelocityGradient.factor2 !== undefined) {
  59225. serializedGradient.factor2 = limitVelocityGradient.factor2;
  59226. }
  59227. serializationObject.limitVelocityGradients.push(serializedGradient);
  59228. }
  59229. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  59230. }
  59231. if (particleSystem.noiseTexture) {
  59232. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  59233. }
  59234. };
  59235. /** @hidden */
  59236. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  59237. // Texture
  59238. if (parsedParticleSystem.textureName) {
  59239. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  59240. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  59241. }
  59242. // Emitter
  59243. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  59244. particleSystem.emitter = BABYLON.Vector3.Zero();
  59245. }
  59246. else if (parsedParticleSystem.emitterId) {
  59247. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  59248. }
  59249. else {
  59250. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  59251. }
  59252. // Misc.
  59253. if (parsedParticleSystem.renderingGroupId !== undefined) {
  59254. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  59255. }
  59256. if (parsedParticleSystem.isBillboardBased !== undefined) {
  59257. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  59258. }
  59259. if (parsedParticleSystem.billboardMode !== undefined) {
  59260. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  59261. }
  59262. // Animations
  59263. if (parsedParticleSystem.animations) {
  59264. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  59265. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  59266. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59267. }
  59268. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  59269. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  59270. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  59271. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  59272. }
  59273. if (parsedParticleSystem.autoAnimate) {
  59274. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  59275. }
  59276. // Particle system
  59277. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  59278. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  59279. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  59280. particleSystem.minSize = parsedParticleSystem.minSize;
  59281. particleSystem.maxSize = parsedParticleSystem.maxSize;
  59282. if (parsedParticleSystem.minScaleX) {
  59283. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  59284. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  59285. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  59286. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  59287. }
  59288. if (parsedParticleSystem.preWarmCycles !== undefined) {
  59289. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  59290. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  59291. }
  59292. if (parsedParticleSystem.minInitialRotation !== undefined) {
  59293. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  59294. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  59295. }
  59296. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  59297. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  59298. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  59299. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  59300. particleSystem.emitRate = parsedParticleSystem.emitRate;
  59301. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  59302. if (parsedParticleSystem.noiseStrength) {
  59303. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  59304. }
  59305. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  59306. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  59307. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  59308. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  59309. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  59310. particleSystem.blendMode = parsedParticleSystem.blendMode;
  59311. if (parsedParticleSystem.colorGradients) {
  59312. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  59313. var colorGradient = _a[_i];
  59314. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  59315. }
  59316. }
  59317. if (parsedParticleSystem.rampGradients) {
  59318. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  59319. var rampGradient = _c[_b];
  59320. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  59321. }
  59322. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  59323. }
  59324. if (parsedParticleSystem.colorRemapGradients) {
  59325. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  59326. var colorRemapGradient = _e[_d];
  59327. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  59328. }
  59329. }
  59330. if (parsedParticleSystem.alphaRemapGradients) {
  59331. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  59332. var alphaRemapGradient = _g[_f];
  59333. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  59334. }
  59335. }
  59336. if (parsedParticleSystem.sizeGradients) {
  59337. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  59338. var sizeGradient = _j[_h];
  59339. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59340. }
  59341. }
  59342. if (parsedParticleSystem.sizeGradients) {
  59343. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  59344. var sizeGradient = _l[_k];
  59345. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59346. }
  59347. }
  59348. if (parsedParticleSystem.angularSpeedGradients) {
  59349. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  59350. var angularSpeedGradient = _o[_m];
  59351. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  59352. }
  59353. }
  59354. if (parsedParticleSystem.velocityGradients) {
  59355. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  59356. var velocityGradient = _q[_p];
  59357. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  59358. }
  59359. }
  59360. if (parsedParticleSystem.dragGradients) {
  59361. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  59362. var dragGradient = _s[_r];
  59363. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  59364. }
  59365. }
  59366. if (parsedParticleSystem.emitRateGradients) {
  59367. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  59368. var emitRateGradient = _u[_t];
  59369. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  59370. }
  59371. }
  59372. if (parsedParticleSystem.startSizeGradients) {
  59373. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  59374. var startSizeGradient = _w[_v];
  59375. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  59376. }
  59377. }
  59378. if (parsedParticleSystem.lifeTimeGradients) {
  59379. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  59380. var lifeTimeGradient = _y[_x];
  59381. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  59382. }
  59383. }
  59384. if (parsedParticleSystem.limitVelocityGradients) {
  59385. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  59386. var limitVelocityGradient = _0[_z];
  59387. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  59388. }
  59389. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  59390. }
  59391. if (parsedParticleSystem.noiseTexture) {
  59392. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  59393. }
  59394. // Emitter
  59395. var emitterType;
  59396. if (parsedParticleSystem.particleEmitterType) {
  59397. switch (parsedParticleSystem.particleEmitterType.type) {
  59398. case "SphereParticleEmitter":
  59399. emitterType = new BABYLON.SphereParticleEmitter();
  59400. break;
  59401. case "SphereDirectedParticleEmitter":
  59402. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  59403. break;
  59404. case "ConeEmitter":
  59405. case "ConeParticleEmitter":
  59406. emitterType = new BABYLON.ConeParticleEmitter();
  59407. break;
  59408. case "CylinderParticleEmitter":
  59409. emitterType = new BABYLON.CylinderParticleEmitter();
  59410. break;
  59411. case "HemisphericParticleEmitter":
  59412. emitterType = new BABYLON.HemisphericParticleEmitter();
  59413. break;
  59414. case "BoxEmitter":
  59415. case "BoxParticleEmitter":
  59416. default:
  59417. emitterType = new BABYLON.BoxParticleEmitter();
  59418. break;
  59419. }
  59420. emitterType.parse(parsedParticleSystem.particleEmitterType);
  59421. }
  59422. else {
  59423. emitterType = new BABYLON.BoxParticleEmitter();
  59424. emitterType.parse(parsedParticleSystem);
  59425. }
  59426. particleSystem.particleEmitterType = emitterType;
  59427. // Animation sheet
  59428. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  59429. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  59430. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  59431. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  59432. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  59433. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  59434. };
  59435. /**
  59436. * Parses a JSON object to create a particle system.
  59437. * @param parsedParticleSystem The JSON object to parse
  59438. * @param scene The scene to create the particle system in
  59439. * @param rootUrl The root url to use to load external dependencies like texture
  59440. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  59441. * @returns the Parsed particle system
  59442. */
  59443. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  59444. if (doNotStart === void 0) { doNotStart = false; }
  59445. var name = parsedParticleSystem.name;
  59446. var custom = null;
  59447. var program = null;
  59448. if (parsedParticleSystem.customShader) {
  59449. program = parsedParticleSystem.customShader;
  59450. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59451. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59452. }
  59453. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  59454. particleSystem.customShader = program;
  59455. if (parsedParticleSystem.id) {
  59456. particleSystem.id = parsedParticleSystem.id;
  59457. }
  59458. // SubEmitters
  59459. if (parsedParticleSystem.subEmitters) {
  59460. particleSystem.subEmitters = [];
  59461. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  59462. var cell = _a[_i];
  59463. var cellArray = [];
  59464. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  59465. var sub = cell_1[_b];
  59466. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  59467. }
  59468. particleSystem.subEmitters.push(cellArray);
  59469. }
  59470. }
  59471. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  59472. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  59473. // Auto start
  59474. if (parsedParticleSystem.preventAutoStart) {
  59475. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  59476. }
  59477. if (!doNotStart && !particleSystem.preventAutoStart) {
  59478. particleSystem.start();
  59479. }
  59480. return particleSystem;
  59481. };
  59482. /**
  59483. * Billboard mode will only apply to Y axis
  59484. */
  59485. ParticleSystem.BILLBOARDMODE_Y = 2;
  59486. /**
  59487. * Billboard mode will apply to all axes
  59488. */
  59489. ParticleSystem.BILLBOARDMODE_ALL = 7;
  59490. /**
  59491. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  59492. */
  59493. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  59494. return ParticleSystem;
  59495. }(BABYLON.BaseParticleSystem));
  59496. BABYLON.ParticleSystem = ParticleSystem;
  59497. })(BABYLON || (BABYLON = {}));
  59498. //# sourceMappingURL=babylon.particleSystem.js.map
  59499. var BABYLON;
  59500. (function (BABYLON) {
  59501. /**
  59502. * Particle emitter emitting particles from the inside of a box.
  59503. * It emits the particles randomly between 2 given directions.
  59504. */
  59505. var BoxParticleEmitter = /** @class */ (function () {
  59506. /**
  59507. * Creates a new instance BoxParticleEmitter
  59508. */
  59509. function BoxParticleEmitter() {
  59510. /**
  59511. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59512. */
  59513. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59514. /**
  59515. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59516. */
  59517. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59518. /**
  59519. * 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.
  59520. */
  59521. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  59522. /**
  59523. * 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.
  59524. */
  59525. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  59526. }
  59527. /**
  59528. * Called by the particle System when the direction is computed for the created particle.
  59529. * @param worldMatrix is the world matrix of the particle system
  59530. * @param directionToUpdate is the direction vector to update with the result
  59531. * @param particle is the particle we are computed the direction for
  59532. */
  59533. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59534. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59535. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59536. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59537. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59538. };
  59539. /**
  59540. * Called by the particle System when the position is computed for the created particle.
  59541. * @param worldMatrix is the world matrix of the particle system
  59542. * @param positionToUpdate is the position vector to update with the result
  59543. * @param particle is the particle we are computed the position for
  59544. */
  59545. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59546. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  59547. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  59548. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  59549. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59550. };
  59551. /**
  59552. * Clones the current emitter and returns a copy of it
  59553. * @returns the new emitter
  59554. */
  59555. BoxParticleEmitter.prototype.clone = function () {
  59556. var newOne = new BoxParticleEmitter();
  59557. BABYLON.Tools.DeepCopy(this, newOne);
  59558. return newOne;
  59559. };
  59560. /**
  59561. * Called by the GPUParticleSystem to setup the update shader
  59562. * @param effect defines the update shader
  59563. */
  59564. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  59565. effect.setVector3("direction1", this.direction1);
  59566. effect.setVector3("direction2", this.direction2);
  59567. effect.setVector3("minEmitBox", this.minEmitBox);
  59568. effect.setVector3("maxEmitBox", this.maxEmitBox);
  59569. };
  59570. /**
  59571. * Returns a string to use to update the GPU particles update shader
  59572. * @returns a string containng the defines string
  59573. */
  59574. BoxParticleEmitter.prototype.getEffectDefines = function () {
  59575. return "#define BOXEMITTER";
  59576. };
  59577. /**
  59578. * Returns the string "BoxParticleEmitter"
  59579. * @returns a string containing the class name
  59580. */
  59581. BoxParticleEmitter.prototype.getClassName = function () {
  59582. return "BoxParticleEmitter";
  59583. };
  59584. /**
  59585. * Serializes the particle system to a JSON object.
  59586. * @returns the JSON object
  59587. */
  59588. BoxParticleEmitter.prototype.serialize = function () {
  59589. var serializationObject = {};
  59590. serializationObject.type = this.getClassName();
  59591. serializationObject.direction1 = this.direction1.asArray();
  59592. serializationObject.direction2 = this.direction2.asArray();
  59593. serializationObject.minEmitBox = this.minEmitBox.asArray();
  59594. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  59595. return serializationObject;
  59596. };
  59597. /**
  59598. * Parse properties from a JSON object
  59599. * @param serializationObject defines the JSON object
  59600. */
  59601. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  59602. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59603. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59604. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  59605. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  59606. };
  59607. return BoxParticleEmitter;
  59608. }());
  59609. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  59610. })(BABYLON || (BABYLON = {}));
  59611. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  59612. var BABYLON;
  59613. (function (BABYLON) {
  59614. /**
  59615. * Particle emitter emitting particles from the inside of a cylinder.
  59616. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  59617. */
  59618. var CylinderParticleEmitter = /** @class */ (function () {
  59619. /**
  59620. * Creates a new instance CylinderParticleEmitter
  59621. * @param radius the radius of the emission cylinder (1 by default)
  59622. * @param height the height of the emission cylinder (1 by default)
  59623. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59624. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59625. */
  59626. function CylinderParticleEmitter(
  59627. /**
  59628. * The radius of the emission cylinder.
  59629. */
  59630. radius,
  59631. /**
  59632. * The height of the emission cylinder.
  59633. */
  59634. height,
  59635. /**
  59636. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59637. */
  59638. radiusRange,
  59639. /**
  59640. * How much to randomize the particle direction [0-1].
  59641. */
  59642. directionRandomizer) {
  59643. if (radius === void 0) { radius = 1; }
  59644. if (height === void 0) { height = 1; }
  59645. if (radiusRange === void 0) { radiusRange = 1; }
  59646. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59647. this.radius = radius;
  59648. this.height = height;
  59649. this.radiusRange = radiusRange;
  59650. this.directionRandomizer = directionRandomizer;
  59651. }
  59652. /**
  59653. * Called by the particle System when the direction is computed for the created particle.
  59654. * @param worldMatrix is the world matrix of the particle system
  59655. * @param directionToUpdate is the direction vector to update with the result
  59656. * @param particle is the particle we are computed the direction for
  59657. */
  59658. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59659. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59660. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  59661. var angle = Math.atan2(direction.x, direction.z);
  59662. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  59663. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  59664. direction.x = Math.sin(angle);
  59665. direction.z = Math.cos(angle);
  59666. direction.normalize();
  59667. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59668. };
  59669. /**
  59670. * Called by the particle System when the position is computed for the created particle.
  59671. * @param worldMatrix is the world matrix of the particle system
  59672. * @param positionToUpdate is the position vector to update with the result
  59673. * @param particle is the particle we are computed the position for
  59674. */
  59675. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59676. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  59677. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59678. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  59679. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  59680. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  59681. var xPos = positionRadius * Math.cos(angle);
  59682. var zPos = positionRadius * Math.sin(angle);
  59683. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  59684. };
  59685. /**
  59686. * Clones the current emitter and returns a copy of it
  59687. * @returns the new emitter
  59688. */
  59689. CylinderParticleEmitter.prototype.clone = function () {
  59690. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  59691. BABYLON.Tools.DeepCopy(this, newOne);
  59692. return newOne;
  59693. };
  59694. /**
  59695. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59696. * @param effect defines the update shader
  59697. */
  59698. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  59699. effect.setFloat("radius", this.radius);
  59700. effect.setFloat("height", this.height);
  59701. effect.setFloat("radiusRange", this.radiusRange);
  59702. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59703. };
  59704. /**
  59705. * Returns a string to use to update the GPU particles update shader
  59706. * @returns a string containng the defines string
  59707. */
  59708. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  59709. return "#define CYLINDEREMITTER";
  59710. };
  59711. /**
  59712. * Returns the string "CylinderParticleEmitter"
  59713. * @returns a string containing the class name
  59714. */
  59715. CylinderParticleEmitter.prototype.getClassName = function () {
  59716. return "CylinderParticleEmitter";
  59717. };
  59718. /**
  59719. * Serializes the particle system to a JSON object.
  59720. * @returns the JSON object
  59721. */
  59722. CylinderParticleEmitter.prototype.serialize = function () {
  59723. var serializationObject = {};
  59724. serializationObject.type = this.getClassName();
  59725. serializationObject.radius = this.radius;
  59726. serializationObject.height = this.height;
  59727. serializationObject.radiusRange = this.radiusRange;
  59728. serializationObject.directionRandomizer = this.directionRandomizer;
  59729. return serializationObject;
  59730. };
  59731. /**
  59732. * Parse properties from a JSON object
  59733. * @param serializationObject defines the JSON object
  59734. */
  59735. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  59736. this.radius = serializationObject.radius;
  59737. this.height = serializationObject.height;
  59738. this.radiusRange = serializationObject.radiusRange;
  59739. this.directionRandomizer = serializationObject.directionRandomizer;
  59740. };
  59741. return CylinderParticleEmitter;
  59742. }());
  59743. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  59744. /**
  59745. * Particle emitter emitting particles from the inside of a cylinder.
  59746. * It emits the particles randomly between two vectors.
  59747. */
  59748. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  59749. __extends(CylinderDirectedParticleEmitter, _super);
  59750. /**
  59751. * Creates a new instance CylinderDirectedParticleEmitter
  59752. * @param radius the radius of the emission cylinder (1 by default)
  59753. * @param height the height of the emission cylinder (1 by default)
  59754. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59755. * @param direction1 the min limit of the emission direction (up vector by default)
  59756. * @param direction2 the max limit of the emission direction (up vector by default)
  59757. */
  59758. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  59759. /**
  59760. * The min limit of the emission direction.
  59761. */
  59762. direction1,
  59763. /**
  59764. * The max limit of the emission direction.
  59765. */
  59766. direction2) {
  59767. if (radius === void 0) { radius = 1; }
  59768. if (height === void 0) { height = 1; }
  59769. if (radiusRange === void 0) { radiusRange = 1; }
  59770. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  59771. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  59772. var _this = _super.call(this, radius, height, radiusRange) || this;
  59773. _this.direction1 = direction1;
  59774. _this.direction2 = direction2;
  59775. return _this;
  59776. }
  59777. /**
  59778. * Called by the particle System when the direction is computed for the created particle.
  59779. * @param worldMatrix is the world matrix of the particle system
  59780. * @param directionToUpdate is the direction vector to update with the result
  59781. * @param particle is the particle we are computed the direction for
  59782. */
  59783. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59784. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59785. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59786. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59787. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59788. };
  59789. /**
  59790. * Clones the current emitter and returns a copy of it
  59791. * @returns the new emitter
  59792. */
  59793. CylinderDirectedParticleEmitter.prototype.clone = function () {
  59794. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  59795. BABYLON.Tools.DeepCopy(this, newOne);
  59796. return newOne;
  59797. };
  59798. /**
  59799. * Called by the GPUParticleSystem to setup the update shader
  59800. * @param effect defines the update shader
  59801. */
  59802. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  59803. effect.setFloat("radius", this.radius);
  59804. effect.setFloat("height", this.height);
  59805. effect.setFloat("radiusRange", this.radiusRange);
  59806. effect.setVector3("direction1", this.direction1);
  59807. effect.setVector3("direction2", this.direction2);
  59808. };
  59809. /**
  59810. * Returns a string to use to update the GPU particles update shader
  59811. * @returns a string containng the defines string
  59812. */
  59813. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  59814. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  59815. };
  59816. /**
  59817. * Returns the string "CylinderDirectedParticleEmitter"
  59818. * @returns a string containing the class name
  59819. */
  59820. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  59821. return "CylinderDirectedParticleEmitter";
  59822. };
  59823. /**
  59824. * Serializes the particle system to a JSON object.
  59825. * @returns the JSON object
  59826. */
  59827. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  59828. var serializationObject = _super.prototype.serialize.call(this);
  59829. serializationObject.direction1 = this.direction1.asArray();
  59830. serializationObject.direction2 = this.direction2.asArray();
  59831. return serializationObject;
  59832. };
  59833. /**
  59834. * Parse properties from a JSON object
  59835. * @param serializationObject defines the JSON object
  59836. */
  59837. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  59838. _super.prototype.parse.call(this, serializationObject);
  59839. this.direction1.copyFrom(serializationObject.direction1);
  59840. this.direction2.copyFrom(serializationObject.direction2);
  59841. };
  59842. return CylinderDirectedParticleEmitter;
  59843. }(CylinderParticleEmitter));
  59844. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  59845. })(BABYLON || (BABYLON = {}));
  59846. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  59847. var BABYLON;
  59848. (function (BABYLON) {
  59849. /**
  59850. * Particle emitter emitting particles from the inside of a cone.
  59851. * It emits the particles alongside the cone volume from the base to the particle.
  59852. * The emission direction might be randomized.
  59853. */
  59854. var ConeParticleEmitter = /** @class */ (function () {
  59855. /**
  59856. * Creates a new instance ConeParticleEmitter
  59857. * @param radius the radius of the emission cone (1 by default)
  59858. * @param angles the cone base angle (PI by default)
  59859. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  59860. */
  59861. function ConeParticleEmitter(radius, angle,
  59862. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  59863. directionRandomizer) {
  59864. if (radius === void 0) { radius = 1; }
  59865. if (angle === void 0) { angle = Math.PI; }
  59866. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59867. this.directionRandomizer = directionRandomizer;
  59868. /**
  59869. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  59870. */
  59871. this.radiusRange = 1;
  59872. /**
  59873. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  59874. */
  59875. this.heightRange = 1;
  59876. /**
  59877. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  59878. */
  59879. this.emitFromSpawnPointOnly = false;
  59880. this.angle = angle;
  59881. this.radius = radius;
  59882. }
  59883. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  59884. /**
  59885. * Gets or sets the radius of the emission cone
  59886. */
  59887. get: function () {
  59888. return this._radius;
  59889. },
  59890. set: function (value) {
  59891. this._radius = value;
  59892. this._buildHeight();
  59893. },
  59894. enumerable: true,
  59895. configurable: true
  59896. });
  59897. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  59898. /**
  59899. * Gets or sets the angle of the emission cone
  59900. */
  59901. get: function () {
  59902. return this._angle;
  59903. },
  59904. set: function (value) {
  59905. this._angle = value;
  59906. this._buildHeight();
  59907. },
  59908. enumerable: true,
  59909. configurable: true
  59910. });
  59911. ConeParticleEmitter.prototype._buildHeight = function () {
  59912. if (this._angle !== 0) {
  59913. this._height = this._radius / Math.tan(this._angle / 2);
  59914. }
  59915. else {
  59916. this._height = 1;
  59917. }
  59918. };
  59919. /**
  59920. * Called by the particle System when the direction is computed for the created particle.
  59921. * @param worldMatrix is the world matrix of the particle system
  59922. * @param directionToUpdate is the direction vector to update with the result
  59923. * @param particle is the particle we are computed the direction for
  59924. */
  59925. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59926. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  59927. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  59928. }
  59929. else {
  59930. // measure the direction Vector from the emitter to the particle.
  59931. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59932. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59933. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59934. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59935. direction.x += randX;
  59936. direction.y += randY;
  59937. direction.z += randZ;
  59938. direction.normalize();
  59939. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59940. }
  59941. };
  59942. /**
  59943. * Called by the particle System when the position is computed for the created particle.
  59944. * @param worldMatrix is the world matrix of the particle system
  59945. * @param positionToUpdate is the position vector to update with the result
  59946. * @param particle is the particle we are computed the position for
  59947. */
  59948. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59949. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  59950. var h;
  59951. if (!this.emitFromSpawnPointOnly) {
  59952. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  59953. // Better distribution in a cone at normal angles.
  59954. h = 1 - h * h;
  59955. }
  59956. else {
  59957. h = 0.0001;
  59958. }
  59959. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  59960. radius = radius * h;
  59961. var randX = radius * Math.sin(s);
  59962. var randZ = radius * Math.cos(s);
  59963. var randY = h * this._height;
  59964. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59965. };
  59966. /**
  59967. * Clones the current emitter and returns a copy of it
  59968. * @returns the new emitter
  59969. */
  59970. ConeParticleEmitter.prototype.clone = function () {
  59971. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  59972. BABYLON.Tools.DeepCopy(this, newOne);
  59973. return newOne;
  59974. };
  59975. /**
  59976. * Called by the GPUParticleSystem to setup the update shader
  59977. * @param effect defines the update shader
  59978. */
  59979. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  59980. effect.setFloat2("radius", this._radius, this.radiusRange);
  59981. effect.setFloat("coneAngle", this._angle);
  59982. effect.setFloat2("height", this._height, this.heightRange);
  59983. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59984. };
  59985. /**
  59986. * Returns a string to use to update the GPU particles update shader
  59987. * @returns a string containng the defines string
  59988. */
  59989. ConeParticleEmitter.prototype.getEffectDefines = function () {
  59990. var defines = "#define CONEEMITTER";
  59991. if (this.emitFromSpawnPointOnly) {
  59992. defines += "\n#define CONEEMITTERSPAWNPOINT";
  59993. }
  59994. return defines;
  59995. };
  59996. /**
  59997. * Returns the string "ConeParticleEmitter"
  59998. * @returns a string containing the class name
  59999. */
  60000. ConeParticleEmitter.prototype.getClassName = function () {
  60001. return "ConeParticleEmitter";
  60002. };
  60003. /**
  60004. * Serializes the particle system to a JSON object.
  60005. * @returns the JSON object
  60006. */
  60007. ConeParticleEmitter.prototype.serialize = function () {
  60008. var serializationObject = {};
  60009. serializationObject.type = this.getClassName();
  60010. serializationObject.radius = this._radius;
  60011. serializationObject.angle = this._angle;
  60012. serializationObject.directionRandomizer = this.directionRandomizer;
  60013. return serializationObject;
  60014. };
  60015. /**
  60016. * Parse properties from a JSON object
  60017. * @param serializationObject defines the JSON object
  60018. */
  60019. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  60020. this.radius = serializationObject.radius;
  60021. this.angle = serializationObject.angle;
  60022. this.directionRandomizer = serializationObject.directionRandomizer;
  60023. };
  60024. return ConeParticleEmitter;
  60025. }());
  60026. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  60027. })(BABYLON || (BABYLON = {}));
  60028. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  60029. var BABYLON;
  60030. (function (BABYLON) {
  60031. /**
  60032. * Particle emitter emitting particles from the inside of a sphere.
  60033. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  60034. */
  60035. var SphereParticleEmitter = /** @class */ (function () {
  60036. /**
  60037. * Creates a new instance SphereParticleEmitter
  60038. * @param radius the radius of the emission sphere (1 by default)
  60039. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60040. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60041. */
  60042. function SphereParticleEmitter(
  60043. /**
  60044. * The radius of the emission sphere.
  60045. */
  60046. radius,
  60047. /**
  60048. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60049. */
  60050. radiusRange,
  60051. /**
  60052. * How much to randomize the particle direction [0-1].
  60053. */
  60054. directionRandomizer) {
  60055. if (radius === void 0) { radius = 1; }
  60056. if (radiusRange === void 0) { radiusRange = 1; }
  60057. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60058. this.radius = radius;
  60059. this.radiusRange = radiusRange;
  60060. this.directionRandomizer = directionRandomizer;
  60061. }
  60062. /**
  60063. * Called by the particle System when the direction is computed for the created particle.
  60064. * @param worldMatrix is the world matrix of the particle system
  60065. * @param directionToUpdate is the direction vector to update with the result
  60066. * @param particle is the particle we are computed the direction for
  60067. */
  60068. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60069. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60070. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60071. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60072. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60073. direction.x += randX;
  60074. direction.y += randY;
  60075. direction.z += randZ;
  60076. direction.normalize();
  60077. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60078. };
  60079. /**
  60080. * Called by the particle System when the position is computed for the created particle.
  60081. * @param worldMatrix is the world matrix of the particle system
  60082. * @param positionToUpdate is the position vector to update with the result
  60083. * @param particle is the particle we are computed the position for
  60084. */
  60085. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60086. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60087. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60088. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60089. var theta = Math.acos(2 * v - 1);
  60090. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60091. var randY = randRadius * Math.cos(theta);
  60092. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60093. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60094. };
  60095. /**
  60096. * Clones the current emitter and returns a copy of it
  60097. * @returns the new emitter
  60098. */
  60099. SphereParticleEmitter.prototype.clone = function () {
  60100. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  60101. BABYLON.Tools.DeepCopy(this, newOne);
  60102. return newOne;
  60103. };
  60104. /**
  60105. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60106. * @param effect defines the update shader
  60107. */
  60108. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  60109. effect.setFloat("radius", this.radius);
  60110. effect.setFloat("radiusRange", this.radiusRange);
  60111. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60112. };
  60113. /**
  60114. * Returns a string to use to update the GPU particles update shader
  60115. * @returns a string containng the defines string
  60116. */
  60117. SphereParticleEmitter.prototype.getEffectDefines = function () {
  60118. return "#define SPHEREEMITTER";
  60119. };
  60120. /**
  60121. * Returns the string "SphereParticleEmitter"
  60122. * @returns a string containing the class name
  60123. */
  60124. SphereParticleEmitter.prototype.getClassName = function () {
  60125. return "SphereParticleEmitter";
  60126. };
  60127. /**
  60128. * Serializes the particle system to a JSON object.
  60129. * @returns the JSON object
  60130. */
  60131. SphereParticleEmitter.prototype.serialize = function () {
  60132. var serializationObject = {};
  60133. serializationObject.type = this.getClassName();
  60134. serializationObject.radius = this.radius;
  60135. serializationObject.radiusRange = this.radiusRange;
  60136. serializationObject.directionRandomizer = this.directionRandomizer;
  60137. return serializationObject;
  60138. };
  60139. /**
  60140. * Parse properties from a JSON object
  60141. * @param serializationObject defines the JSON object
  60142. */
  60143. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  60144. this.radius = serializationObject.radius;
  60145. this.radiusRange = serializationObject.radiusRange;
  60146. this.directionRandomizer = serializationObject.directionRandomizer;
  60147. };
  60148. return SphereParticleEmitter;
  60149. }());
  60150. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  60151. /**
  60152. * Particle emitter emitting particles from the inside of a sphere.
  60153. * It emits the particles randomly between two vectors.
  60154. */
  60155. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  60156. __extends(SphereDirectedParticleEmitter, _super);
  60157. /**
  60158. * Creates a new instance SphereDirectedParticleEmitter
  60159. * @param radius the radius of the emission sphere (1 by default)
  60160. * @param direction1 the min limit of the emission direction (up vector by default)
  60161. * @param direction2 the max limit of the emission direction (up vector by default)
  60162. */
  60163. function SphereDirectedParticleEmitter(radius,
  60164. /**
  60165. * The min limit of the emission direction.
  60166. */
  60167. direction1,
  60168. /**
  60169. * The max limit of the emission direction.
  60170. */
  60171. direction2) {
  60172. if (radius === void 0) { radius = 1; }
  60173. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60174. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60175. var _this = _super.call(this, radius) || this;
  60176. _this.direction1 = direction1;
  60177. _this.direction2 = direction2;
  60178. return _this;
  60179. }
  60180. /**
  60181. * Called by the particle System when the direction is computed for the created particle.
  60182. * @param worldMatrix is the world matrix of the particle system
  60183. * @param directionToUpdate is the direction vector to update with the result
  60184. * @param particle is the particle we are computed the direction for
  60185. */
  60186. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60187. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60188. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60189. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60190. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60191. };
  60192. /**
  60193. * Clones the current emitter and returns a copy of it
  60194. * @returns the new emitter
  60195. */
  60196. SphereDirectedParticleEmitter.prototype.clone = function () {
  60197. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  60198. BABYLON.Tools.DeepCopy(this, newOne);
  60199. return newOne;
  60200. };
  60201. /**
  60202. * Called by the GPUParticleSystem to setup the update shader
  60203. * @param effect defines the update shader
  60204. */
  60205. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60206. effect.setFloat("radius", this.radius);
  60207. effect.setFloat("radiusRange", this.radiusRange);
  60208. effect.setVector3("direction1", this.direction1);
  60209. effect.setVector3("direction2", this.direction2);
  60210. };
  60211. /**
  60212. * Returns a string to use to update the GPU particles update shader
  60213. * @returns a string containng the defines string
  60214. */
  60215. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60216. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  60217. };
  60218. /**
  60219. * Returns the string "SphereDirectedParticleEmitter"
  60220. * @returns a string containing the class name
  60221. */
  60222. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  60223. return "SphereDirectedParticleEmitter";
  60224. };
  60225. /**
  60226. * Serializes the particle system to a JSON object.
  60227. * @returns the JSON object
  60228. */
  60229. SphereDirectedParticleEmitter.prototype.serialize = function () {
  60230. var serializationObject = _super.prototype.serialize.call(this);
  60231. serializationObject.direction1 = this.direction1.asArray();
  60232. serializationObject.direction2 = this.direction2.asArray();
  60233. return serializationObject;
  60234. };
  60235. /**
  60236. * Parse properties from a JSON object
  60237. * @param serializationObject defines the JSON object
  60238. */
  60239. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60240. _super.prototype.parse.call(this, serializationObject);
  60241. this.direction1.copyFrom(serializationObject.direction1);
  60242. this.direction2.copyFrom(serializationObject.direction2);
  60243. };
  60244. return SphereDirectedParticleEmitter;
  60245. }(SphereParticleEmitter));
  60246. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  60247. })(BABYLON || (BABYLON = {}));
  60248. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  60249. var BABYLON;
  60250. (function (BABYLON) {
  60251. /**
  60252. * Particle emitter emitting particles from the inside of a hemisphere.
  60253. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  60254. */
  60255. var HemisphericParticleEmitter = /** @class */ (function () {
  60256. /**
  60257. * Creates a new instance HemisphericParticleEmitter
  60258. * @param radius the radius of the emission hemisphere (1 by default)
  60259. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60260. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60261. */
  60262. function HemisphericParticleEmitter(
  60263. /**
  60264. * The radius of the emission hemisphere.
  60265. */
  60266. radius,
  60267. /**
  60268. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60269. */
  60270. radiusRange,
  60271. /**
  60272. * How much to randomize the particle direction [0-1].
  60273. */
  60274. directionRandomizer) {
  60275. if (radius === void 0) { radius = 1; }
  60276. if (radiusRange === void 0) { radiusRange = 1; }
  60277. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60278. this.radius = radius;
  60279. this.radiusRange = radiusRange;
  60280. this.directionRandomizer = directionRandomizer;
  60281. }
  60282. /**
  60283. * Called by the particle System when the direction is computed for the created particle.
  60284. * @param worldMatrix is the world matrix of the particle system
  60285. * @param directionToUpdate is the direction vector to update with the result
  60286. * @param particle is the particle we are computed the direction for
  60287. */
  60288. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60289. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60290. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60291. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60292. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60293. direction.x += randX;
  60294. direction.y += randY;
  60295. direction.z += randZ;
  60296. direction.normalize();
  60297. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60298. };
  60299. /**
  60300. * Called by the particle System when the position is computed for the created particle.
  60301. * @param worldMatrix is the world matrix of the particle system
  60302. * @param positionToUpdate is the position vector to update with the result
  60303. * @param particle is the particle we are computed the position for
  60304. */
  60305. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60306. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60307. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60308. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60309. var theta = Math.acos(2 * v - 1);
  60310. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60311. var randY = randRadius * Math.cos(theta);
  60312. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60313. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  60314. };
  60315. /**
  60316. * Clones the current emitter and returns a copy of it
  60317. * @returns the new emitter
  60318. */
  60319. HemisphericParticleEmitter.prototype.clone = function () {
  60320. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  60321. BABYLON.Tools.DeepCopy(this, newOne);
  60322. return newOne;
  60323. };
  60324. /**
  60325. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60326. * @param effect defines the update shader
  60327. */
  60328. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  60329. effect.setFloat("radius", this.radius);
  60330. effect.setFloat("radiusRange", this.radiusRange);
  60331. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60332. };
  60333. /**
  60334. * Returns a string to use to update the GPU particles update shader
  60335. * @returns a string containng the defines string
  60336. */
  60337. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  60338. return "#define HEMISPHERICEMITTER";
  60339. };
  60340. /**
  60341. * Returns the string "HemisphericParticleEmitter"
  60342. * @returns a string containing the class name
  60343. */
  60344. HemisphericParticleEmitter.prototype.getClassName = function () {
  60345. return "HemisphericParticleEmitter";
  60346. };
  60347. /**
  60348. * Serializes the particle system to a JSON object.
  60349. * @returns the JSON object
  60350. */
  60351. HemisphericParticleEmitter.prototype.serialize = function () {
  60352. var serializationObject = {};
  60353. serializationObject.type = this.getClassName();
  60354. serializationObject.radius = this.radius;
  60355. serializationObject.radiusRange = this.radiusRange;
  60356. serializationObject.directionRandomizer = this.directionRandomizer;
  60357. return serializationObject;
  60358. };
  60359. /**
  60360. * Parse properties from a JSON object
  60361. * @param serializationObject defines the JSON object
  60362. */
  60363. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  60364. this.radius = serializationObject.radius;
  60365. this.radiusRange = serializationObject.radiusRange;
  60366. this.directionRandomizer = serializationObject.directionRandomizer;
  60367. };
  60368. return HemisphericParticleEmitter;
  60369. }());
  60370. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  60371. })(BABYLON || (BABYLON = {}));
  60372. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  60373. var BABYLON;
  60374. (function (BABYLON) {
  60375. /**
  60376. * Particle emitter emitting particles from a point.
  60377. * It emits the particles randomly between 2 given directions.
  60378. */
  60379. var PointParticleEmitter = /** @class */ (function () {
  60380. /**
  60381. * Creates a new instance PointParticleEmitter
  60382. */
  60383. function PointParticleEmitter() {
  60384. /**
  60385. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60386. */
  60387. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60388. /**
  60389. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60390. */
  60391. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60392. }
  60393. /**
  60394. * Called by the particle System when the direction is computed for the created particle.
  60395. * @param worldMatrix is the world matrix of the particle system
  60396. * @param directionToUpdate is the direction vector to update with the result
  60397. * @param particle is the particle we are computed the direction for
  60398. */
  60399. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60400. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60401. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60402. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60403. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60404. };
  60405. /**
  60406. * Called by the particle System when the position is computed for the created particle.
  60407. * @param worldMatrix is the world matrix of the particle system
  60408. * @param positionToUpdate is the position vector to update with the result
  60409. * @param particle is the particle we are computed the position for
  60410. */
  60411. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60412. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  60413. };
  60414. /**
  60415. * Clones the current emitter and returns a copy of it
  60416. * @returns the new emitter
  60417. */
  60418. PointParticleEmitter.prototype.clone = function () {
  60419. var newOne = new PointParticleEmitter();
  60420. BABYLON.Tools.DeepCopy(this, newOne);
  60421. return newOne;
  60422. };
  60423. /**
  60424. * Called by the GPUParticleSystem to setup the update shader
  60425. * @param effect defines the update shader
  60426. */
  60427. PointParticleEmitter.prototype.applyToShader = function (effect) {
  60428. effect.setVector3("direction1", this.direction1);
  60429. effect.setVector3("direction2", this.direction2);
  60430. };
  60431. /**
  60432. * Returns a string to use to update the GPU particles update shader
  60433. * @returns a string containng the defines string
  60434. */
  60435. PointParticleEmitter.prototype.getEffectDefines = function () {
  60436. return "#define POINTEMITTER";
  60437. };
  60438. /**
  60439. * Returns the string "PointParticleEmitter"
  60440. * @returns a string containing the class name
  60441. */
  60442. PointParticleEmitter.prototype.getClassName = function () {
  60443. return "PointParticleEmitter";
  60444. };
  60445. /**
  60446. * Serializes the particle system to a JSON object.
  60447. * @returns the JSON object
  60448. */
  60449. PointParticleEmitter.prototype.serialize = function () {
  60450. var serializationObject = {};
  60451. serializationObject.type = this.getClassName();
  60452. serializationObject.direction1 = this.direction1.asArray();
  60453. serializationObject.direction2 = this.direction2.asArray();
  60454. return serializationObject;
  60455. };
  60456. /**
  60457. * Parse properties from a JSON object
  60458. * @param serializationObject defines the JSON object
  60459. */
  60460. PointParticleEmitter.prototype.parse = function (serializationObject) {
  60461. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60462. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60463. };
  60464. return PointParticleEmitter;
  60465. }());
  60466. BABYLON.PointParticleEmitter = PointParticleEmitter;
  60467. })(BABYLON || (BABYLON = {}));
  60468. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  60469. var BABYLON;
  60470. (function (BABYLON) {
  60471. // Adds the parsers to the scene parsers.
  60472. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  60473. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  60474. if (!individualParser) {
  60475. return;
  60476. }
  60477. // Particles Systems
  60478. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60479. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60480. var parsedParticleSystem = parsedData.particleSystems[index];
  60481. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  60482. }
  60483. }
  60484. });
  60485. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  60486. if (parsedParticleSystem.activeParticleCount) {
  60487. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60488. return ps;
  60489. }
  60490. else {
  60491. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60492. return ps;
  60493. }
  60494. });
  60495. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  60496. if (uniformsNames === void 0) { uniformsNames = []; }
  60497. if (samplers === void 0) { samplers = []; }
  60498. if (defines === void 0) { defines = ""; }
  60499. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  60500. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  60501. if (defines.indexOf(" BILLBOARD") === -1) {
  60502. defines += "\n#define BILLBOARD\n";
  60503. }
  60504. if (samplers.indexOf("diffuseSampler") === -1) {
  60505. samplers.push("diffuseSampler");
  60506. }
  60507. return this.createEffect({
  60508. vertex: "particles",
  60509. fragmentElement: fragmentName
  60510. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  60511. };
  60512. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  60513. var results = new Array();
  60514. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60515. var particleSystem = this.getScene().particleSystems[index];
  60516. if (particleSystem.emitter === this) {
  60517. results.push(particleSystem);
  60518. }
  60519. }
  60520. return results;
  60521. };
  60522. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  60523. var results = new Array();
  60524. var descendants = this.getDescendants();
  60525. descendants.push(this);
  60526. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60527. var particleSystem = this.getScene().particleSystems[index];
  60528. var emitter = particleSystem.emitter;
  60529. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  60530. results.push(particleSystem);
  60531. }
  60532. }
  60533. return results;
  60534. };
  60535. })(BABYLON || (BABYLON = {}));
  60536. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  60537. var BABYLON;
  60538. (function (BABYLON) {
  60539. /**
  60540. * Type of sub emitter
  60541. */
  60542. var SubEmitterType;
  60543. (function (SubEmitterType) {
  60544. /**
  60545. * Attached to the particle over it's lifetime
  60546. */
  60547. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  60548. /**
  60549. * Created when the particle dies
  60550. */
  60551. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  60552. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  60553. /**
  60554. * Sub emitter class used to emit particles from an existing particle
  60555. */
  60556. var SubEmitter = /** @class */ (function () {
  60557. /**
  60558. * Creates a sub emitter
  60559. * @param particleSystem the particle system to be used by the sub emitter
  60560. */
  60561. function SubEmitter(
  60562. /**
  60563. * the particle system to be used by the sub emitter
  60564. */
  60565. particleSystem) {
  60566. this.particleSystem = particleSystem;
  60567. /**
  60568. * Type of the submitter (Default: END)
  60569. */
  60570. this.type = SubEmitterType.END;
  60571. /**
  60572. * 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)
  60573. * Note: This only is supported when using an emitter of type Mesh
  60574. */
  60575. this.inheritDirection = false;
  60576. /**
  60577. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  60578. */
  60579. this.inheritedVelocityAmount = 0;
  60580. }
  60581. /**
  60582. * Clones the sub emitter
  60583. * @returns the cloned sub emitter
  60584. */
  60585. SubEmitter.prototype.clone = function () {
  60586. // Clone particle system
  60587. var emitter = this.particleSystem.emitter;
  60588. if (!emitter) {
  60589. emitter = new BABYLON.Vector3();
  60590. }
  60591. else if (emitter instanceof BABYLON.Vector3) {
  60592. emitter = emitter.clone();
  60593. }
  60594. else if (emitter instanceof BABYLON.AbstractMesh) {
  60595. emitter = new BABYLON.Mesh("", emitter.getScene());
  60596. emitter.isVisible = false;
  60597. }
  60598. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  60599. // Clone properties
  60600. clone.type = this.type;
  60601. clone.inheritDirection = this.inheritDirection;
  60602. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60603. clone.particleSystem._disposeEmitterOnDispose = true;
  60604. clone.particleSystem.disposeOnStop = true;
  60605. return clone;
  60606. };
  60607. /**
  60608. * Serialize current object to a JSON object
  60609. * @returns the serialized object
  60610. */
  60611. SubEmitter.prototype.serialize = function () {
  60612. var serializationObject = {};
  60613. serializationObject.type = this.type;
  60614. serializationObject.inheritDirection = this.inheritDirection;
  60615. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60616. serializationObject.particleSystem = this.particleSystem.serialize();
  60617. return serializationObject;
  60618. };
  60619. /**
  60620. * Creates a new SubEmitter from a serialized JSON version
  60621. * @param serializationObject defines the JSON object to read from
  60622. * @param scene defines the hosting scene
  60623. * @param rootUrl defines the rootUrl for data loading
  60624. * @returns a new SubEmitter
  60625. */
  60626. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  60627. var system = serializationObject.particleSystem;
  60628. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  60629. subEmitter.type = serializationObject.type;
  60630. subEmitter.inheritDirection = serializationObject.inheritDirection;
  60631. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  60632. subEmitter.particleSystem._isSubEmitter = true;
  60633. return subEmitter;
  60634. };
  60635. /** Release associated resources */
  60636. SubEmitter.prototype.dispose = function () {
  60637. this.particleSystem.dispose();
  60638. };
  60639. return SubEmitter;
  60640. }());
  60641. BABYLON.SubEmitter = SubEmitter;
  60642. })(BABYLON || (BABYLON = {}));
  60643. //# sourceMappingURL=babylon.subEmitter.js.map
  60644. var BABYLON;
  60645. (function (BABYLON) {
  60646. var ShaderMaterial = /** @class */ (function (_super) {
  60647. __extends(ShaderMaterial, _super);
  60648. function ShaderMaterial(name, scene, shaderPath, options) {
  60649. var _this = _super.call(this, name, scene) || this;
  60650. _this._textures = {};
  60651. _this._textureArrays = {};
  60652. _this._floats = {};
  60653. _this._ints = {};
  60654. _this._floatsArrays = {};
  60655. _this._colors3 = {};
  60656. _this._colors3Arrays = {};
  60657. _this._colors4 = {};
  60658. _this._vectors2 = {};
  60659. _this._vectors3 = {};
  60660. _this._vectors4 = {};
  60661. _this._matrices = {};
  60662. _this._matrices3x3 = {};
  60663. _this._matrices2x2 = {};
  60664. _this._vectors2Arrays = {};
  60665. _this._vectors3Arrays = {};
  60666. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  60667. _this._shaderPath = shaderPath;
  60668. options.needAlphaBlending = options.needAlphaBlending || false;
  60669. options.needAlphaTesting = options.needAlphaTesting || false;
  60670. options.attributes = options.attributes || ["position", "normal", "uv"];
  60671. options.uniforms = options.uniforms || ["worldViewProjection"];
  60672. options.uniformBuffers = options.uniformBuffers || [];
  60673. options.samplers = options.samplers || [];
  60674. options.defines = options.defines || [];
  60675. _this._options = options;
  60676. return _this;
  60677. }
  60678. ShaderMaterial.prototype.getClassName = function () {
  60679. return "ShaderMaterial";
  60680. };
  60681. ShaderMaterial.prototype.needAlphaBlending = function () {
  60682. return this._options.needAlphaBlending;
  60683. };
  60684. ShaderMaterial.prototype.needAlphaTesting = function () {
  60685. return this._options.needAlphaTesting;
  60686. };
  60687. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  60688. if (this._options.uniforms.indexOf(uniformName) === -1) {
  60689. this._options.uniforms.push(uniformName);
  60690. }
  60691. };
  60692. ShaderMaterial.prototype.setTexture = function (name, texture) {
  60693. if (this._options.samplers.indexOf(name) === -1) {
  60694. this._options.samplers.push(name);
  60695. }
  60696. this._textures[name] = texture;
  60697. return this;
  60698. };
  60699. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  60700. if (this._options.samplers.indexOf(name) === -1) {
  60701. this._options.samplers.push(name);
  60702. }
  60703. this._checkUniform(name);
  60704. this._textureArrays[name] = textures;
  60705. return this;
  60706. };
  60707. ShaderMaterial.prototype.setFloat = function (name, value) {
  60708. this._checkUniform(name);
  60709. this._floats[name] = value;
  60710. return this;
  60711. };
  60712. ShaderMaterial.prototype.setInt = function (name, value) {
  60713. this._checkUniform(name);
  60714. this._ints[name] = value;
  60715. return this;
  60716. };
  60717. ShaderMaterial.prototype.setFloats = function (name, value) {
  60718. this._checkUniform(name);
  60719. this._floatsArrays[name] = value;
  60720. return this;
  60721. };
  60722. ShaderMaterial.prototype.setColor3 = function (name, value) {
  60723. this._checkUniform(name);
  60724. this._colors3[name] = value;
  60725. return this;
  60726. };
  60727. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  60728. this._checkUniform(name);
  60729. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  60730. color.toArray(arr, arr.length);
  60731. return arr;
  60732. }, []);
  60733. return this;
  60734. };
  60735. ShaderMaterial.prototype.setColor4 = function (name, value) {
  60736. this._checkUniform(name);
  60737. this._colors4[name] = value;
  60738. return this;
  60739. };
  60740. ShaderMaterial.prototype.setVector2 = function (name, value) {
  60741. this._checkUniform(name);
  60742. this._vectors2[name] = value;
  60743. return this;
  60744. };
  60745. ShaderMaterial.prototype.setVector3 = function (name, value) {
  60746. this._checkUniform(name);
  60747. this._vectors3[name] = value;
  60748. return this;
  60749. };
  60750. ShaderMaterial.prototype.setVector4 = function (name, value) {
  60751. this._checkUniform(name);
  60752. this._vectors4[name] = value;
  60753. return this;
  60754. };
  60755. ShaderMaterial.prototype.setMatrix = function (name, value) {
  60756. this._checkUniform(name);
  60757. this._matrices[name] = value;
  60758. return this;
  60759. };
  60760. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  60761. this._checkUniform(name);
  60762. this._matrices3x3[name] = value;
  60763. return this;
  60764. };
  60765. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  60766. this._checkUniform(name);
  60767. this._matrices2x2[name] = value;
  60768. return this;
  60769. };
  60770. ShaderMaterial.prototype.setArray2 = function (name, value) {
  60771. this._checkUniform(name);
  60772. this._vectors2Arrays[name] = value;
  60773. return this;
  60774. };
  60775. ShaderMaterial.prototype.setArray3 = function (name, value) {
  60776. this._checkUniform(name);
  60777. this._vectors3Arrays[name] = value;
  60778. return this;
  60779. };
  60780. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60781. if (!mesh) {
  60782. return true;
  60783. }
  60784. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  60785. return false;
  60786. }
  60787. return false;
  60788. };
  60789. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60790. var scene = this.getScene();
  60791. var engine = scene.getEngine();
  60792. if (!this.checkReadyOnEveryCall) {
  60793. if (this._renderId === scene.getRenderId()) {
  60794. if (this._checkCache(scene, mesh, useInstances)) {
  60795. return true;
  60796. }
  60797. }
  60798. }
  60799. // Instances
  60800. var defines = [];
  60801. var attribs = [];
  60802. var fallbacks = new BABYLON.EffectFallbacks();
  60803. if (useInstances) {
  60804. defines.push("#define INSTANCES");
  60805. }
  60806. for (var index = 0; index < this._options.defines.length; index++) {
  60807. defines.push(this._options.defines[index]);
  60808. }
  60809. for (var index = 0; index < this._options.attributes.length; index++) {
  60810. attribs.push(this._options.attributes[index]);
  60811. }
  60812. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60813. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60814. defines.push("#define VERTEXCOLOR");
  60815. }
  60816. // Bones
  60817. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60818. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60819. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60820. if (mesh.numBoneInfluencers > 4) {
  60821. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60822. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60823. }
  60824. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60825. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60826. fallbacks.addCPUSkinningFallback(0, mesh);
  60827. if (this._options.uniforms.indexOf("mBones") === -1) {
  60828. this._options.uniforms.push("mBones");
  60829. }
  60830. }
  60831. else {
  60832. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60833. }
  60834. // Textures
  60835. for (var name in this._textures) {
  60836. if (!this._textures[name].isReady()) {
  60837. return false;
  60838. }
  60839. }
  60840. // Alpha test
  60841. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60842. defines.push("#define ALPHATEST");
  60843. }
  60844. var previousEffect = this._effect;
  60845. var join = defines.join("\n");
  60846. this._effect = engine.createEffect(this._shaderPath, {
  60847. attributes: attribs,
  60848. uniformsNames: this._options.uniforms,
  60849. uniformBuffersNames: this._options.uniformBuffers,
  60850. samplers: this._options.samplers,
  60851. defines: join,
  60852. fallbacks: fallbacks,
  60853. onCompiled: this.onCompiled,
  60854. onError: this.onError
  60855. }, engine);
  60856. if (!this._effect.isReady()) {
  60857. return false;
  60858. }
  60859. if (previousEffect !== this._effect) {
  60860. scene.resetCachedMaterial();
  60861. }
  60862. this._renderId = scene.getRenderId();
  60863. return true;
  60864. };
  60865. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60866. var scene = this.getScene();
  60867. if (!this._effect) {
  60868. return;
  60869. }
  60870. if (this._options.uniforms.indexOf("world") !== -1) {
  60871. this._effect.setMatrix("world", world);
  60872. }
  60873. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60874. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60875. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60876. }
  60877. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60878. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60879. }
  60880. };
  60881. ShaderMaterial.prototype.bind = function (world, mesh) {
  60882. // Std values
  60883. this.bindOnlyWorldMatrix(world);
  60884. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60885. if (this._options.uniforms.indexOf("view") !== -1) {
  60886. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60887. }
  60888. if (this._options.uniforms.indexOf("projection") !== -1) {
  60889. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60890. }
  60891. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60892. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60893. }
  60894. // Bones
  60895. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60896. var name;
  60897. // Texture
  60898. for (name in this._textures) {
  60899. this._effect.setTexture(name, this._textures[name]);
  60900. }
  60901. // Texture arrays
  60902. for (name in this._textureArrays) {
  60903. this._effect.setTextureArray(name, this._textureArrays[name]);
  60904. }
  60905. // Int
  60906. for (name in this._ints) {
  60907. this._effect.setInt(name, this._ints[name]);
  60908. }
  60909. // Float
  60910. for (name in this._floats) {
  60911. this._effect.setFloat(name, this._floats[name]);
  60912. }
  60913. // Floats
  60914. for (name in this._floatsArrays) {
  60915. this._effect.setArray(name, this._floatsArrays[name]);
  60916. }
  60917. // Color3
  60918. for (name in this._colors3) {
  60919. this._effect.setColor3(name, this._colors3[name]);
  60920. }
  60921. for (name in this._colors3Arrays) {
  60922. this._effect.setArray3(name, this._colors3Arrays[name]);
  60923. }
  60924. // Color4
  60925. for (name in this._colors4) {
  60926. var color = this._colors4[name];
  60927. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60928. }
  60929. // Vector2
  60930. for (name in this._vectors2) {
  60931. this._effect.setVector2(name, this._vectors2[name]);
  60932. }
  60933. // Vector3
  60934. for (name in this._vectors3) {
  60935. this._effect.setVector3(name, this._vectors3[name]);
  60936. }
  60937. // Vector4
  60938. for (name in this._vectors4) {
  60939. this._effect.setVector4(name, this._vectors4[name]);
  60940. }
  60941. // Matrix
  60942. for (name in this._matrices) {
  60943. this._effect.setMatrix(name, this._matrices[name]);
  60944. }
  60945. // Matrix 3x3
  60946. for (name in this._matrices3x3) {
  60947. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60948. }
  60949. // Matrix 2x2
  60950. for (name in this._matrices2x2) {
  60951. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60952. }
  60953. // Vector2Array
  60954. for (name in this._vectors2Arrays) {
  60955. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60956. }
  60957. // Vector3Array
  60958. for (name in this._vectors3Arrays) {
  60959. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60960. }
  60961. }
  60962. this._afterBind(mesh);
  60963. };
  60964. ShaderMaterial.prototype.getActiveTextures = function () {
  60965. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60966. for (var name in this._textures) {
  60967. activeTextures.push(this._textures[name]);
  60968. }
  60969. for (var name in this._textureArrays) {
  60970. var array = this._textureArrays[name];
  60971. for (var index = 0; index < array.length; index++) {
  60972. activeTextures.push(array[index]);
  60973. }
  60974. }
  60975. return activeTextures;
  60976. };
  60977. ShaderMaterial.prototype.hasTexture = function (texture) {
  60978. if (_super.prototype.hasTexture.call(this, texture)) {
  60979. return true;
  60980. }
  60981. for (var name in this._textures) {
  60982. if (this._textures[name] === texture) {
  60983. return true;
  60984. }
  60985. }
  60986. for (var name in this._textureArrays) {
  60987. var array = this._textureArrays[name];
  60988. for (var index = 0; index < array.length; index++) {
  60989. if (array[index] === texture) {
  60990. return true;
  60991. }
  60992. }
  60993. }
  60994. return false;
  60995. };
  60996. ShaderMaterial.prototype.clone = function (name) {
  60997. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60998. return newShaderMaterial;
  60999. };
  61000. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61001. if (forceDisposeTextures) {
  61002. var name;
  61003. for (name in this._textures) {
  61004. this._textures[name].dispose();
  61005. }
  61006. for (name in this._textureArrays) {
  61007. var array = this._textureArrays[name];
  61008. for (var index = 0; index < array.length; index++) {
  61009. array[index].dispose();
  61010. }
  61011. }
  61012. }
  61013. this._textures = {};
  61014. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61015. };
  61016. ShaderMaterial.prototype.serialize = function () {
  61017. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61018. serializationObject.customType = "BABYLON.ShaderMaterial";
  61019. serializationObject.options = this._options;
  61020. serializationObject.shaderPath = this._shaderPath;
  61021. var name;
  61022. // Texture
  61023. serializationObject.textures = {};
  61024. for (name in this._textures) {
  61025. serializationObject.textures[name] = this._textures[name].serialize();
  61026. }
  61027. // Texture arrays
  61028. serializationObject.textureArrays = {};
  61029. for (name in this._textureArrays) {
  61030. serializationObject.textureArrays[name] = [];
  61031. var array = this._textureArrays[name];
  61032. for (var index = 0; index < array.length; index++) {
  61033. serializationObject.textureArrays[name].push(array[index].serialize());
  61034. }
  61035. }
  61036. // Float
  61037. serializationObject.floats = {};
  61038. for (name in this._floats) {
  61039. serializationObject.floats[name] = this._floats[name];
  61040. }
  61041. // Float s
  61042. serializationObject.FloatArrays = {};
  61043. for (name in this._floatsArrays) {
  61044. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  61045. }
  61046. // Color3
  61047. serializationObject.colors3 = {};
  61048. for (name in this._colors3) {
  61049. serializationObject.colors3[name] = this._colors3[name].asArray();
  61050. }
  61051. // Color3 array
  61052. serializationObject.colors3Arrays = {};
  61053. for (name in this._colors3Arrays) {
  61054. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  61055. }
  61056. // Color4
  61057. serializationObject.colors4 = {};
  61058. for (name in this._colors4) {
  61059. serializationObject.colors4[name] = this._colors4[name].asArray();
  61060. }
  61061. // Vector2
  61062. serializationObject.vectors2 = {};
  61063. for (name in this._vectors2) {
  61064. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  61065. }
  61066. // Vector3
  61067. serializationObject.vectors3 = {};
  61068. for (name in this._vectors3) {
  61069. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  61070. }
  61071. // Vector4
  61072. serializationObject.vectors4 = {};
  61073. for (name in this._vectors4) {
  61074. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  61075. }
  61076. // Matrix
  61077. serializationObject.matrices = {};
  61078. for (name in this._matrices) {
  61079. serializationObject.matrices[name] = this._matrices[name].asArray();
  61080. }
  61081. // Matrix 3x3
  61082. serializationObject.matrices3x3 = {};
  61083. for (name in this._matrices3x3) {
  61084. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  61085. }
  61086. // Matrix 2x2
  61087. serializationObject.matrices2x2 = {};
  61088. for (name in this._matrices2x2) {
  61089. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  61090. }
  61091. // Vector2Array
  61092. serializationObject.vectors2Arrays = {};
  61093. for (name in this._vectors2Arrays) {
  61094. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  61095. }
  61096. // Vector3Array
  61097. serializationObject.vectors3Arrays = {};
  61098. for (name in this._vectors3Arrays) {
  61099. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  61100. }
  61101. return serializationObject;
  61102. };
  61103. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  61104. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  61105. var name;
  61106. // Texture
  61107. for (name in source.textures) {
  61108. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  61109. }
  61110. // Texture arrays
  61111. for (name in source.textureArrays) {
  61112. var array = source.textureArrays[name];
  61113. var textureArray = new Array();
  61114. for (var index = 0; index < array.length; index++) {
  61115. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  61116. }
  61117. material.setTextureArray(name, textureArray);
  61118. }
  61119. // Float
  61120. for (name in source.floats) {
  61121. material.setFloat(name, source.floats[name]);
  61122. }
  61123. // Float s
  61124. for (name in source.floatsArrays) {
  61125. material.setFloats(name, source.floatsArrays[name]);
  61126. }
  61127. // Color3
  61128. for (name in source.colors3) {
  61129. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  61130. }
  61131. // Color3 arrays
  61132. for (name in source.colors3Arrays) {
  61133. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  61134. if (i % 3 === 0) {
  61135. arr.push([num]);
  61136. }
  61137. else {
  61138. arr[arr.length - 1].push(num);
  61139. }
  61140. return arr;
  61141. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  61142. material.setColor3Array(name, colors);
  61143. }
  61144. // Color4
  61145. for (name in source.colors4) {
  61146. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  61147. }
  61148. // Vector2
  61149. for (name in source.vectors2) {
  61150. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  61151. }
  61152. // Vector3
  61153. for (name in source.vectors3) {
  61154. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  61155. }
  61156. // Vector4
  61157. for (name in source.vectors4) {
  61158. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  61159. }
  61160. // Matrix
  61161. for (name in source.matrices) {
  61162. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  61163. }
  61164. // Matrix 3x3
  61165. for (name in source.matrices3x3) {
  61166. material.setMatrix3x3(name, source.matrices3x3[name]);
  61167. }
  61168. // Matrix 2x2
  61169. for (name in source.matrices2x2) {
  61170. material.setMatrix2x2(name, source.matrices2x2[name]);
  61171. }
  61172. // Vector2Array
  61173. for (name in source.vectors2Arrays) {
  61174. material.setArray2(name, source.vectors2Arrays[name]);
  61175. }
  61176. // Vector3Array
  61177. for (name in source.vectors3Arrays) {
  61178. material.setArray3(name, source.vectors3Arrays[name]);
  61179. }
  61180. return material;
  61181. };
  61182. return ShaderMaterial;
  61183. }(BABYLON.Material));
  61184. BABYLON.ShaderMaterial = ShaderMaterial;
  61185. })(BABYLON || (BABYLON = {}));
  61186. //# sourceMappingURL=babylon.shaderMaterial.js.map
  61187. var BABYLON;
  61188. (function (BABYLON) {
  61189. var GroundMesh = /** @class */ (function (_super) {
  61190. __extends(GroundMesh, _super);
  61191. function GroundMesh(name, scene) {
  61192. var _this = _super.call(this, name, scene) || this;
  61193. _this.generateOctree = false;
  61194. return _this;
  61195. }
  61196. GroundMesh.prototype.getClassName = function () {
  61197. return "GroundMesh";
  61198. };
  61199. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  61200. get: function () {
  61201. return Math.min(this._subdivisionsX, this._subdivisionsY);
  61202. },
  61203. enumerable: true,
  61204. configurable: true
  61205. });
  61206. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  61207. get: function () {
  61208. return this._subdivisionsX;
  61209. },
  61210. enumerable: true,
  61211. configurable: true
  61212. });
  61213. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  61214. get: function () {
  61215. return this._subdivisionsY;
  61216. },
  61217. enumerable: true,
  61218. configurable: true
  61219. });
  61220. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  61221. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  61222. this._subdivisionsX = chunksCount;
  61223. this._subdivisionsY = chunksCount;
  61224. this.subdivide(chunksCount);
  61225. // Call the octree system optimization if it is defined.
  61226. var thisAsAny = this;
  61227. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  61228. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  61229. }
  61230. };
  61231. /**
  61232. * Returns a height (y) value in the Worl system :
  61233. * the ground altitude at the coordinates (x, z) expressed in the World system.
  61234. * Returns the ground y position if (x, z) are outside the ground surface.
  61235. */
  61236. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  61237. var world = this.getWorldMatrix();
  61238. var invMat = BABYLON.Tmp.Matrix[5];
  61239. world.invertToRef(invMat);
  61240. var tmpVect = BABYLON.Tmp.Vector3[8];
  61241. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  61242. x = tmpVect.x;
  61243. z = tmpVect.z;
  61244. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61245. return this.position.y;
  61246. }
  61247. if (!this._heightQuads || this._heightQuads.length == 0) {
  61248. this._initHeightQuads();
  61249. this._computeHeightQuads();
  61250. }
  61251. var facet = this._getFacetAt(x, z);
  61252. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  61253. // return y in the World system
  61254. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  61255. return tmpVect.y;
  61256. };
  61257. /**
  61258. * Returns a normalized vector (Vector3) orthogonal to the ground
  61259. * at the ground coordinates (x, z) expressed in the World system.
  61260. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  61261. */
  61262. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  61263. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  61264. this.getNormalAtCoordinatesToRef(x, z, normal);
  61265. return normal;
  61266. };
  61267. /**
  61268. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  61269. * at the ground coordinates (x, z) expressed in the World system.
  61270. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  61271. * Returns the GroundMesh.
  61272. */
  61273. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  61274. var world = this.getWorldMatrix();
  61275. var tmpMat = BABYLON.Tmp.Matrix[5];
  61276. world.invertToRef(tmpMat);
  61277. var tmpVect = BABYLON.Tmp.Vector3[8];
  61278. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  61279. x = tmpVect.x;
  61280. z = tmpVect.z;
  61281. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61282. return this;
  61283. }
  61284. if (!this._heightQuads || this._heightQuads.length == 0) {
  61285. this._initHeightQuads();
  61286. this._computeHeightQuads();
  61287. }
  61288. var facet = this._getFacetAt(x, z);
  61289. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  61290. return this;
  61291. };
  61292. /**
  61293. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  61294. * if the ground has been updated.
  61295. * This can be used in the render loop.
  61296. * Returns the GroundMesh.
  61297. */
  61298. GroundMesh.prototype.updateCoordinateHeights = function () {
  61299. if (!this._heightQuads || this._heightQuads.length == 0) {
  61300. this._initHeightQuads();
  61301. }
  61302. this._computeHeightQuads();
  61303. return this;
  61304. };
  61305. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  61306. GroundMesh.prototype._getFacetAt = function (x, z) {
  61307. // retrieve col and row from x, z coordinates in the ground local system
  61308. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  61309. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  61310. var quad = this._heightQuads[row * this._subdivisionsX + col];
  61311. var facet;
  61312. if (z < quad.slope.x * x + quad.slope.y) {
  61313. facet = quad.facet1;
  61314. }
  61315. else {
  61316. facet = quad.facet2;
  61317. }
  61318. return facet;
  61319. };
  61320. // Creates and populates the heightMap array with "facet" elements :
  61321. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  61322. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61323. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61324. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61325. // Returns the GroundMesh.
  61326. GroundMesh.prototype._initHeightQuads = function () {
  61327. var subdivisionsX = this._subdivisionsX;
  61328. var subdivisionsY = this._subdivisionsY;
  61329. this._heightQuads = new Array();
  61330. for (var row = 0; row < subdivisionsY; row++) {
  61331. for (var col = 0; col < subdivisionsX; col++) {
  61332. 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) };
  61333. this._heightQuads[row * subdivisionsX + col] = quad;
  61334. }
  61335. }
  61336. return this;
  61337. };
  61338. // Compute each quad element values and update the the heightMap array :
  61339. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61340. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61341. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61342. // Returns the GroundMesh.
  61343. GroundMesh.prototype._computeHeightQuads = function () {
  61344. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61345. if (!positions) {
  61346. return this;
  61347. }
  61348. var v1 = BABYLON.Tmp.Vector3[3];
  61349. var v2 = BABYLON.Tmp.Vector3[2];
  61350. var v3 = BABYLON.Tmp.Vector3[1];
  61351. var v4 = BABYLON.Tmp.Vector3[0];
  61352. var v1v2 = BABYLON.Tmp.Vector3[4];
  61353. var v1v3 = BABYLON.Tmp.Vector3[5];
  61354. var v1v4 = BABYLON.Tmp.Vector3[6];
  61355. var norm1 = BABYLON.Tmp.Vector3[7];
  61356. var norm2 = BABYLON.Tmp.Vector3[8];
  61357. var i = 0;
  61358. var j = 0;
  61359. var k = 0;
  61360. var cd = 0; // 2D slope coefficient : z = cd * x + h
  61361. var h = 0;
  61362. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  61363. var d2 = 0;
  61364. var subdivisionsX = this._subdivisionsX;
  61365. var subdivisionsY = this._subdivisionsY;
  61366. for (var row = 0; row < subdivisionsY; row++) {
  61367. for (var col = 0; col < subdivisionsX; col++) {
  61368. i = col * 3;
  61369. j = row * (subdivisionsX + 1) * 3;
  61370. k = (row + 1) * (subdivisionsX + 1) * 3;
  61371. v1.x = positions[j + i];
  61372. v1.y = positions[j + i + 1];
  61373. v1.z = positions[j + i + 2];
  61374. v2.x = positions[j + i + 3];
  61375. v2.y = positions[j + i + 4];
  61376. v2.z = positions[j + i + 5];
  61377. v3.x = positions[k + i];
  61378. v3.y = positions[k + i + 1];
  61379. v3.z = positions[k + i + 2];
  61380. v4.x = positions[k + i + 3];
  61381. v4.y = positions[k + i + 4];
  61382. v4.z = positions[k + i + 5];
  61383. // 2D slope V1V4
  61384. cd = (v4.z - v1.z) / (v4.x - v1.x);
  61385. h = v1.z - cd * v1.x; // v1 belongs to the slope
  61386. // facet equations :
  61387. // we compute each facet normal vector
  61388. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  61389. // we compute the value d by applying the equation to v1 which belongs to the plane
  61390. // then we store the facet equation in a Vector4
  61391. v2.subtractToRef(v1, v1v2);
  61392. v3.subtractToRef(v1, v1v3);
  61393. v4.subtractToRef(v1, v1v4);
  61394. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  61395. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  61396. norm1.normalize();
  61397. norm2.normalize();
  61398. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  61399. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  61400. var quad = this._heightQuads[row * subdivisionsX + col];
  61401. quad.slope.copyFromFloats(cd, h);
  61402. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  61403. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  61404. }
  61405. }
  61406. return this;
  61407. };
  61408. GroundMesh.prototype.serialize = function (serializationObject) {
  61409. _super.prototype.serialize.call(this, serializationObject);
  61410. serializationObject.subdivisionsX = this._subdivisionsX;
  61411. serializationObject.subdivisionsY = this._subdivisionsY;
  61412. serializationObject.minX = this._minX;
  61413. serializationObject.maxX = this._maxX;
  61414. serializationObject.minZ = this._minZ;
  61415. serializationObject.maxZ = this._maxZ;
  61416. serializationObject.width = this._width;
  61417. serializationObject.height = this._height;
  61418. };
  61419. GroundMesh.Parse = function (parsedMesh, scene) {
  61420. var result = new GroundMesh(parsedMesh.name, scene);
  61421. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  61422. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  61423. result._minX = parsedMesh.minX;
  61424. result._maxX = parsedMesh.maxX;
  61425. result._minZ = parsedMesh.minZ;
  61426. result._maxZ = parsedMesh.maxZ;
  61427. result._width = parsedMesh.width;
  61428. result._height = parsedMesh.height;
  61429. return result;
  61430. };
  61431. return GroundMesh;
  61432. }(BABYLON.Mesh));
  61433. BABYLON.GroundMesh = GroundMesh;
  61434. })(BABYLON || (BABYLON = {}));
  61435. //# sourceMappingURL=babylon.groundMesh.js.map
  61436. var BABYLON;
  61437. (function (BABYLON) {
  61438. /**
  61439. * Creates an instance based on a source mesh.
  61440. */
  61441. var InstancedMesh = /** @class */ (function (_super) {
  61442. __extends(InstancedMesh, _super);
  61443. function InstancedMesh(name, source) {
  61444. var _this = _super.call(this, name, source.getScene()) || this;
  61445. source.instances.push(_this);
  61446. _this._sourceMesh = source;
  61447. _this.position.copyFrom(source.position);
  61448. _this.rotation.copyFrom(source.rotation);
  61449. _this.scaling.copyFrom(source.scaling);
  61450. if (source.rotationQuaternion) {
  61451. _this.rotationQuaternion = source.rotationQuaternion.clone();
  61452. }
  61453. _this.infiniteDistance = source.infiniteDistance;
  61454. _this.setPivotMatrix(source.getPivotMatrix());
  61455. _this.refreshBoundingInfo();
  61456. _this._syncSubMeshes();
  61457. return _this;
  61458. }
  61459. /**
  61460. * Returns the string "InstancedMesh".
  61461. */
  61462. InstancedMesh.prototype.getClassName = function () {
  61463. return "InstancedMesh";
  61464. };
  61465. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  61466. // Methods
  61467. get: function () {
  61468. return this._sourceMesh.receiveShadows;
  61469. },
  61470. enumerable: true,
  61471. configurable: true
  61472. });
  61473. Object.defineProperty(InstancedMesh.prototype, "material", {
  61474. get: function () {
  61475. return this._sourceMesh.material;
  61476. },
  61477. enumerable: true,
  61478. configurable: true
  61479. });
  61480. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  61481. get: function () {
  61482. return this._sourceMesh.visibility;
  61483. },
  61484. enumerable: true,
  61485. configurable: true
  61486. });
  61487. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  61488. get: function () {
  61489. return this._sourceMesh.skeleton;
  61490. },
  61491. enumerable: true,
  61492. configurable: true
  61493. });
  61494. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  61495. get: function () {
  61496. return this._sourceMesh.renderingGroupId;
  61497. },
  61498. set: function (value) {
  61499. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  61500. return;
  61501. }
  61502. //no-op with warning
  61503. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  61504. },
  61505. enumerable: true,
  61506. configurable: true
  61507. });
  61508. /**
  61509. * Returns the total number of vertices (integer).
  61510. */
  61511. InstancedMesh.prototype.getTotalVertices = function () {
  61512. return this._sourceMesh.getTotalVertices();
  61513. };
  61514. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  61515. get: function () {
  61516. return this._sourceMesh;
  61517. },
  61518. enumerable: true,
  61519. configurable: true
  61520. });
  61521. /**
  61522. * Is this node ready to be used/rendered
  61523. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  61524. * @return {boolean} is it ready
  61525. */
  61526. InstancedMesh.prototype.isReady = function (completeCheck) {
  61527. if (completeCheck === void 0) { completeCheck = false; }
  61528. return this._sourceMesh.isReady(completeCheck, true);
  61529. };
  61530. /**
  61531. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  61532. */
  61533. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  61534. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  61535. };
  61536. /**
  61537. * Sets the vertex data of the mesh geometry for the requested `kind`.
  61538. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  61539. * The `data` are either a numeric array either a Float32Array.
  61540. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  61541. * 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).
  61542. * Note that a new underlying VertexBuffer object is created each call.
  61543. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  61544. *
  61545. * Possible `kind` values :
  61546. * - BABYLON.VertexBuffer.PositionKind
  61547. * - BABYLON.VertexBuffer.UVKind
  61548. * - BABYLON.VertexBuffer.UV2Kind
  61549. * - BABYLON.VertexBuffer.UV3Kind
  61550. * - BABYLON.VertexBuffer.UV4Kind
  61551. * - BABYLON.VertexBuffer.UV5Kind
  61552. * - BABYLON.VertexBuffer.UV6Kind
  61553. * - BABYLON.VertexBuffer.ColorKind
  61554. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61555. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61556. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61557. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61558. *
  61559. * Returns the Mesh.
  61560. */
  61561. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  61562. if (this.sourceMesh) {
  61563. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  61564. }
  61565. return this.sourceMesh;
  61566. };
  61567. /**
  61568. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  61569. * If the mesh has no geometry, it is simply returned as it is.
  61570. * The `data` are either a numeric array either a Float32Array.
  61571. * No new underlying VertexBuffer object is created.
  61572. * 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.
  61573. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  61574. *
  61575. * Possible `kind` values :
  61576. * - BABYLON.VertexBuffer.PositionKind
  61577. * - BABYLON.VertexBuffer.UVKind
  61578. * - BABYLON.VertexBuffer.UV2Kind
  61579. * - BABYLON.VertexBuffer.UV3Kind
  61580. * - BABYLON.VertexBuffer.UV4Kind
  61581. * - BABYLON.VertexBuffer.UV5Kind
  61582. * - BABYLON.VertexBuffer.UV6Kind
  61583. * - BABYLON.VertexBuffer.ColorKind
  61584. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61585. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61586. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61587. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61588. *
  61589. * Returns the Mesh.
  61590. */
  61591. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  61592. if (this.sourceMesh) {
  61593. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  61594. }
  61595. return this.sourceMesh;
  61596. };
  61597. /**
  61598. * Sets the mesh indices.
  61599. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  61600. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  61601. * This method creates a new index buffer each call.
  61602. * Returns the Mesh.
  61603. */
  61604. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  61605. if (totalVertices === void 0) { totalVertices = null; }
  61606. if (this.sourceMesh) {
  61607. this.sourceMesh.setIndices(indices, totalVertices);
  61608. }
  61609. return this.sourceMesh;
  61610. };
  61611. /**
  61612. * Boolean : True if the mesh owns the requested kind of data.
  61613. */
  61614. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  61615. return this._sourceMesh.isVerticesDataPresent(kind);
  61616. };
  61617. /**
  61618. * Returns an array of indices (IndicesArray).
  61619. */
  61620. InstancedMesh.prototype.getIndices = function () {
  61621. return this._sourceMesh.getIndices();
  61622. };
  61623. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  61624. get: function () {
  61625. return this._sourceMesh._positions;
  61626. },
  61627. enumerable: true,
  61628. configurable: true
  61629. });
  61630. /**
  61631. * Sets a new updated BoundingInfo to the mesh.
  61632. * Returns the mesh.
  61633. */
  61634. InstancedMesh.prototype.refreshBoundingInfo = function () {
  61635. var meshBB = this._sourceMesh.getBoundingInfo();
  61636. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  61637. this._updateBoundingInfo();
  61638. return this;
  61639. };
  61640. /** @hidden */
  61641. InstancedMesh.prototype._preActivate = function () {
  61642. if (this._currentLOD) {
  61643. this._currentLOD._preActivate();
  61644. }
  61645. return this;
  61646. };
  61647. /** @hidden */
  61648. InstancedMesh.prototype._activate = function (renderId) {
  61649. if (this._currentLOD) {
  61650. this._currentLOD._registerInstanceForRenderId(this, renderId);
  61651. }
  61652. return this;
  61653. };
  61654. /**
  61655. * Returns the current associated LOD AbstractMesh.
  61656. */
  61657. InstancedMesh.prototype.getLOD = function (camera) {
  61658. if (!camera) {
  61659. return this;
  61660. }
  61661. var boundingInfo = this.getBoundingInfo();
  61662. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  61663. if (this._currentLOD === this.sourceMesh) {
  61664. return this;
  61665. }
  61666. return this._currentLOD;
  61667. };
  61668. /** @hidden */
  61669. InstancedMesh.prototype._syncSubMeshes = function () {
  61670. this.releaseSubMeshes();
  61671. if (this._sourceMesh.subMeshes) {
  61672. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  61673. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  61674. }
  61675. }
  61676. return this;
  61677. };
  61678. /** @hidden */
  61679. InstancedMesh.prototype._generatePointsArray = function () {
  61680. return this._sourceMesh._generatePointsArray();
  61681. };
  61682. /**
  61683. * Creates a new InstancedMesh from the current mesh.
  61684. * - name (string) : the cloned mesh name
  61685. * - newParent (optional Node) : the optional Node to parent the clone to.
  61686. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  61687. *
  61688. * Returns the clone.
  61689. */
  61690. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61691. var result = this._sourceMesh.createInstance(name);
  61692. // Deep copy
  61693. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  61694. // Bounding info
  61695. this.refreshBoundingInfo();
  61696. // Parent
  61697. if (newParent) {
  61698. result.parent = newParent;
  61699. }
  61700. if (!doNotCloneChildren) {
  61701. // Children
  61702. for (var index = 0; index < this.getScene().meshes.length; index++) {
  61703. var mesh = this.getScene().meshes[index];
  61704. if (mesh.parent === this) {
  61705. mesh.clone(mesh.name, result);
  61706. }
  61707. }
  61708. }
  61709. result.computeWorldMatrix(true);
  61710. return result;
  61711. };
  61712. /**
  61713. * Disposes the InstancedMesh.
  61714. * Returns nothing.
  61715. */
  61716. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  61717. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  61718. // Remove from mesh
  61719. var index = this._sourceMesh.instances.indexOf(this);
  61720. this._sourceMesh.instances.splice(index, 1);
  61721. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  61722. };
  61723. return InstancedMesh;
  61724. }(BABYLON.AbstractMesh));
  61725. BABYLON.InstancedMesh = InstancedMesh;
  61726. })(BABYLON || (BABYLON = {}));
  61727. //# sourceMappingURL=babylon.instancedMesh.js.map
  61728. var BABYLON;
  61729. (function (BABYLON) {
  61730. var LinesMesh = /** @class */ (function (_super) {
  61731. __extends(LinesMesh, _super);
  61732. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  61733. if (scene === void 0) { scene = null; }
  61734. if (parent === void 0) { parent = null; }
  61735. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  61736. _this.useVertexColor = useVertexColor;
  61737. _this.useVertexAlpha = useVertexAlpha;
  61738. _this.color = new BABYLON.Color3(1, 1, 1);
  61739. _this.alpha = 1;
  61740. if (source) {
  61741. _this.color = source.color.clone();
  61742. _this.alpha = source.alpha;
  61743. _this.useVertexColor = source.useVertexColor;
  61744. _this.useVertexAlpha = source.useVertexAlpha;
  61745. }
  61746. _this._intersectionThreshold = 0.1;
  61747. var defines = [];
  61748. var options = {
  61749. attributes: [BABYLON.VertexBuffer.PositionKind],
  61750. uniforms: ["world", "viewProjection"],
  61751. needAlphaBlending: true,
  61752. defines: defines
  61753. };
  61754. if (useVertexAlpha === false) {
  61755. options.needAlphaBlending = false;
  61756. }
  61757. if (!useVertexColor) {
  61758. options.uniforms.push("color");
  61759. }
  61760. else {
  61761. options.defines.push("#define VERTEXCOLOR");
  61762. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  61763. }
  61764. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  61765. return _this;
  61766. }
  61767. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  61768. /**
  61769. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61770. * This margin is expressed in world space coordinates, so its value may vary.
  61771. * Default value is 0.1
  61772. * @returns the intersection Threshold value.
  61773. */
  61774. get: function () {
  61775. return this._intersectionThreshold;
  61776. },
  61777. /**
  61778. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61779. * This margin is expressed in world space coordinates, so its value may vary.
  61780. * @param value the new threshold to apply
  61781. */
  61782. set: function (value) {
  61783. if (this._intersectionThreshold === value) {
  61784. return;
  61785. }
  61786. this._intersectionThreshold = value;
  61787. if (this.geometry) {
  61788. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  61789. }
  61790. },
  61791. enumerable: true,
  61792. configurable: true
  61793. });
  61794. /**
  61795. * Returns the string "LineMesh"
  61796. */
  61797. LinesMesh.prototype.getClassName = function () {
  61798. return "LinesMesh";
  61799. };
  61800. Object.defineProperty(LinesMesh.prototype, "material", {
  61801. /**
  61802. * @hidden
  61803. */
  61804. get: function () {
  61805. return this._colorShader;
  61806. },
  61807. /**
  61808. * @hidden
  61809. */
  61810. set: function (value) {
  61811. // Do nothing
  61812. },
  61813. enumerable: true,
  61814. configurable: true
  61815. });
  61816. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61817. /**
  61818. * @hidden
  61819. */
  61820. get: function () {
  61821. return false;
  61822. },
  61823. enumerable: true,
  61824. configurable: true
  61825. });
  61826. LinesMesh.prototype.createInstance = function (name) {
  61827. throw new Error("LinesMeshes do not support createInstance.");
  61828. };
  61829. /** @hidden */
  61830. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61831. if (!this._geometry) {
  61832. return this;
  61833. }
  61834. // VBOs
  61835. this._geometry._bind(this._colorShader.getEffect());
  61836. // Color
  61837. if (!this.useVertexColor) {
  61838. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61839. }
  61840. return this;
  61841. };
  61842. /** @hidden */
  61843. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61844. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61845. return this;
  61846. }
  61847. var engine = this.getScene().getEngine();
  61848. // Draw order
  61849. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61850. return this;
  61851. };
  61852. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61853. this._colorShader.dispose();
  61854. _super.prototype.dispose.call(this, doNotRecurse);
  61855. };
  61856. /**
  61857. * Returns a new LineMesh object cloned from the current one.
  61858. */
  61859. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61860. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61861. };
  61862. return LinesMesh;
  61863. }(BABYLON.Mesh));
  61864. BABYLON.LinesMesh = LinesMesh;
  61865. })(BABYLON || (BABYLON = {}));
  61866. //# sourceMappingURL=babylon.linesMesh.js.map
  61867. var BABYLON;
  61868. (function (BABYLON) {
  61869. /**
  61870. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61871. * The underlying implementation relies on an associative array to ensure the best performances.
  61872. * The value can be anything including 'null' but except 'undefined'
  61873. */
  61874. var StringDictionary = /** @class */ (function () {
  61875. function StringDictionary() {
  61876. this._count = 0;
  61877. this._data = {};
  61878. }
  61879. /**
  61880. * This will clear this dictionary and copy the content from the 'source' one.
  61881. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61882. * @param source the dictionary to take the content from and copy to this dictionary
  61883. */
  61884. StringDictionary.prototype.copyFrom = function (source) {
  61885. var _this = this;
  61886. this.clear();
  61887. source.forEach(function (t, v) { return _this.add(t, v); });
  61888. };
  61889. /**
  61890. * Get a value based from its key
  61891. * @param key the given key to get the matching value from
  61892. * @return the value if found, otherwise undefined is returned
  61893. */
  61894. StringDictionary.prototype.get = function (key) {
  61895. var val = this._data[key];
  61896. if (val !== undefined) {
  61897. return val;
  61898. }
  61899. return undefined;
  61900. };
  61901. /**
  61902. * Get a value from its key or add it if it doesn't exist.
  61903. * This method will ensure you that a given key/data will be present in the dictionary.
  61904. * @param key the given key to get the matching value from
  61905. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61906. * The factory will only be invoked if there's no data for the given key.
  61907. * @return the value corresponding to the key.
  61908. */
  61909. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61910. var val = this.get(key);
  61911. if (val !== undefined) {
  61912. return val;
  61913. }
  61914. val = factory(key);
  61915. if (val) {
  61916. this.add(key, val);
  61917. }
  61918. return val;
  61919. };
  61920. /**
  61921. * Get a value from its key if present in the dictionary otherwise add it
  61922. * @param key the key to get the value from
  61923. * @param val if there's no such key/value pair in the dictionary add it with this value
  61924. * @return the value corresponding to the key
  61925. */
  61926. StringDictionary.prototype.getOrAdd = function (key, val) {
  61927. var curVal = this.get(key);
  61928. if (curVal !== undefined) {
  61929. return curVal;
  61930. }
  61931. this.add(key, val);
  61932. return val;
  61933. };
  61934. /**
  61935. * Check if there's a given key in the dictionary
  61936. * @param key the key to check for
  61937. * @return true if the key is present, false otherwise
  61938. */
  61939. StringDictionary.prototype.contains = function (key) {
  61940. return this._data[key] !== undefined;
  61941. };
  61942. /**
  61943. * Add a new key and its corresponding value
  61944. * @param key the key to add
  61945. * @param value the value corresponding to the key
  61946. * @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
  61947. */
  61948. StringDictionary.prototype.add = function (key, value) {
  61949. if (this._data[key] !== undefined) {
  61950. return false;
  61951. }
  61952. this._data[key] = value;
  61953. ++this._count;
  61954. return true;
  61955. };
  61956. StringDictionary.prototype.set = function (key, value) {
  61957. if (this._data[key] === undefined) {
  61958. return false;
  61959. }
  61960. this._data[key] = value;
  61961. return true;
  61962. };
  61963. /**
  61964. * Get the element of the given key and remove it from the dictionary
  61965. * @param key
  61966. */
  61967. StringDictionary.prototype.getAndRemove = function (key) {
  61968. var val = this.get(key);
  61969. if (val !== undefined) {
  61970. delete this._data[key];
  61971. --this._count;
  61972. return val;
  61973. }
  61974. return null;
  61975. };
  61976. /**
  61977. * Remove a key/value from the dictionary.
  61978. * @param key the key to remove
  61979. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61980. */
  61981. StringDictionary.prototype.remove = function (key) {
  61982. if (this.contains(key)) {
  61983. delete this._data[key];
  61984. --this._count;
  61985. return true;
  61986. }
  61987. return false;
  61988. };
  61989. /**
  61990. * Clear the whole content of the dictionary
  61991. */
  61992. StringDictionary.prototype.clear = function () {
  61993. this._data = {};
  61994. this._count = 0;
  61995. };
  61996. Object.defineProperty(StringDictionary.prototype, "count", {
  61997. get: function () {
  61998. return this._count;
  61999. },
  62000. enumerable: true,
  62001. configurable: true
  62002. });
  62003. /**
  62004. * Execute a callback on each key/val of the dictionary.
  62005. * Note that you can remove any element in this dictionary in the callback implementation
  62006. * @param callback the callback to execute on a given key/value pair
  62007. */
  62008. StringDictionary.prototype.forEach = function (callback) {
  62009. for (var cur in this._data) {
  62010. var val = this._data[cur];
  62011. callback(cur, val);
  62012. }
  62013. };
  62014. /**
  62015. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62016. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62017. * Note that you can remove any element in this dictionary in the callback implementation
  62018. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62019. */
  62020. StringDictionary.prototype.first = function (callback) {
  62021. for (var cur in this._data) {
  62022. var val = this._data[cur];
  62023. var res = callback(cur, val);
  62024. if (res) {
  62025. return res;
  62026. }
  62027. }
  62028. return null;
  62029. };
  62030. return StringDictionary;
  62031. }());
  62032. BABYLON.StringDictionary = StringDictionary;
  62033. })(BABYLON || (BABYLON = {}));
  62034. //# sourceMappingURL=babylon.stringDictionary.js.map
  62035. var BABYLON;
  62036. (function (BABYLON) {
  62037. var Debug;
  62038. (function (Debug) {
  62039. /**
  62040. * Class used to render a debug view of a given skeleton
  62041. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  62042. */
  62043. var SkeletonViewer = /** @class */ (function () {
  62044. /**
  62045. * Creates a new SkeletonViewer
  62046. * @param skeleton defines the skeleton to render
  62047. * @param mesh defines the mesh attached to the skeleton
  62048. * @param scene defines the hosting scene
  62049. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  62050. * @param renderingGroupId defines the rendering group id to use with the viewer
  62051. */
  62052. function SkeletonViewer(
  62053. /** defines the skeleton to render */
  62054. skeleton,
  62055. /** defines the mesh attached to the skeleton */
  62056. mesh, scene,
  62057. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  62058. autoUpdateBonesMatrices,
  62059. /** defines the rendering group id to use with the viewer */
  62060. renderingGroupId) {
  62061. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  62062. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  62063. this.skeleton = skeleton;
  62064. this.mesh = mesh;
  62065. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  62066. this.renderingGroupId = renderingGroupId;
  62067. /** Gets or sets the color used to render the skeleton */
  62068. this.color = BABYLON.Color3.White();
  62069. this._debugLines = new Array();
  62070. this._isEnabled = false;
  62071. this._scene = scene;
  62072. this.update();
  62073. this._renderFunction = this.update.bind(this);
  62074. }
  62075. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  62076. get: function () {
  62077. return this._isEnabled;
  62078. },
  62079. /** Gets or sets a boolean indicating if the viewer is enabled */
  62080. set: function (value) {
  62081. if (this._isEnabled === value) {
  62082. return;
  62083. }
  62084. this._isEnabled = value;
  62085. if (value) {
  62086. this._scene.registerBeforeRender(this._renderFunction);
  62087. }
  62088. else {
  62089. this._scene.unregisterBeforeRender(this._renderFunction);
  62090. }
  62091. },
  62092. enumerable: true,
  62093. configurable: true
  62094. });
  62095. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  62096. if (x === void 0) { x = 0; }
  62097. if (y === void 0) { y = 0; }
  62098. if (z === void 0) { z = 0; }
  62099. var tmat = BABYLON.Tmp.Matrix[0];
  62100. var parentBone = bone.getParent();
  62101. tmat.copyFrom(bone.getLocalMatrix());
  62102. if (x !== 0 || y !== 0 || z !== 0) {
  62103. var tmat2 = BABYLON.Tmp.Matrix[1];
  62104. BABYLON.Matrix.IdentityToRef(tmat2);
  62105. tmat2.m[12] = x;
  62106. tmat2.m[13] = y;
  62107. tmat2.m[14] = z;
  62108. tmat2.multiplyToRef(tmat, tmat);
  62109. }
  62110. if (parentBone) {
  62111. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  62112. }
  62113. tmat.multiplyToRef(meshMat, tmat);
  62114. position.x = tmat.m[12];
  62115. position.y = tmat.m[13];
  62116. position.z = tmat.m[14];
  62117. };
  62118. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  62119. var len = bones.length;
  62120. var meshPos = this.mesh.position;
  62121. for (var i = 0; i < len; i++) {
  62122. var bone = bones[i];
  62123. var points = this._debugLines[i];
  62124. if (!points) {
  62125. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62126. this._debugLines[i] = points;
  62127. }
  62128. this._getBonePosition(points[0], bone, meshMat);
  62129. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  62130. points[0].subtractInPlace(meshPos);
  62131. points[1].subtractInPlace(meshPos);
  62132. }
  62133. };
  62134. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  62135. var len = bones.length;
  62136. var boneNum = 0;
  62137. var meshPos = this.mesh.position;
  62138. for (var i = len - 1; i >= 0; i--) {
  62139. var childBone = bones[i];
  62140. var parentBone = childBone.getParent();
  62141. if (!parentBone) {
  62142. continue;
  62143. }
  62144. var points = this._debugLines[boneNum];
  62145. if (!points) {
  62146. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62147. this._debugLines[boneNum] = points;
  62148. }
  62149. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  62150. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  62151. points[0].subtractInPlace(meshPos);
  62152. points[1].subtractInPlace(meshPos);
  62153. boneNum++;
  62154. }
  62155. };
  62156. /** Update the viewer to sync with current skeleton state */
  62157. SkeletonViewer.prototype.update = function () {
  62158. if (this.autoUpdateBonesMatrices) {
  62159. this.skeleton.computeAbsoluteTransforms();
  62160. }
  62161. if (this.skeleton.bones[0].length === undefined) {
  62162. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62163. }
  62164. else {
  62165. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62166. }
  62167. if (!this._debugMesh) {
  62168. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  62169. this._debugMesh.renderingGroupId = this.renderingGroupId;
  62170. }
  62171. else {
  62172. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  62173. }
  62174. this._debugMesh.position.copyFrom(this.mesh.position);
  62175. this._debugMesh.color = this.color;
  62176. };
  62177. /** Release associated resources */
  62178. SkeletonViewer.prototype.dispose = function () {
  62179. if (this._debugMesh) {
  62180. this.isEnabled = false;
  62181. this._debugMesh.dispose();
  62182. this._debugMesh = null;
  62183. }
  62184. };
  62185. return SkeletonViewer;
  62186. }());
  62187. Debug.SkeletonViewer = SkeletonViewer;
  62188. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62189. })(BABYLON || (BABYLON = {}));
  62190. //# sourceMappingURL=babylon.skeletonViewer.js.map
  62191. /**
  62192. * Module Debug contains the (visual) components to debug a scene correctly
  62193. */
  62194. var BABYLON;
  62195. (function (BABYLON) {
  62196. var Debug;
  62197. (function (Debug) {
  62198. /**
  62199. * The Axes viewer will show 3 axes in a specific point in space
  62200. */
  62201. var AxesViewer = /** @class */ (function () {
  62202. /**
  62203. * Creates a new AxesViewer
  62204. * @param scene defines the hosting scene
  62205. * @param scaleLines defines a number used to scale line length (1 by default)
  62206. */
  62207. function AxesViewer(scene, scaleLines) {
  62208. if (scaleLines === void 0) { scaleLines = 1; }
  62209. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62210. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62211. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62212. /**
  62213. * Gets or sets a number used to scale line length
  62214. */
  62215. this.scaleLines = 1;
  62216. this.scaleLines = scaleLines;
  62217. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  62218. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  62219. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  62220. this._xmesh.renderingGroupId = 2;
  62221. this._ymesh.renderingGroupId = 2;
  62222. this._zmesh.renderingGroupId = 2;
  62223. this._xmesh.material.checkReadyOnlyOnce = true;
  62224. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  62225. this._ymesh.material.checkReadyOnlyOnce = true;
  62226. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  62227. this._zmesh.material.checkReadyOnlyOnce = true;
  62228. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  62229. this.scene = scene;
  62230. }
  62231. /**
  62232. * Force the viewer to update
  62233. * @param position defines the position of the viewer
  62234. * @param xaxis defines the x axis of the viewer
  62235. * @param yaxis defines the y axis of the viewer
  62236. * @param zaxis defines the z axis of the viewer
  62237. */
  62238. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  62239. var scaleLines = this.scaleLines;
  62240. if (this._xmesh) {
  62241. this._xmesh.position.copyFrom(position);
  62242. }
  62243. if (this._ymesh) {
  62244. this._ymesh.position.copyFrom(position);
  62245. }
  62246. if (this._zmesh) {
  62247. this._zmesh.position.copyFrom(position);
  62248. }
  62249. var point2 = this._xline[1];
  62250. point2.x = xaxis.x * scaleLines;
  62251. point2.y = xaxis.y * scaleLines;
  62252. point2.z = xaxis.z * scaleLines;
  62253. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  62254. point2 = this._yline[1];
  62255. point2.x = yaxis.x * scaleLines;
  62256. point2.y = yaxis.y * scaleLines;
  62257. point2.z = yaxis.z * scaleLines;
  62258. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  62259. point2 = this._zline[1];
  62260. point2.x = zaxis.x * scaleLines;
  62261. point2.y = zaxis.y * scaleLines;
  62262. point2.z = zaxis.z * scaleLines;
  62263. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  62264. };
  62265. /** Releases resources */
  62266. AxesViewer.prototype.dispose = function () {
  62267. if (this._xmesh) {
  62268. this._xmesh.dispose();
  62269. }
  62270. if (this._ymesh) {
  62271. this._ymesh.dispose();
  62272. }
  62273. if (this._zmesh) {
  62274. this._zmesh.dispose();
  62275. }
  62276. this._xmesh = null;
  62277. this._ymesh = null;
  62278. this._zmesh = null;
  62279. this.scene = null;
  62280. };
  62281. return AxesViewer;
  62282. }());
  62283. Debug.AxesViewer = AxesViewer;
  62284. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62285. })(BABYLON || (BABYLON = {}));
  62286. //# sourceMappingURL=babylon.axesViewer.js.map
  62287. var BABYLON;
  62288. (function (BABYLON) {
  62289. var Debug;
  62290. (function (Debug) {
  62291. /**
  62292. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  62293. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  62294. */
  62295. var BoneAxesViewer = /** @class */ (function (_super) {
  62296. __extends(BoneAxesViewer, _super);
  62297. /**
  62298. * Creates a new BoneAxesViewer
  62299. * @param scene defines the hosting scene
  62300. * @param bone defines the target bone
  62301. * @param mesh defines the target mesh
  62302. * @param scaleLines defines a scaling factor for line length (1 by default)
  62303. */
  62304. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  62305. if (scaleLines === void 0) { scaleLines = 1; }
  62306. var _this = _super.call(this, scene, scaleLines) || this;
  62307. /** Gets current position */
  62308. _this.pos = BABYLON.Vector3.Zero();
  62309. /** Gets direction of X axis */
  62310. _this.xaxis = BABYLON.Vector3.Zero();
  62311. /** Gets direction of Y axis */
  62312. _this.yaxis = BABYLON.Vector3.Zero();
  62313. /** Gets direction of Z axis */
  62314. _this.zaxis = BABYLON.Vector3.Zero();
  62315. _this.mesh = mesh;
  62316. _this.bone = bone;
  62317. return _this;
  62318. }
  62319. /**
  62320. * Force the viewer to update
  62321. */
  62322. BoneAxesViewer.prototype.update = function () {
  62323. if (!this.mesh || !this.bone) {
  62324. return;
  62325. }
  62326. var bone = this.bone;
  62327. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62328. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62329. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62330. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62331. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62332. };
  62333. /** Releases resources */
  62334. BoneAxesViewer.prototype.dispose = function () {
  62335. if (this.mesh) {
  62336. this.mesh = null;
  62337. this.bone = null;
  62338. _super.prototype.dispose.call(this);
  62339. }
  62340. };
  62341. return BoneAxesViewer;
  62342. }(Debug.AxesViewer));
  62343. Debug.BoneAxesViewer = BoneAxesViewer;
  62344. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62345. })(BABYLON || (BABYLON = {}));
  62346. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62347. var BABYLON;
  62348. (function (BABYLON) {
  62349. /**
  62350. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  62351. * in order to better appreciate the issue one might have.
  62352. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  62353. */
  62354. var RayHelper = /** @class */ (function () {
  62355. /**
  62356. * Instantiate a new ray helper.
  62357. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  62358. * in order to better appreciate the issue one might have.
  62359. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  62360. * @param ray Defines the ray we are currently tryin to visualize
  62361. */
  62362. function RayHelper(ray) {
  62363. this.ray = ray;
  62364. }
  62365. /**
  62366. * Helper function to create a colored helper in a scene in one line.
  62367. * @param ray Defines the ray we are currently tryin to visualize
  62368. * @param scene Defines the scene the ray is used in
  62369. * @param color Defines the color we want to see the ray in
  62370. * @returns The newly created ray helper.
  62371. */
  62372. RayHelper.CreateAndShow = function (ray, scene, color) {
  62373. var helper = new RayHelper(ray);
  62374. helper.show(scene, color);
  62375. return helper;
  62376. };
  62377. /**
  62378. * Shows the ray we are willing to debug.
  62379. * @param scene Defines the scene the ray needs to be rendered in
  62380. * @param color Defines the color the ray needs to be rendered in
  62381. */
  62382. RayHelper.prototype.show = function (scene, color) {
  62383. if (!this._renderFunction && this.ray) {
  62384. var ray = this.ray;
  62385. this._renderFunction = this._render.bind(this);
  62386. this._scene = scene;
  62387. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62388. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62389. if (this._renderFunction) {
  62390. this._scene.registerBeforeRender(this._renderFunction);
  62391. }
  62392. }
  62393. if (color && this._renderLine) {
  62394. this._renderLine.color.copyFrom(color);
  62395. }
  62396. };
  62397. /**
  62398. * Hides the ray we are debugging.
  62399. */
  62400. RayHelper.prototype.hide = function () {
  62401. if (this._renderFunction && this._scene) {
  62402. this._scene.unregisterBeforeRender(this._renderFunction);
  62403. this._scene = null;
  62404. this._renderFunction = null;
  62405. if (this._renderLine) {
  62406. this._renderLine.dispose();
  62407. this._renderLine = null;
  62408. }
  62409. this._renderPoints = [];
  62410. }
  62411. };
  62412. RayHelper.prototype._render = function () {
  62413. var ray = this.ray;
  62414. if (!ray) {
  62415. return;
  62416. }
  62417. var point = this._renderPoints[1];
  62418. var len = Math.min(ray.length, 1000000);
  62419. point.copyFrom(ray.direction);
  62420. point.scaleInPlace(len);
  62421. point.addInPlace(ray.origin);
  62422. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62423. };
  62424. /**
  62425. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  62426. * @param mesh Defines the mesh we want the helper attached to
  62427. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  62428. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  62429. * @param length Defines the length of the ray
  62430. */
  62431. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62432. this._attachedToMesh = mesh;
  62433. var ray = this.ray;
  62434. if (!ray) {
  62435. return;
  62436. }
  62437. if (!ray.direction) {
  62438. ray.direction = BABYLON.Vector3.Zero();
  62439. }
  62440. if (!ray.origin) {
  62441. ray.origin = BABYLON.Vector3.Zero();
  62442. }
  62443. if (length) {
  62444. ray.length = length;
  62445. }
  62446. if (!meshSpaceOrigin) {
  62447. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62448. }
  62449. if (!meshSpaceDirection) {
  62450. // -1 so that this will work with Mesh.lookAt
  62451. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62452. }
  62453. if (!this._meshSpaceDirection) {
  62454. this._meshSpaceDirection = meshSpaceDirection.clone();
  62455. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62456. }
  62457. else {
  62458. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62459. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62460. }
  62461. if (!this._updateToMeshFunction) {
  62462. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62463. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62464. }
  62465. this._updateToMesh();
  62466. };
  62467. /**
  62468. * Detach the ray helper from the mesh it has previously been attached to.
  62469. */
  62470. RayHelper.prototype.detachFromMesh = function () {
  62471. if (this._attachedToMesh) {
  62472. if (this._updateToMeshFunction) {
  62473. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62474. }
  62475. this._attachedToMesh = null;
  62476. this._updateToMeshFunction = null;
  62477. }
  62478. };
  62479. RayHelper.prototype._updateToMesh = function () {
  62480. var ray = this.ray;
  62481. if (!this._attachedToMesh || !ray) {
  62482. return;
  62483. }
  62484. if (this._attachedToMesh._isDisposed) {
  62485. this.detachFromMesh();
  62486. return;
  62487. }
  62488. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62489. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62490. };
  62491. /**
  62492. * Dispose the helper and release its associated resources.
  62493. */
  62494. RayHelper.prototype.dispose = function () {
  62495. this.hide();
  62496. this.detachFromMesh();
  62497. this.ray = null;
  62498. };
  62499. return RayHelper;
  62500. }());
  62501. BABYLON.RayHelper = RayHelper;
  62502. })(BABYLON || (BABYLON = {}));
  62503. //# sourceMappingURL=babylon.rayHelper.js.map
  62504. var BABYLON;
  62505. (function (BABYLON) {
  62506. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  62507. get: function () {
  62508. if (!this._debugLayer) {
  62509. this._debugLayer = new DebugLayer(this);
  62510. }
  62511. return this._debugLayer;
  62512. },
  62513. enumerable: true,
  62514. configurable: true
  62515. });
  62516. /**
  62517. * The debug layer (aka Inspector) is the go to tool in order to better understand
  62518. * what is happening in your scene
  62519. * @see http://doc.babylonjs.com/features/playground_debuglayer
  62520. */
  62521. var DebugLayer = /** @class */ (function () {
  62522. /**
  62523. * Instantiates a new debug layer.
  62524. * The debug layer (aka Inspector) is the go to tool in order to better understand
  62525. * what is happening in your scene
  62526. * @see http://doc.babylonjs.com/features/playground_debuglayer
  62527. * @param scene Defines the scene to inspect
  62528. */
  62529. function DebugLayer(scene) {
  62530. var _this = this;
  62531. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62532. /**
  62533. * Observable triggered when a property is changed through the inspector.
  62534. */
  62535. this.onPropertyChangedObservable = new BABYLON.Observable();
  62536. this._scene = scene;
  62537. this._scene.onDisposeObservable.add(function () {
  62538. // Debug layer
  62539. if (_this._scene._debugLayer) {
  62540. _this._scene._debugLayer.hide();
  62541. }
  62542. });
  62543. }
  62544. /** Creates the inspector window. */
  62545. DebugLayer.prototype._createInspector = function (config) {
  62546. if (config === void 0) { config = {}; }
  62547. var popup = config.popup || false;
  62548. var initialTab = config.initialTab || 0;
  62549. var parentElement = config.parentElement || null;
  62550. if (!this._inspector) {
  62551. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62552. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62553. } // else nothing to do as instance is already created
  62554. };
  62555. /**
  62556. * Get if the inspector is visible or not.
  62557. * @returns true if visible otherwise, false
  62558. */
  62559. DebugLayer.prototype.isVisible = function () {
  62560. if (!this._inspector) {
  62561. return false;
  62562. }
  62563. return true;
  62564. };
  62565. /**
  62566. * Hide the inspector and close its window.
  62567. */
  62568. DebugLayer.prototype.hide = function () {
  62569. if (this._inspector) {
  62570. try {
  62571. this._inspector.dispose();
  62572. }
  62573. catch (e) {
  62574. // If the inspector has been removed directly from the inspector tool
  62575. }
  62576. this.onPropertyChangedObservable.clear();
  62577. this._inspector = null;
  62578. }
  62579. };
  62580. /**
  62581. *
  62582. * Launch the debugLayer.
  62583. *
  62584. * initialTab:
  62585. * | Value | Tab Name |
  62586. * | --- | --- |
  62587. * | 0 | Scene |
  62588. * | 1 | Console |
  62589. * | 2 | Stats |
  62590. * | 3 | Textures |
  62591. * | 4 | Mesh |
  62592. * | 5 | Light |
  62593. * | 6 | Material |
  62594. * | 7 | GLTF |
  62595. * | 8 | GUI |
  62596. * | 9 | Physics |
  62597. * | 10 | Camera |
  62598. * | 11 | Audio |
  62599. *
  62600. * @param config Define the configuration of the inspector
  62601. */
  62602. DebugLayer.prototype.show = function (config) {
  62603. if (config === void 0) { config = {}; }
  62604. if (typeof this.BJSINSPECTOR == 'undefined') {
  62605. // Load inspector and add it to the DOM
  62606. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62607. }
  62608. else {
  62609. // Otherwise creates the inspector
  62610. this._createInspector(config);
  62611. }
  62612. };
  62613. /**
  62614. * Gets the active tab
  62615. * @return the index of the active tab or -1 if the inspector is hidden
  62616. */
  62617. DebugLayer.prototype.getActiveTab = function () {
  62618. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  62619. };
  62620. /**
  62621. * Define the url to get the inspector script from.
  62622. * By default it uses the babylonjs CDN.
  62623. * @ignoreNaming
  62624. */
  62625. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62626. return DebugLayer;
  62627. }());
  62628. BABYLON.DebugLayer = DebugLayer;
  62629. })(BABYLON || (BABYLON = {}));
  62630. //# sourceMappingURL=babylon.debugLayer.js.map
  62631. var BABYLON;
  62632. (function (BABYLON) {
  62633. var Debug;
  62634. (function (Debug) {
  62635. /**
  62636. * Used to show the physics impostor around the specific mesh
  62637. */
  62638. var PhysicsViewer = /** @class */ (function () {
  62639. /**
  62640. * Creates a new PhysicsViewer
  62641. * @param scene defines the hosting scene
  62642. */
  62643. function PhysicsViewer(scene) {
  62644. /** @hidden */
  62645. this._impostors = [];
  62646. /** @hidden */
  62647. this._meshes = [];
  62648. /** @hidden */
  62649. this._numMeshes = 0;
  62650. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62651. var physicEngine = this._scene.getPhysicsEngine();
  62652. if (physicEngine) {
  62653. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  62654. }
  62655. }
  62656. /** @hidden */
  62657. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62658. var plugin = this._physicsEnginePlugin;
  62659. for (var i = 0; i < this._numMeshes; i++) {
  62660. var impostor = this._impostors[i];
  62661. if (!impostor) {
  62662. continue;
  62663. }
  62664. if (impostor.isDisposed) {
  62665. this.hideImpostor(this._impostors[i--]);
  62666. }
  62667. else {
  62668. var mesh = this._meshes[i];
  62669. if (mesh && plugin) {
  62670. plugin.syncMeshWithImpostor(mesh, impostor);
  62671. }
  62672. }
  62673. }
  62674. };
  62675. /**
  62676. * Renders a specified physic impostor
  62677. * @param impostor defines the impostor to render
  62678. */
  62679. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62680. if (!this._scene) {
  62681. return;
  62682. }
  62683. for (var i = 0; i < this._numMeshes; i++) {
  62684. if (this._impostors[i] == impostor) {
  62685. return;
  62686. }
  62687. }
  62688. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62689. if (debugMesh) {
  62690. this._impostors[this._numMeshes] = impostor;
  62691. this._meshes[this._numMeshes] = debugMesh;
  62692. if (this._numMeshes === 0) {
  62693. this._renderFunction = this._updateDebugMeshes.bind(this);
  62694. this._scene.registerBeforeRender(this._renderFunction);
  62695. }
  62696. this._numMeshes++;
  62697. }
  62698. };
  62699. /**
  62700. * Hides a specified physic impostor
  62701. * @param impostor defines the impostor to hide
  62702. */
  62703. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62704. if (!impostor || !this._scene) {
  62705. return;
  62706. }
  62707. var removed = false;
  62708. for (var i = 0; i < this._numMeshes; i++) {
  62709. if (this._impostors[i] == impostor) {
  62710. var mesh = this._meshes[i];
  62711. if (!mesh) {
  62712. continue;
  62713. }
  62714. this._scene.removeMesh(mesh);
  62715. mesh.dispose();
  62716. this._numMeshes--;
  62717. if (this._numMeshes > 0) {
  62718. this._meshes[i] = this._meshes[this._numMeshes];
  62719. this._impostors[i] = this._impostors[this._numMeshes];
  62720. this._meshes[this._numMeshes] = null;
  62721. this._impostors[this._numMeshes] = null;
  62722. }
  62723. else {
  62724. this._meshes[0] = null;
  62725. this._impostors[0] = null;
  62726. }
  62727. removed = true;
  62728. break;
  62729. }
  62730. }
  62731. if (removed && this._numMeshes === 0) {
  62732. this._scene.unregisterBeforeRender(this._renderFunction);
  62733. }
  62734. };
  62735. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  62736. if (!this._debugMaterial) {
  62737. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  62738. this._debugMaterial.wireframe = true;
  62739. }
  62740. return this._debugMaterial;
  62741. };
  62742. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  62743. if (!this._debugBoxMesh) {
  62744. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  62745. this._debugBoxMesh.renderingGroupId = 1;
  62746. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62747. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  62748. scene.removeMesh(this._debugBoxMesh);
  62749. }
  62750. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  62751. };
  62752. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  62753. if (!this._debugSphereMesh) {
  62754. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  62755. this._debugSphereMesh.renderingGroupId = 1;
  62756. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62757. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  62758. scene.removeMesh(this._debugSphereMesh);
  62759. }
  62760. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  62761. };
  62762. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  62763. var mesh = null;
  62764. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  62765. mesh = this._getDebugBoxMesh(scene);
  62766. impostor.getBoxSizeToRef(mesh.scaling);
  62767. }
  62768. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  62769. mesh = this._getDebugSphereMesh(scene);
  62770. var radius = impostor.getRadius();
  62771. mesh.scaling.x = radius * 2;
  62772. mesh.scaling.y = radius * 2;
  62773. mesh.scaling.z = radius * 2;
  62774. }
  62775. return mesh;
  62776. };
  62777. /** Releases all resources */
  62778. PhysicsViewer.prototype.dispose = function () {
  62779. for (var i = 0; i < this._numMeshes; i++) {
  62780. this.hideImpostor(this._impostors[i]);
  62781. }
  62782. if (this._debugBoxMesh) {
  62783. this._debugBoxMesh.dispose();
  62784. }
  62785. if (this._debugSphereMesh) {
  62786. this._debugSphereMesh.dispose();
  62787. }
  62788. if (this._debugMaterial) {
  62789. this._debugMaterial.dispose();
  62790. }
  62791. this._impostors.length = 0;
  62792. this._scene = null;
  62793. this._physicsEnginePlugin = null;
  62794. };
  62795. return PhysicsViewer;
  62796. }());
  62797. Debug.PhysicsViewer = PhysicsViewer;
  62798. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62799. })(BABYLON || (BABYLON = {}));
  62800. //# sourceMappingURL=babylon.physicsViewer.js.map
  62801. var BABYLON;
  62802. (function (BABYLON) {
  62803. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  62804. get: function () {
  62805. return this._forceShowBoundingBoxes || false;
  62806. },
  62807. set: function (value) {
  62808. this._forceShowBoundingBoxes = value;
  62809. // Lazyly creates a BB renderer if needed.
  62810. if (value) {
  62811. this.getBoundingBoxRenderer();
  62812. }
  62813. },
  62814. enumerable: true,
  62815. configurable: true
  62816. });
  62817. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  62818. if (!this._boundingBoxRenderer) {
  62819. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  62820. }
  62821. return this._boundingBoxRenderer;
  62822. };
  62823. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  62824. get: function () {
  62825. return this._showBoundingBox || false;
  62826. },
  62827. set: function (value) {
  62828. this._showBoundingBox = value;
  62829. // Lazyly creates a BB renderer if needed.
  62830. if (value) {
  62831. this.getScene().getBoundingBoxRenderer();
  62832. }
  62833. },
  62834. enumerable: true,
  62835. configurable: true
  62836. });
  62837. /**
  62838. * Component responsible of rendering the bounding box of the meshes in a scene.
  62839. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  62840. */
  62841. var BoundingBoxRenderer = /** @class */ (function () {
  62842. /**
  62843. * Instantiates a new bounding box renderer in a scene.
  62844. * @param scene the scene the renderer renders in
  62845. */
  62846. function BoundingBoxRenderer(scene) {
  62847. /**
  62848. * The component name helpfull to identify the component in the list of scene components.
  62849. */
  62850. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  62851. /**
  62852. * Color of the bounding box lines placed in front of an object
  62853. */
  62854. this.frontColor = new BABYLON.Color3(1, 1, 1);
  62855. /**
  62856. * Color of the bounding box lines placed behind an object
  62857. */
  62858. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  62859. /**
  62860. * Defines if the renderer should show the back lines or not
  62861. */
  62862. this.showBackLines = true;
  62863. /**
  62864. * @hidden
  62865. */
  62866. this.renderList = new BABYLON.SmartArray(32);
  62867. this._vertexBuffers = {};
  62868. this.scene = scene;
  62869. scene._addComponent(this);
  62870. }
  62871. /**
  62872. * Registers the component in a given scene
  62873. */
  62874. BoundingBoxRenderer.prototype.register = function () {
  62875. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  62876. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  62877. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  62878. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  62879. };
  62880. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  62881. if (mesh.showSubMeshesBoundingBox) {
  62882. var boundingInfo = subMesh.getBoundingInfo();
  62883. if (boundingInfo !== null && boundingInfo !== undefined) {
  62884. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62885. this.renderList.push(boundingInfo.boundingBox);
  62886. }
  62887. }
  62888. };
  62889. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  62890. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  62891. var boundingInfo = sourceMesh.getBoundingInfo();
  62892. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62893. this.renderList.push(boundingInfo.boundingBox);
  62894. }
  62895. };
  62896. BoundingBoxRenderer.prototype._prepareRessources = function () {
  62897. if (this._colorShader) {
  62898. return;
  62899. }
  62900. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  62901. attributes: [BABYLON.VertexBuffer.PositionKind],
  62902. uniforms: ["world", "viewProjection", "color"]
  62903. });
  62904. var engine = this.scene.getEngine();
  62905. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  62906. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  62907. this._createIndexBuffer();
  62908. };
  62909. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  62910. var engine = this.scene.getEngine();
  62911. 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]);
  62912. };
  62913. /**
  62914. * Rebuilds the elements related to this component in case of
  62915. * context lost for instance.
  62916. */
  62917. BoundingBoxRenderer.prototype.rebuild = function () {
  62918. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62919. if (vb) {
  62920. vb._rebuild();
  62921. }
  62922. this._createIndexBuffer();
  62923. };
  62924. /**
  62925. * @hidden
  62926. */
  62927. BoundingBoxRenderer.prototype.reset = function () {
  62928. this.renderList.reset();
  62929. };
  62930. /**
  62931. * Render the bounding boxes of a specific rendering group
  62932. * @param renderingGroupId defines the rendering group to render
  62933. */
  62934. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  62935. if (this.renderList.length === 0) {
  62936. return;
  62937. }
  62938. this._prepareRessources();
  62939. if (!this._colorShader.isReady()) {
  62940. return;
  62941. }
  62942. var engine = this.scene.getEngine();
  62943. engine.setDepthWrite(false);
  62944. this._colorShader._preBind();
  62945. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  62946. var boundingBox = this.renderList.data[boundingBoxIndex];
  62947. if (boundingBox._tag !== renderingGroupId) {
  62948. continue;
  62949. }
  62950. var min = boundingBox.minimum;
  62951. var max = boundingBox.maximum;
  62952. var diff = max.subtract(min);
  62953. var median = min.add(diff.scale(0.5));
  62954. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62955. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62956. .multiply(boundingBox.getWorldMatrix());
  62957. // VBOs
  62958. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62959. if (this.showBackLines) {
  62960. // Back
  62961. engine.setDepthFunctionToGreaterOrEqual();
  62962. this.scene.resetCachedMaterial();
  62963. this._colorShader.setColor4("color", this.backColor.toColor4());
  62964. this._colorShader.bind(worldMatrix);
  62965. // Draw order
  62966. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62967. }
  62968. // Front
  62969. engine.setDepthFunctionToLess();
  62970. this.scene.resetCachedMaterial();
  62971. this._colorShader.setColor4("color", this.frontColor.toColor4());
  62972. this._colorShader.bind(worldMatrix);
  62973. // Draw order
  62974. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62975. }
  62976. this._colorShader.unbind();
  62977. engine.setDepthFunctionToLessOrEqual();
  62978. engine.setDepthWrite(true);
  62979. };
  62980. /**
  62981. * In case of occlusion queries, we can render the occlusion bounding box through this method
  62982. * @param mesh Define the mesh to render the occlusion bounding box for
  62983. */
  62984. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  62985. this._prepareRessources();
  62986. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  62987. return;
  62988. }
  62989. var engine = this.scene.getEngine();
  62990. engine.setDepthWrite(false);
  62991. engine.setColorWrite(false);
  62992. this._colorShader._preBind();
  62993. var boundingBox = mesh._boundingInfo.boundingBox;
  62994. var min = boundingBox.minimum;
  62995. var max = boundingBox.maximum;
  62996. var diff = max.subtract(min);
  62997. var median = min.add(diff.scale(0.5));
  62998. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62999. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63000. .multiply(boundingBox.getWorldMatrix());
  63001. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63002. engine.setDepthFunctionToLess();
  63003. this.scene.resetCachedMaterial();
  63004. this._colorShader.bind(worldMatrix);
  63005. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63006. this._colorShader.unbind();
  63007. engine.setDepthFunctionToLessOrEqual();
  63008. engine.setDepthWrite(true);
  63009. engine.setColorWrite(true);
  63010. };
  63011. /**
  63012. * Dispose and release the resources attached to this renderer.
  63013. */
  63014. BoundingBoxRenderer.prototype.dispose = function () {
  63015. if (!this._colorShader) {
  63016. return;
  63017. }
  63018. this.renderList.dispose();
  63019. this._colorShader.dispose();
  63020. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63021. if (buffer) {
  63022. buffer.dispose();
  63023. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63024. }
  63025. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  63026. };
  63027. return BoundingBoxRenderer;
  63028. }());
  63029. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  63030. })(BABYLON || (BABYLON = {}));
  63031. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  63032. var BABYLON;
  63033. (function (BABYLON) {
  63034. BABYLON.Engine.prototype.createTransformFeedback = function () {
  63035. return this._gl.createTransformFeedback();
  63036. };
  63037. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  63038. this._gl.deleteTransformFeedback(value);
  63039. };
  63040. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  63041. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  63042. };
  63043. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  63044. if (usePoints === void 0) { usePoints = true; }
  63045. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  63046. };
  63047. BABYLON.Engine.prototype.endTransformFeedback = function () {
  63048. this._gl.endTransformFeedback();
  63049. };
  63050. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  63051. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  63052. };
  63053. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  63054. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  63055. };
  63056. })(BABYLON || (BABYLON = {}));
  63057. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  63058. var BABYLON;
  63059. (function (BABYLON) {
  63060. /**
  63061. * This represents a GPU particle system in Babylon
  63062. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  63063. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  63064. */
  63065. var GPUParticleSystem = /** @class */ (function (_super) {
  63066. __extends(GPUParticleSystem, _super);
  63067. /**
  63068. * Instantiates a GPU particle system.
  63069. * 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.
  63070. * @param name The name of the particle system
  63071. * @param options The options used to create the system
  63072. * @param scene The scene the particle system belongs to
  63073. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  63074. */
  63075. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  63076. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  63077. var _this = _super.call(this, name) || this;
  63078. /**
  63079. * The layer mask we are rendering the particles through.
  63080. */
  63081. _this.layerMask = 0x0FFFFFFF;
  63082. _this._accumulatedCount = 0;
  63083. _this._targetIndex = 0;
  63084. _this._currentRenderId = -1;
  63085. _this._started = false;
  63086. _this._stopped = false;
  63087. _this._timeDelta = 0;
  63088. _this._attributesStrideSize = 21;
  63089. _this._actualFrame = 0;
  63090. _this._rawTextureWidth = 256;
  63091. /**
  63092. * An event triggered when the system is disposed.
  63093. */
  63094. _this.onDisposeObservable = new BABYLON.Observable();
  63095. /**
  63096. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  63097. * to override the particles.
  63098. */
  63099. _this.forceDepthWrite = false;
  63100. _this._preWarmDone = false;
  63101. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63102. // Setup the default processing configuration to the scene.
  63103. _this._attachImageProcessingConfiguration(null);
  63104. _this._engine = _this._scene.getEngine();
  63105. if (!options.randomTextureSize) {
  63106. delete options.randomTextureSize;
  63107. }
  63108. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  63109. var optionsAsNumber = options;
  63110. if (isFinite(optionsAsNumber)) {
  63111. fullOptions.capacity = optionsAsNumber;
  63112. }
  63113. _this._capacity = fullOptions.capacity;
  63114. _this._activeCount = fullOptions.capacity;
  63115. _this._currentActiveCount = 0;
  63116. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  63117. _this._scene.particleSystems.push(_this);
  63118. _this._updateEffectOptions = {
  63119. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  63120. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  63121. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  63122. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  63123. uniformBuffersNames: [],
  63124. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  63125. defines: "",
  63126. fallbacks: null,
  63127. onCompiled: null,
  63128. onError: null,
  63129. indexParameters: null,
  63130. maxSimultaneousLights: 0,
  63131. transformFeedbackVaryings: []
  63132. };
  63133. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  63134. // Random data
  63135. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  63136. var d = [];
  63137. for (var i = 0; i < maxTextureSize; ++i) {
  63138. d.push(Math.random());
  63139. d.push(Math.random());
  63140. d.push(Math.random());
  63141. d.push(Math.random());
  63142. }
  63143. _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);
  63144. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63145. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63146. d = [];
  63147. for (var i = 0; i < maxTextureSize; ++i) {
  63148. d.push(Math.random());
  63149. d.push(Math.random());
  63150. d.push(Math.random());
  63151. d.push(Math.random());
  63152. }
  63153. _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);
  63154. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63155. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63156. _this._randomTextureSize = maxTextureSize;
  63157. return _this;
  63158. }
  63159. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  63160. /**
  63161. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  63162. */
  63163. get: function () {
  63164. if (!BABYLON.Engine.LastCreatedEngine) {
  63165. return false;
  63166. }
  63167. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  63168. },
  63169. enumerable: true,
  63170. configurable: true
  63171. });
  63172. /**
  63173. * Gets the maximum number of particles active at the same time.
  63174. * @returns The max number of active particles.
  63175. */
  63176. GPUParticleSystem.prototype.getCapacity = function () {
  63177. return this._capacity;
  63178. };
  63179. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  63180. /**
  63181. * Gets or set the number of active particles
  63182. */
  63183. get: function () {
  63184. return this._activeCount;
  63185. },
  63186. set: function (value) {
  63187. this._activeCount = Math.min(value, this._capacity);
  63188. },
  63189. enumerable: true,
  63190. configurable: true
  63191. });
  63192. /**
  63193. * Is this system ready to be used/rendered
  63194. * @return true if the system is ready
  63195. */
  63196. GPUParticleSystem.prototype.isReady = function () {
  63197. if (!this._updateEffect) {
  63198. this._recreateUpdateEffect();
  63199. this._recreateRenderEffect();
  63200. return false;
  63201. }
  63202. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  63203. return false;
  63204. }
  63205. return true;
  63206. };
  63207. /**
  63208. * Gets if the system has been started. (Note: this will still be true after stop is called)
  63209. * @returns True if it has been started, otherwise false.
  63210. */
  63211. GPUParticleSystem.prototype.isStarted = function () {
  63212. return this._started;
  63213. };
  63214. /**
  63215. * Starts the particle system and begins to emit
  63216. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  63217. */
  63218. GPUParticleSystem.prototype.start = function (delay) {
  63219. var _this = this;
  63220. if (delay === void 0) { delay = this.startDelay; }
  63221. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  63222. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  63223. }
  63224. if (delay) {
  63225. setTimeout(function () {
  63226. _this.start(0);
  63227. }, delay);
  63228. return;
  63229. }
  63230. this._started = true;
  63231. this._stopped = false;
  63232. this._preWarmDone = false;
  63233. // Animations
  63234. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  63235. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  63236. }
  63237. };
  63238. /**
  63239. * Stops the particle system.
  63240. */
  63241. GPUParticleSystem.prototype.stop = function () {
  63242. this._stopped = true;
  63243. };
  63244. /**
  63245. * Remove all active particles
  63246. */
  63247. GPUParticleSystem.prototype.reset = function () {
  63248. this._releaseBuffers();
  63249. this._releaseVAOs();
  63250. this._currentActiveCount = 0;
  63251. this._targetIndex = 0;
  63252. };
  63253. /**
  63254. * Returns the string "GPUParticleSystem"
  63255. * @returns a string containing the class name
  63256. */
  63257. GPUParticleSystem.prototype.getClassName = function () {
  63258. return "GPUParticleSystem";
  63259. };
  63260. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  63261. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  63262. this._releaseBuffers();
  63263. return this;
  63264. };
  63265. /**
  63266. * Adds a new color gradient
  63267. * @param gradient defines the gradient to use (between 0 and 1)
  63268. * @param color1 defines the color to affect to the specified gradient
  63269. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  63270. * @returns the current particle system
  63271. */
  63272. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  63273. if (!this._colorGradients) {
  63274. this._colorGradients = [];
  63275. }
  63276. var colorGradient = new BABYLON.ColorGradient();
  63277. colorGradient.gradient = gradient;
  63278. colorGradient.color1 = color1;
  63279. this._colorGradients.push(colorGradient);
  63280. this._colorGradients.sort(function (a, b) {
  63281. if (a.gradient < b.gradient) {
  63282. return -1;
  63283. }
  63284. else if (a.gradient > b.gradient) {
  63285. return 1;
  63286. }
  63287. return 0;
  63288. });
  63289. if (this._colorGradientsTexture) {
  63290. this._colorGradientsTexture.dispose();
  63291. this._colorGradientsTexture = null;
  63292. }
  63293. this._releaseBuffers();
  63294. return this;
  63295. };
  63296. /**
  63297. * Remove a specific color gradient
  63298. * @param gradient defines the gradient to remove
  63299. * @returns the current particle system
  63300. */
  63301. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  63302. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  63303. this._colorGradientsTexture = null;
  63304. return this;
  63305. };
  63306. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  63307. var valueGradient = new BABYLON.FactorGradient();
  63308. valueGradient.gradient = gradient;
  63309. valueGradient.factor1 = factor;
  63310. factorGradients.push(valueGradient);
  63311. factorGradients.sort(function (a, b) {
  63312. if (a.gradient < b.gradient) {
  63313. return -1;
  63314. }
  63315. else if (a.gradient > b.gradient) {
  63316. return 1;
  63317. }
  63318. return 0;
  63319. });
  63320. this._releaseBuffers();
  63321. };
  63322. /**
  63323. * Adds a new size gradient
  63324. * @param gradient defines the gradient to use (between 0 and 1)
  63325. * @param factor defines the size factor to affect to the specified gradient
  63326. * @returns the current particle system
  63327. */
  63328. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  63329. if (!this._sizeGradients) {
  63330. this._sizeGradients = [];
  63331. }
  63332. this._addFactorGradient(this._sizeGradients, gradient, factor);
  63333. if (this._sizeGradientsTexture) {
  63334. this._sizeGradientsTexture.dispose();
  63335. this._sizeGradientsTexture = null;
  63336. }
  63337. this._releaseBuffers();
  63338. return this;
  63339. };
  63340. /**
  63341. * Remove a specific size gradient
  63342. * @param gradient defines the gradient to remove
  63343. * @returns the current particle system
  63344. */
  63345. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  63346. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  63347. this._sizeGradientsTexture = null;
  63348. return this;
  63349. };
  63350. /**
  63351. * Adds a new angular speed gradient
  63352. * @param gradient defines the gradient to use (between 0 and 1)
  63353. * @param factor defines the angular speed to affect to the specified gradient
  63354. * @returns the current particle system
  63355. */
  63356. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  63357. if (!this._angularSpeedGradients) {
  63358. this._angularSpeedGradients = [];
  63359. }
  63360. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  63361. if (this._angularSpeedGradientsTexture) {
  63362. this._angularSpeedGradientsTexture.dispose();
  63363. this._angularSpeedGradientsTexture = null;
  63364. }
  63365. this._releaseBuffers();
  63366. return this;
  63367. };
  63368. /**
  63369. * Remove a specific angular speed gradient
  63370. * @param gradient defines the gradient to remove
  63371. * @returns the current particle system
  63372. */
  63373. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  63374. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  63375. this._angularSpeedGradientsTexture = null;
  63376. return this;
  63377. };
  63378. /**
  63379. * Adds a new velocity gradient
  63380. * @param gradient defines the gradient to use (between 0 and 1)
  63381. * @param factor defines the velocity to affect to the specified gradient
  63382. * @returns the current particle system
  63383. */
  63384. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  63385. if (!this._velocityGradients) {
  63386. this._velocityGradients = [];
  63387. }
  63388. this._addFactorGradient(this._velocityGradients, gradient, factor);
  63389. if (this._velocityGradientsTexture) {
  63390. this._velocityGradientsTexture.dispose();
  63391. this._velocityGradientsTexture = null;
  63392. }
  63393. this._releaseBuffers();
  63394. return this;
  63395. };
  63396. /**
  63397. * Remove a specific velocity gradient
  63398. * @param gradient defines the gradient to remove
  63399. * @returns the current particle system
  63400. */
  63401. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  63402. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  63403. this._velocityGradientsTexture = null;
  63404. return this;
  63405. };
  63406. /**
  63407. * Adds a new limit velocity gradient
  63408. * @param gradient defines the gradient to use (between 0 and 1)
  63409. * @param factor defines the limit velocity value to affect to the specified gradient
  63410. * @returns the current particle system
  63411. */
  63412. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  63413. if (!this._limitVelocityGradients) {
  63414. this._limitVelocityGradients = [];
  63415. }
  63416. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  63417. if (this._limitVelocityGradientsTexture) {
  63418. this._limitVelocityGradientsTexture.dispose();
  63419. this._limitVelocityGradientsTexture = null;
  63420. }
  63421. this._releaseBuffers();
  63422. return this;
  63423. };
  63424. /**
  63425. * Remove a specific limit velocity gradient
  63426. * @param gradient defines the gradient to remove
  63427. * @returns the current particle system
  63428. */
  63429. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  63430. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  63431. this._limitVelocityGradientsTexture = null;
  63432. return this;
  63433. };
  63434. /**
  63435. * Adds a new drag gradient
  63436. * @param gradient defines the gradient to use (between 0 and 1)
  63437. * @param factor defines the drag value to affect to the specified gradient
  63438. * @returns the current particle system
  63439. */
  63440. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  63441. if (!this._dragGradients) {
  63442. this._dragGradients = [];
  63443. }
  63444. this._addFactorGradient(this._dragGradients, gradient, factor);
  63445. if (this._dragGradientsTexture) {
  63446. this._dragGradientsTexture.dispose();
  63447. this._dragGradientsTexture = null;
  63448. }
  63449. this._releaseBuffers();
  63450. return this;
  63451. };
  63452. /**
  63453. * Remove a specific drag gradient
  63454. * @param gradient defines the gradient to remove
  63455. * @returns the current particle system
  63456. */
  63457. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  63458. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  63459. this._dragGradientsTexture = null;
  63460. return this;
  63461. };
  63462. /**
  63463. * Not supported by GPUParticleSystem
  63464. * @param gradient defines the gradient to use (between 0 and 1)
  63465. * @param factor defines the emit rate value to affect to the specified gradient
  63466. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63467. * @returns the current particle system
  63468. */
  63469. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  63470. // Do nothing as emit rate is not supported by GPUParticleSystem
  63471. return this;
  63472. };
  63473. /**
  63474. * Not supported by GPUParticleSystem
  63475. * @param gradient defines the gradient to remove
  63476. * @returns the current particle system
  63477. */
  63478. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  63479. // Do nothing as emit rate is not supported by GPUParticleSystem
  63480. return this;
  63481. };
  63482. /**
  63483. * Not supported by GPUParticleSystem
  63484. * @param gradient defines the gradient to use (between 0 and 1)
  63485. * @param factor defines the start size value to affect to the specified gradient
  63486. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63487. * @returns the current particle system
  63488. */
  63489. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  63490. // Do nothing as start size is not supported by GPUParticleSystem
  63491. return this;
  63492. };
  63493. /**
  63494. * Not supported by GPUParticleSystem
  63495. * @param gradient defines the gradient to remove
  63496. * @returns the current particle system
  63497. */
  63498. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  63499. // Do nothing as start size is not supported by GPUParticleSystem
  63500. return this;
  63501. };
  63502. /**
  63503. * Not supported by GPUParticleSystem
  63504. * @param gradient defines the gradient to use (between 0 and 1)
  63505. * @param min defines the color remap minimal range
  63506. * @param max defines the color remap maximal range
  63507. * @returns the current particle system
  63508. */
  63509. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  63510. // Do nothing as start size is not supported by GPUParticleSystem
  63511. return this;
  63512. };
  63513. /**
  63514. * Not supported by GPUParticleSystem
  63515. * @param gradient defines the gradient to remove
  63516. * @returns the current particle system
  63517. */
  63518. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  63519. // Do nothing as start size is not supported by GPUParticleSystem
  63520. return this;
  63521. };
  63522. /**
  63523. * Not supported by GPUParticleSystem
  63524. * @param gradient defines the gradient to use (between 0 and 1)
  63525. * @param min defines the alpha remap minimal range
  63526. * @param max defines the alpha remap maximal range
  63527. * @returns the current particle system
  63528. */
  63529. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  63530. // Do nothing as start size is not supported by GPUParticleSystem
  63531. return this;
  63532. };
  63533. /**
  63534. * Not supported by GPUParticleSystem
  63535. * @param gradient defines the gradient to remove
  63536. * @returns the current particle system
  63537. */
  63538. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  63539. // Do nothing as start size is not supported by GPUParticleSystem
  63540. return this;
  63541. };
  63542. /**
  63543. * Not supported by GPUParticleSystem
  63544. * @param gradient defines the gradient to use (between 0 and 1)
  63545. * @param color defines the color to affect to the specified gradient
  63546. * @returns the current particle system
  63547. */
  63548. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  63549. //Not supported by GPUParticleSystem
  63550. return this;
  63551. };
  63552. /**
  63553. * Not supported by GPUParticleSystem
  63554. * @param gradient defines the gradient to remove
  63555. * @returns the current particle system
  63556. */
  63557. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  63558. //Not supported by GPUParticleSystem
  63559. return this;
  63560. };
  63561. /**
  63562. * Not supported by GPUParticleSystem
  63563. * @returns the list of ramp gradients
  63564. */
  63565. GPUParticleSystem.prototype.getRampGradients = function () {
  63566. return null;
  63567. };
  63568. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  63569. /**
  63570. * Not supported by GPUParticleSystem
  63571. * Gets or sets a boolean indicating that ramp gradients must be used
  63572. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  63573. */
  63574. get: function () {
  63575. //Not supported by GPUParticleSystem
  63576. return false;
  63577. },
  63578. set: function (value) {
  63579. //Not supported by GPUParticleSystem
  63580. },
  63581. enumerable: true,
  63582. configurable: true
  63583. });
  63584. /**
  63585. * Not supported by GPUParticleSystem
  63586. * @param gradient defines the gradient to use (between 0 and 1)
  63587. * @param factor defines the life time factor to affect to the specified gradient
  63588. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63589. * @returns the current particle system
  63590. */
  63591. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  63592. //Not supported by GPUParticleSystem
  63593. return this;
  63594. };
  63595. /**
  63596. * Not supported by GPUParticleSystem
  63597. * @param gradient defines the gradient to remove
  63598. * @returns the current particle system
  63599. */
  63600. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  63601. //Not supported by GPUParticleSystem
  63602. return this;
  63603. };
  63604. GPUParticleSystem.prototype._reset = function () {
  63605. this._releaseBuffers();
  63606. };
  63607. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  63608. var updateVertexBuffers = {};
  63609. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  63610. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  63611. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  63612. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  63613. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  63614. var offset = 12;
  63615. if (!this._colorGradientsTexture) {
  63616. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  63617. offset += 4;
  63618. }
  63619. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  63620. offset += 3;
  63621. if (!this._isBillboardBased) {
  63622. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  63623. offset += 3;
  63624. }
  63625. if (this._angularSpeedGradientsTexture) {
  63626. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  63627. offset += 1;
  63628. }
  63629. else {
  63630. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  63631. offset += 2;
  63632. }
  63633. if (this._isAnimationSheetEnabled) {
  63634. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  63635. offset += 1;
  63636. if (this.spriteRandomStartCell) {
  63637. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  63638. offset += 1;
  63639. }
  63640. }
  63641. if (this.noiseTexture) {
  63642. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  63643. offset += 3;
  63644. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  63645. offset += 3;
  63646. }
  63647. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  63648. this._engine.bindArrayBuffer(null);
  63649. return vao;
  63650. };
  63651. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  63652. var renderVertexBuffers = {};
  63653. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  63654. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  63655. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  63656. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  63657. var offset = 12;
  63658. if (!this._colorGradientsTexture) {
  63659. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  63660. offset += 4;
  63661. }
  63662. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  63663. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  63664. }
  63665. offset += 3; // Direction
  63666. if (!this._isBillboardBased) {
  63667. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  63668. offset += 3;
  63669. }
  63670. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  63671. if (this._angularSpeedGradientsTexture) {
  63672. offset++;
  63673. }
  63674. else {
  63675. offset += 2;
  63676. }
  63677. if (this._isAnimationSheetEnabled) {
  63678. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  63679. offset += 1;
  63680. if (this.spriteRandomStartCell) {
  63681. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  63682. offset += 1;
  63683. }
  63684. }
  63685. if (this.noiseTexture) {
  63686. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  63687. offset += 3;
  63688. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  63689. offset += 3;
  63690. }
  63691. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  63692. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  63693. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  63694. this._engine.bindArrayBuffer(null);
  63695. return vao;
  63696. };
  63697. GPUParticleSystem.prototype._initialize = function (force) {
  63698. if (force === void 0) { force = false; }
  63699. if (this._buffer0 && !force) {
  63700. return;
  63701. }
  63702. var engine = this._scene.getEngine();
  63703. var data = new Array();
  63704. if (!this.isBillboardBased) {
  63705. this._attributesStrideSize += 3;
  63706. }
  63707. if (this._colorGradientsTexture) {
  63708. this._attributesStrideSize -= 4;
  63709. }
  63710. if (this._angularSpeedGradientsTexture) {
  63711. this._attributesStrideSize -= 1;
  63712. }
  63713. if (this._isAnimationSheetEnabled) {
  63714. this._attributesStrideSize += 1;
  63715. if (this.spriteRandomStartCell) {
  63716. this._attributesStrideSize += 1;
  63717. }
  63718. }
  63719. if (this.noiseTexture) {
  63720. this._attributesStrideSize += 6;
  63721. }
  63722. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  63723. // position
  63724. data.push(0.0);
  63725. data.push(0.0);
  63726. data.push(0.0);
  63727. // Age and life
  63728. data.push(0.0); // create the particle as a dead one to create a new one at start
  63729. data.push(0.0);
  63730. // Seed
  63731. data.push(Math.random());
  63732. data.push(Math.random());
  63733. data.push(Math.random());
  63734. data.push(Math.random());
  63735. // Size
  63736. data.push(0.0);
  63737. data.push(0.0);
  63738. data.push(0.0);
  63739. if (!this._colorGradientsTexture) {
  63740. // color
  63741. data.push(0.0);
  63742. data.push(0.0);
  63743. data.push(0.0);
  63744. data.push(0.0);
  63745. }
  63746. // direction
  63747. data.push(0.0);
  63748. data.push(0.0);
  63749. data.push(0.0);
  63750. if (!this.isBillboardBased) {
  63751. // initialDirection
  63752. data.push(0.0);
  63753. data.push(0.0);
  63754. data.push(0.0);
  63755. }
  63756. // angle
  63757. data.push(0.0);
  63758. if (!this._angularSpeedGradientsTexture) {
  63759. data.push(0.0);
  63760. }
  63761. if (this._isAnimationSheetEnabled) {
  63762. data.push(0.0);
  63763. if (this.spriteRandomStartCell) {
  63764. data.push(0.0);
  63765. }
  63766. }
  63767. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  63768. data.push(Math.random());
  63769. data.push(Math.random());
  63770. data.push(Math.random());
  63771. data.push(Math.random());
  63772. data.push(Math.random());
  63773. data.push(Math.random());
  63774. }
  63775. }
  63776. // Sprite data
  63777. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  63778. -0.5, 0.5, 0, 1,
  63779. -0.5, -0.5, 0, 0,
  63780. 0.5, -0.5, 1, 0]);
  63781. // Buffers
  63782. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63783. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63784. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  63785. // Update VAO
  63786. this._updateVAO = [];
  63787. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  63788. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  63789. // Render VAO
  63790. this._renderVAO = [];
  63791. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  63792. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  63793. // Links
  63794. this._sourceBuffer = this._buffer0;
  63795. this._targetBuffer = this._buffer1;
  63796. };
  63797. /** @hidden */
  63798. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  63799. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  63800. if (this._isBillboardBased) {
  63801. defines += "\n#define BILLBOARD";
  63802. }
  63803. if (this._colorGradientsTexture) {
  63804. defines += "\n#define COLORGRADIENTS";
  63805. }
  63806. if (this._sizeGradientsTexture) {
  63807. defines += "\n#define SIZEGRADIENTS";
  63808. }
  63809. if (this._angularSpeedGradientsTexture) {
  63810. defines += "\n#define ANGULARSPEEDGRADIENTS";
  63811. }
  63812. if (this._velocityGradientsTexture) {
  63813. defines += "\n#define VELOCITYGRADIENTS";
  63814. }
  63815. if (this._limitVelocityGradientsTexture) {
  63816. defines += "\n#define LIMITVELOCITYGRADIENTS";
  63817. }
  63818. if (this._dragGradientsTexture) {
  63819. defines += "\n#define DRAGGRADIENTS";
  63820. }
  63821. if (this.isAnimationSheetEnabled) {
  63822. defines += "\n#define ANIMATESHEET";
  63823. if (this.spriteRandomStartCell) {
  63824. defines += "\n#define ANIMATESHEETRANDOMSTART";
  63825. }
  63826. }
  63827. if (this.noiseTexture) {
  63828. defines += "\n#define NOISE";
  63829. }
  63830. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  63831. return;
  63832. }
  63833. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  63834. if (!this._colorGradientsTexture) {
  63835. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  63836. }
  63837. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  63838. if (!this._isBillboardBased) {
  63839. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  63840. }
  63841. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  63842. if (this.isAnimationSheetEnabled) {
  63843. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  63844. if (this.spriteRandomStartCell) {
  63845. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  63846. }
  63847. }
  63848. if (this.noiseTexture) {
  63849. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  63850. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  63851. }
  63852. this._updateEffectOptions.defines = defines;
  63853. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  63854. };
  63855. /** @hidden */
  63856. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  63857. var defines = "";
  63858. if (this._scene.clipPlane) {
  63859. defines = "\n#define CLIPPLANE";
  63860. }
  63861. if (this._scene.clipPlane2) {
  63862. defines = "\n#define CLIPPLANE2";
  63863. }
  63864. if (this._scene.clipPlane3) {
  63865. defines = "\n#define CLIPPLANE3";
  63866. }
  63867. if (this._scene.clipPlane4) {
  63868. defines = "\n#define CLIPPLANE4";
  63869. }
  63870. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  63871. defines = "\n#define BLENDMULTIPLYMODE";
  63872. }
  63873. if (this._isBillboardBased) {
  63874. defines += "\n#define BILLBOARD";
  63875. switch (this.billboardMode) {
  63876. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  63877. defines += "\n#define BILLBOARDY";
  63878. break;
  63879. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  63880. defines += "\n#define BILLBOARDSTRETCHED";
  63881. break;
  63882. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  63883. default:
  63884. break;
  63885. }
  63886. }
  63887. if (this._colorGradientsTexture) {
  63888. defines += "\n#define COLORGRADIENTS";
  63889. }
  63890. if (this.isAnimationSheetEnabled) {
  63891. defines += "\n#define ANIMATESHEET";
  63892. }
  63893. if (this._imageProcessingConfiguration) {
  63894. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  63895. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  63896. }
  63897. if (this._renderEffect && this._renderEffect.defines === defines) {
  63898. return;
  63899. }
  63900. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  63901. var samplers = ["textureSampler", "colorGradientSampler"];
  63902. if (BABYLON.ImageProcessingConfiguration) {
  63903. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  63904. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  63905. }
  63906. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  63907. };
  63908. /**
  63909. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  63910. * @param preWarm defines if we are in the pre-warmimg phase
  63911. */
  63912. GPUParticleSystem.prototype.animate = function (preWarm) {
  63913. if (preWarm === void 0) { preWarm = false; }
  63914. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  63915. this._actualFrame += this._timeDelta;
  63916. if (!this._stopped) {
  63917. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  63918. this.stop();
  63919. }
  63920. }
  63921. };
  63922. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  63923. var texture = this[textureName];
  63924. if (!factorGradients || !factorGradients.length || texture) {
  63925. return;
  63926. }
  63927. var data = new Float32Array(this._rawTextureWidth);
  63928. for (var x = 0; x < this._rawTextureWidth; x++) {
  63929. var ratio = x / this._rawTextureWidth;
  63930. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  63931. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  63932. });
  63933. }
  63934. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63935. };
  63936. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  63937. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  63938. };
  63939. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  63940. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  63941. };
  63942. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  63943. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  63944. };
  63945. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  63946. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  63947. };
  63948. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  63949. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  63950. };
  63951. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  63952. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  63953. return;
  63954. }
  63955. var data = new Uint8Array(this._rawTextureWidth * 4);
  63956. var tmpColor = BABYLON.Tmp.Color4[0];
  63957. for (var x = 0; x < this._rawTextureWidth; x++) {
  63958. var ratio = x / this._rawTextureWidth;
  63959. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  63960. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  63961. data[x * 4] = tmpColor.r * 255;
  63962. data[x * 4 + 1] = tmpColor.g * 255;
  63963. data[x * 4 + 2] = tmpColor.b * 255;
  63964. data[x * 4 + 3] = tmpColor.a * 255;
  63965. });
  63966. }
  63967. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63968. };
  63969. /**
  63970. * Renders the particle system in its current state
  63971. * @param preWarm defines if the system should only update the particles but not render them
  63972. * @returns the current number of particles
  63973. */
  63974. GPUParticleSystem.prototype.render = function (preWarm) {
  63975. if (preWarm === void 0) { preWarm = false; }
  63976. if (!this._started) {
  63977. return 0;
  63978. }
  63979. this._createColorGradientTexture();
  63980. this._createSizeGradientTexture();
  63981. this._createAngularSpeedGradientTexture();
  63982. this._createVelocityGradientTexture();
  63983. this._createLimitVelocityGradientTexture();
  63984. this._createDragGradientTexture();
  63985. this._recreateUpdateEffect();
  63986. this._recreateRenderEffect();
  63987. if (!this.isReady()) {
  63988. return 0;
  63989. }
  63990. if (!preWarm) {
  63991. if (!this._preWarmDone && this.preWarmCycles) {
  63992. for (var index = 0; index < this.preWarmCycles; index++) {
  63993. this.animate(true);
  63994. this.render(true);
  63995. }
  63996. this._preWarmDone = true;
  63997. }
  63998. if (this._currentRenderId === this._scene.getRenderId()) {
  63999. return 0;
  64000. }
  64001. this._currentRenderId = this._scene.getRenderId();
  64002. }
  64003. // Get everything ready to render
  64004. this._initialize();
  64005. this._accumulatedCount += this.emitRate * this._timeDelta;
  64006. if (this._accumulatedCount > 1) {
  64007. var intPart = this._accumulatedCount | 0;
  64008. this._accumulatedCount -= intPart;
  64009. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  64010. }
  64011. if (!this._currentActiveCount) {
  64012. return 0;
  64013. }
  64014. // Enable update effect
  64015. this._engine.enableEffect(this._updateEffect);
  64016. this._engine.setState(false);
  64017. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  64018. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  64019. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  64020. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  64021. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  64022. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  64023. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  64024. if (!this._colorGradientsTexture) {
  64025. this._updateEffect.setDirectColor4("color1", this.color1);
  64026. this._updateEffect.setDirectColor4("color2", this.color2);
  64027. }
  64028. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  64029. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  64030. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  64031. this._updateEffect.setVector3("gravity", this.gravity);
  64032. if (this._sizeGradientsTexture) {
  64033. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  64034. }
  64035. if (this._angularSpeedGradientsTexture) {
  64036. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  64037. }
  64038. if (this._velocityGradientsTexture) {
  64039. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  64040. }
  64041. if (this._limitVelocityGradientsTexture) {
  64042. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  64043. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  64044. }
  64045. if (this._dragGradientsTexture) {
  64046. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  64047. }
  64048. if (this.particleEmitterType) {
  64049. this.particleEmitterType.applyToShader(this._updateEffect);
  64050. }
  64051. if (this._isAnimationSheetEnabled) {
  64052. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  64053. }
  64054. if (this.noiseTexture) {
  64055. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  64056. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  64057. }
  64058. var emitterWM;
  64059. if (this.emitter.position) {
  64060. var emitterMesh = this.emitter;
  64061. emitterWM = emitterMesh.getWorldMatrix();
  64062. }
  64063. else {
  64064. var emitterPosition = this.emitter;
  64065. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  64066. }
  64067. this._updateEffect.setMatrix("emitterWM", emitterWM);
  64068. // Bind source VAO
  64069. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  64070. // Update
  64071. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  64072. this._engine.setRasterizerState(false);
  64073. this._engine.beginTransformFeedback(true);
  64074. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  64075. this._engine.endTransformFeedback();
  64076. this._engine.setRasterizerState(true);
  64077. this._engine.bindTransformFeedbackBuffer(null);
  64078. if (!preWarm) {
  64079. // Enable render effect
  64080. this._engine.enableEffect(this._renderEffect);
  64081. var viewMatrix = this._scene.getViewMatrix();
  64082. this._renderEffect.setMatrix("view", viewMatrix);
  64083. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  64084. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  64085. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  64086. if (this._colorGradientsTexture) {
  64087. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  64088. }
  64089. else {
  64090. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  64091. }
  64092. if (this._isAnimationSheetEnabled && this.particleTexture) {
  64093. var baseSize = this.particleTexture.getBaseSize();
  64094. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  64095. }
  64096. if (this._isBillboardBased) {
  64097. var camera = this._scene.activeCamera;
  64098. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  64099. }
  64100. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  64101. var invView = viewMatrix.clone();
  64102. invView.invert();
  64103. this._renderEffect.setMatrix("invView", invView);
  64104. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  64105. }
  64106. // image processing
  64107. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  64108. this._imageProcessingConfiguration.bind(this._renderEffect);
  64109. }
  64110. // Draw order
  64111. switch (this.blendMode) {
  64112. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  64113. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  64114. break;
  64115. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  64116. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  64117. break;
  64118. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  64119. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64120. break;
  64121. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  64122. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  64123. break;
  64124. }
  64125. if (this.forceDepthWrite) {
  64126. this._engine.setDepthWrite(true);
  64127. }
  64128. // Bind source VAO
  64129. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  64130. // Render
  64131. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  64132. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64133. }
  64134. // Switch VAOs
  64135. this._targetIndex++;
  64136. if (this._targetIndex === 2) {
  64137. this._targetIndex = 0;
  64138. }
  64139. // Switch buffers
  64140. var tmpBuffer = this._sourceBuffer;
  64141. this._sourceBuffer = this._targetBuffer;
  64142. this._targetBuffer = tmpBuffer;
  64143. return this._currentActiveCount;
  64144. };
  64145. /**
  64146. * Rebuilds the particle system
  64147. */
  64148. GPUParticleSystem.prototype.rebuild = function () {
  64149. this._initialize(true);
  64150. };
  64151. GPUParticleSystem.prototype._releaseBuffers = function () {
  64152. if (this._buffer0) {
  64153. this._buffer0.dispose();
  64154. this._buffer0 = null;
  64155. }
  64156. if (this._buffer1) {
  64157. this._buffer1.dispose();
  64158. this._buffer1 = null;
  64159. }
  64160. if (this._spriteBuffer) {
  64161. this._spriteBuffer.dispose();
  64162. this._spriteBuffer = null;
  64163. }
  64164. };
  64165. GPUParticleSystem.prototype._releaseVAOs = function () {
  64166. if (!this._updateVAO) {
  64167. return;
  64168. }
  64169. for (var index = 0; index < this._updateVAO.length; index++) {
  64170. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  64171. }
  64172. this._updateVAO = [];
  64173. for (var index = 0; index < this._renderVAO.length; index++) {
  64174. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  64175. }
  64176. this._renderVAO = [];
  64177. };
  64178. /**
  64179. * Disposes the particle system and free the associated resources
  64180. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  64181. */
  64182. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  64183. if (disposeTexture === void 0) { disposeTexture = true; }
  64184. var index = this._scene.particleSystems.indexOf(this);
  64185. if (index > -1) {
  64186. this._scene.particleSystems.splice(index, 1);
  64187. }
  64188. this._releaseBuffers();
  64189. this._releaseVAOs();
  64190. if (this._colorGradientsTexture) {
  64191. this._colorGradientsTexture.dispose();
  64192. this._colorGradientsTexture = null;
  64193. }
  64194. if (this._sizeGradientsTexture) {
  64195. this._sizeGradientsTexture.dispose();
  64196. this._sizeGradientsTexture = null;
  64197. }
  64198. if (this._angularSpeedGradientsTexture) {
  64199. this._angularSpeedGradientsTexture.dispose();
  64200. this._angularSpeedGradientsTexture = null;
  64201. }
  64202. if (this._velocityGradientsTexture) {
  64203. this._velocityGradientsTexture.dispose();
  64204. this._velocityGradientsTexture = null;
  64205. }
  64206. if (this._limitVelocityGradientsTexture) {
  64207. this._limitVelocityGradientsTexture.dispose();
  64208. this._limitVelocityGradientsTexture = null;
  64209. }
  64210. if (this._dragGradientsTexture) {
  64211. this._dragGradientsTexture.dispose();
  64212. this._dragGradientsTexture = null;
  64213. }
  64214. if (this._randomTexture) {
  64215. this._randomTexture.dispose();
  64216. this._randomTexture = null;
  64217. }
  64218. if (this._randomTexture2) {
  64219. this._randomTexture2.dispose();
  64220. this._randomTexture2 = null;
  64221. }
  64222. if (disposeTexture && this.particleTexture) {
  64223. this.particleTexture.dispose();
  64224. this.particleTexture = null;
  64225. }
  64226. if (disposeTexture && this.noiseTexture) {
  64227. this.noiseTexture.dispose();
  64228. this.noiseTexture = null;
  64229. }
  64230. // Callback
  64231. this.onDisposeObservable.notifyObservers(this);
  64232. this.onDisposeObservable.clear();
  64233. };
  64234. /**
  64235. * Clones the particle system.
  64236. * @param name The name of the cloned object
  64237. * @param newEmitter The new emitter to use
  64238. * @returns the cloned particle system
  64239. */
  64240. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  64241. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  64242. BABYLON.Tools.DeepCopy(this, result);
  64243. if (newEmitter === undefined) {
  64244. newEmitter = this.emitter;
  64245. }
  64246. result.emitter = newEmitter;
  64247. if (this.particleTexture) {
  64248. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  64249. }
  64250. return result;
  64251. };
  64252. /**
  64253. * Serializes the particle system to a JSON object.
  64254. * @returns the JSON object
  64255. */
  64256. GPUParticleSystem.prototype.serialize = function () {
  64257. var serializationObject = {};
  64258. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  64259. serializationObject.activeParticleCount = this.activeParticleCount;
  64260. return serializationObject;
  64261. };
  64262. /**
  64263. * Parses a JSON object to create a GPU particle system.
  64264. * @param parsedParticleSystem The JSON object to parse
  64265. * @param scene The scene to create the particle system in
  64266. * @param rootUrl The root url to use to load external dependencies like texture
  64267. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  64268. * @returns the parsed GPU particle system
  64269. */
  64270. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  64271. if (doNotStart === void 0) { doNotStart = false; }
  64272. var name = parsedParticleSystem.name;
  64273. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  64274. if (parsedParticleSystem.activeParticleCount) {
  64275. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  64276. }
  64277. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  64278. // Auto start
  64279. if (parsedParticleSystem.preventAutoStart) {
  64280. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  64281. }
  64282. if (!doNotStart && !particleSystem.preventAutoStart) {
  64283. particleSystem.start();
  64284. }
  64285. return particleSystem;
  64286. };
  64287. return GPUParticleSystem;
  64288. }(BABYLON.BaseParticleSystem));
  64289. BABYLON.GPUParticleSystem = GPUParticleSystem;
  64290. })(BABYLON || (BABYLON = {}));
  64291. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  64292. var BABYLON;
  64293. (function (BABYLON) {
  64294. /**
  64295. * Represents one particle of a solid particle system.
  64296. */
  64297. var SolidParticle = /** @class */ (function () {
  64298. /**
  64299. * Creates a Solid Particle object.
  64300. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  64301. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  64302. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  64303. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  64304. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  64305. * @param shapeId (integer) is the model shape identifier in the SPS.
  64306. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  64307. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  64308. */
  64309. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  64310. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  64311. /**
  64312. * particle global index
  64313. */
  64314. this.idx = 0;
  64315. /**
  64316. * The color of the particle
  64317. */
  64318. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64319. /**
  64320. * The world space position of the particle.
  64321. */
  64322. this.position = BABYLON.Vector3.Zero();
  64323. /**
  64324. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  64325. */
  64326. this.rotation = BABYLON.Vector3.Zero();
  64327. /**
  64328. * The scaling of the particle.
  64329. */
  64330. this.scaling = BABYLON.Vector3.One();
  64331. /**
  64332. * The uvs of the particle.
  64333. */
  64334. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  64335. /**
  64336. * The current speed of the particle.
  64337. */
  64338. this.velocity = BABYLON.Vector3.Zero();
  64339. /**
  64340. * The pivot point in the particle local space.
  64341. */
  64342. this.pivot = BABYLON.Vector3.Zero();
  64343. /**
  64344. * Must the particle be translated from its pivot point in its local space ?
  64345. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  64346. * Default : false
  64347. */
  64348. this.translateFromPivot = false;
  64349. /**
  64350. * Is the particle active or not ?
  64351. */
  64352. this.alive = true;
  64353. /**
  64354. * Is the particle visible or not ?
  64355. */
  64356. this.isVisible = true;
  64357. /**
  64358. * Index of this particle in the global "positions" array (Internal use)
  64359. * @hidden
  64360. */
  64361. this._pos = 0;
  64362. /**
  64363. * @hidden Index of this particle in the global "indices" array (Internal use)
  64364. */
  64365. this._ind = 0;
  64366. /**
  64367. * ModelShape id of this particle
  64368. */
  64369. this.shapeId = 0;
  64370. /**
  64371. * Index of the particle in its shape id (Internal use)
  64372. */
  64373. this.idxInShape = 0;
  64374. /**
  64375. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  64376. */
  64377. this._stillInvisible = false;
  64378. /**
  64379. * @hidden Last computed particle rotation matrix
  64380. */
  64381. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  64382. /**
  64383. * Parent particle Id, if any.
  64384. * Default null.
  64385. */
  64386. this.parentId = null;
  64387. /**
  64388. * @hidden Internal global position in the SPS.
  64389. */
  64390. this._globalPosition = BABYLON.Vector3.Zero();
  64391. this.idx = particleIndex;
  64392. this._pos = positionIndex;
  64393. this._ind = indiceIndex;
  64394. this._model = model;
  64395. this.shapeId = shapeId;
  64396. this.idxInShape = idxInShape;
  64397. this._sps = sps;
  64398. if (modelBoundingInfo) {
  64399. this._modelBoundingInfo = modelBoundingInfo;
  64400. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  64401. }
  64402. }
  64403. Object.defineProperty(SolidParticle.prototype, "scale", {
  64404. /**
  64405. * Legacy support, changed scale to scaling
  64406. */
  64407. get: function () {
  64408. return this.scaling;
  64409. },
  64410. /**
  64411. * Legacy support, changed scale to scaling
  64412. */
  64413. set: function (scale) {
  64414. this.scaling = scale;
  64415. },
  64416. enumerable: true,
  64417. configurable: true
  64418. });
  64419. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  64420. /**
  64421. * Legacy support, changed quaternion to rotationQuaternion
  64422. */
  64423. get: function () {
  64424. return this.rotationQuaternion;
  64425. },
  64426. /**
  64427. * Legacy support, changed quaternion to rotationQuaternion
  64428. */
  64429. set: function (q) {
  64430. this.rotationQuaternion = q;
  64431. },
  64432. enumerable: true,
  64433. configurable: true
  64434. });
  64435. /**
  64436. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  64437. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  64438. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  64439. * @returns true if it intersects
  64440. */
  64441. SolidParticle.prototype.intersectsMesh = function (target) {
  64442. if (!this._boundingInfo || !target._boundingInfo) {
  64443. return false;
  64444. }
  64445. if (this._sps._bSphereOnly) {
  64446. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  64447. }
  64448. return this._boundingInfo.intersects(target._boundingInfo, false);
  64449. };
  64450. return SolidParticle;
  64451. }());
  64452. BABYLON.SolidParticle = SolidParticle;
  64453. /**
  64454. * Represents the shape of the model used by one particle of a solid particle system.
  64455. * SPS internal tool, don't use it manually.
  64456. */
  64457. var ModelShape = /** @class */ (function () {
  64458. /**
  64459. * 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.
  64460. * SPS internal tool, don't use it manually.
  64461. * @hidden
  64462. */
  64463. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  64464. /**
  64465. * length of the shape in the model indices array (internal use)
  64466. * @hidden
  64467. */
  64468. this._indicesLength = 0;
  64469. this.shapeID = id;
  64470. this._shape = shape;
  64471. this._indicesLength = indicesLength;
  64472. this._shapeUV = shapeUV;
  64473. this._positionFunction = posFunction;
  64474. this._vertexFunction = vtxFunction;
  64475. }
  64476. return ModelShape;
  64477. }());
  64478. BABYLON.ModelShape = ModelShape;
  64479. /**
  64480. * Represents a Depth Sorted Particle in the solid particle system.
  64481. */
  64482. var DepthSortedParticle = /** @class */ (function () {
  64483. function DepthSortedParticle() {
  64484. /**
  64485. * Index of the particle in the "indices" array
  64486. */
  64487. this.ind = 0;
  64488. /**
  64489. * Length of the particle shape in the "indices" array
  64490. */
  64491. this.indicesLength = 0;
  64492. /**
  64493. * Squared distance from the particle to the camera
  64494. */
  64495. this.sqDistance = 0.0;
  64496. }
  64497. return DepthSortedParticle;
  64498. }());
  64499. BABYLON.DepthSortedParticle = DepthSortedParticle;
  64500. })(BABYLON || (BABYLON = {}));
  64501. //# sourceMappingURL=babylon.solidParticle.js.map
  64502. var BABYLON;
  64503. (function (BABYLON) {
  64504. /**
  64505. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  64506. *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.
  64507. * The SPS is also a particle system. It provides some methods to manage the particles.
  64508. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  64509. *
  64510. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  64511. */
  64512. var SolidParticleSystem = /** @class */ (function () {
  64513. /**
  64514. * Creates a SPS (Solid Particle System) object.
  64515. * @param name (String) is the SPS name, this will be the underlying mesh name.
  64516. * @param scene (Scene) is the scene in which the SPS is added.
  64517. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  64518. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  64519. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  64520. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  64521. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  64522. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  64523. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  64524. */
  64525. function SolidParticleSystem(name, scene, options) {
  64526. /**
  64527. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  64528. * Example : var p = SPS.particles[i];
  64529. */
  64530. this.particles = new Array();
  64531. /**
  64532. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  64533. */
  64534. this.nbParticles = 0;
  64535. /**
  64536. * If the particles must ever face the camera (default false). Useful for planar particles.
  64537. */
  64538. this.billboard = false;
  64539. /**
  64540. * Recompute normals when adding a shape
  64541. */
  64542. this.recomputeNormals = true;
  64543. /**
  64544. * This a counter ofr your own usage. It's not set by any SPS functions.
  64545. */
  64546. this.counter = 0;
  64547. /**
  64548. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  64549. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  64550. */
  64551. this.vars = {};
  64552. /**
  64553. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  64554. * @hidden
  64555. */
  64556. this._bSphereOnly = false;
  64557. /**
  64558. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  64559. * @hidden
  64560. */
  64561. this._bSphereRadiusFactor = 1.0;
  64562. this._positions = new Array();
  64563. this._indices = new Array();
  64564. this._normals = new Array();
  64565. this._colors = new Array();
  64566. this._uvs = new Array();
  64567. this._index = 0; // indices index
  64568. this._updatable = true;
  64569. this._pickable = false;
  64570. this._isVisibilityBoxLocked = false;
  64571. this._alwaysVisible = false;
  64572. this._depthSort = false;
  64573. this._shapeCounter = 0;
  64574. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  64575. this._color = new BABYLON.Color4(0, 0, 0, 0);
  64576. this._computeParticleColor = true;
  64577. this._computeParticleTexture = true;
  64578. this._computeParticleRotation = true;
  64579. this._computeParticleVertex = false;
  64580. this._computeBoundingBox = false;
  64581. this._depthSortParticles = true;
  64582. this._cam_axisZ = BABYLON.Vector3.Zero();
  64583. this._cam_axisY = BABYLON.Vector3.Zero();
  64584. this._cam_axisX = BABYLON.Vector3.Zero();
  64585. this._axisZ = BABYLON.Axis.Z;
  64586. this._camDir = BABYLON.Vector3.Zero();
  64587. this._camInvertedPosition = BABYLON.Vector3.Zero();
  64588. this._rotMatrix = new BABYLON.Matrix();
  64589. this._invertMatrix = new BABYLON.Matrix();
  64590. this._rotated = BABYLON.Vector3.Zero();
  64591. this._quaternion = new BABYLON.Quaternion();
  64592. this._vertex = BABYLON.Vector3.Zero();
  64593. this._normal = BABYLON.Vector3.Zero();
  64594. this._yaw = 0.0;
  64595. this._pitch = 0.0;
  64596. this._roll = 0.0;
  64597. this._halfroll = 0.0;
  64598. this._halfpitch = 0.0;
  64599. this._halfyaw = 0.0;
  64600. this._sinRoll = 0.0;
  64601. this._cosRoll = 0.0;
  64602. this._sinPitch = 0.0;
  64603. this._cosPitch = 0.0;
  64604. this._sinYaw = 0.0;
  64605. this._cosYaw = 0.0;
  64606. this._mustUnrotateFixedNormals = false;
  64607. this._minimum = BABYLON.Vector3.Zero();
  64608. this._maximum = BABYLON.Vector3.Zero();
  64609. this._minBbox = BABYLON.Vector3.Zero();
  64610. this._maxBbox = BABYLON.Vector3.Zero();
  64611. this._particlesIntersect = false;
  64612. this._depthSortFunction = function (p1, p2) {
  64613. return (p2.sqDistance - p1.sqDistance);
  64614. };
  64615. this._needs32Bits = false;
  64616. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  64617. this._scaledPivot = BABYLON.Vector3.Zero();
  64618. this._particleHasParent = false;
  64619. this.name = name;
  64620. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64621. this._camera = scene.activeCamera;
  64622. this._pickable = options ? options.isPickable : false;
  64623. this._depthSort = options ? options.enableDepthSort : false;
  64624. this._particlesIntersect = options ? options.particleIntersection : false;
  64625. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  64626. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  64627. if (options && options.updatable !== undefined) {
  64628. this._updatable = options.updatable;
  64629. }
  64630. else {
  64631. this._updatable = true;
  64632. }
  64633. if (this._pickable) {
  64634. this.pickedParticles = [];
  64635. }
  64636. if (this._depthSort) {
  64637. this.depthSortedParticles = [];
  64638. }
  64639. }
  64640. /**
  64641. * Builds the SPS underlying mesh. Returns a standard Mesh.
  64642. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  64643. * @returns the created mesh
  64644. */
  64645. SolidParticleSystem.prototype.buildMesh = function () {
  64646. if (this.nbParticles === 0) {
  64647. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  64648. this.addShape(triangle, 1);
  64649. triangle.dispose();
  64650. }
  64651. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  64652. this._positions32 = new Float32Array(this._positions);
  64653. this._uvs32 = new Float32Array(this._uvs);
  64654. this._colors32 = new Float32Array(this._colors);
  64655. if (this.recomputeNormals) {
  64656. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  64657. }
  64658. this._normals32 = new Float32Array(this._normals);
  64659. this._fixedNormal32 = new Float32Array(this._normals);
  64660. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  64661. this._unrotateFixedNormals();
  64662. }
  64663. var vertexData = new BABYLON.VertexData();
  64664. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  64665. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  64666. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  64667. if (this._uvs32.length > 0) {
  64668. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  64669. }
  64670. if (this._colors32.length > 0) {
  64671. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  64672. }
  64673. var mesh = new BABYLON.Mesh(this.name, this._scene);
  64674. vertexData.applyToMesh(mesh, this._updatable);
  64675. this.mesh = mesh;
  64676. this.mesh.isPickable = this._pickable;
  64677. // free memory
  64678. if (!this._depthSort) {
  64679. this._indices = null;
  64680. }
  64681. this._positions = null;
  64682. this._normals = null;
  64683. this._uvs = null;
  64684. this._colors = null;
  64685. if (!this._updatable) {
  64686. this.particles.length = 0;
  64687. }
  64688. return mesh;
  64689. };
  64690. /**
  64691. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  64692. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  64693. * Thus the particles generated from `digest()` have their property `position` set yet.
  64694. * @param mesh ( Mesh ) is the mesh to be digested
  64695. * @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
  64696. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  64697. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  64698. * @returns the current SPS
  64699. */
  64700. SolidParticleSystem.prototype.digest = function (mesh, options) {
  64701. var size = (options && options.facetNb) || 1;
  64702. var number = (options && options.number) || 0;
  64703. var delta = (options && options.delta) || 0;
  64704. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64705. var meshInd = mesh.getIndices();
  64706. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64707. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64708. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64709. var f = 0; // facet counter
  64710. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  64711. // compute size from number
  64712. if (number) {
  64713. number = (number > totalFacets) ? totalFacets : number;
  64714. size = Math.round(totalFacets / number);
  64715. delta = 0;
  64716. }
  64717. else {
  64718. size = (size > totalFacets) ? totalFacets : size;
  64719. }
  64720. var facetPos = []; // submesh positions
  64721. var facetInd = []; // submesh indices
  64722. var facetUV = []; // submesh UV
  64723. var facetCol = []; // submesh colors
  64724. var barycenter = BABYLON.Vector3.Zero();
  64725. var sizeO = size;
  64726. while (f < totalFacets) {
  64727. size = sizeO + Math.floor((1 + delta) * Math.random());
  64728. if (f > totalFacets - size) {
  64729. size = totalFacets - f;
  64730. }
  64731. // reset temp arrays
  64732. facetPos.length = 0;
  64733. facetInd.length = 0;
  64734. facetUV.length = 0;
  64735. facetCol.length = 0;
  64736. // iterate over "size" facets
  64737. var fi = 0;
  64738. for (var j = f * 3; j < (f + size) * 3; j++) {
  64739. facetInd.push(fi);
  64740. var i = meshInd[j];
  64741. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  64742. if (meshUV) {
  64743. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  64744. }
  64745. if (meshCol) {
  64746. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  64747. }
  64748. fi++;
  64749. }
  64750. // create a model shape for each single particle
  64751. var idx = this.nbParticles;
  64752. var shape = this._posToShape(facetPos);
  64753. var shapeUV = this._uvsToShapeUV(facetUV);
  64754. // compute the barycenter of the shape
  64755. var v;
  64756. for (v = 0; v < shape.length; v++) {
  64757. barycenter.addInPlace(shape[v]);
  64758. }
  64759. barycenter.scaleInPlace(1 / shape.length);
  64760. // shift the shape from its barycenter to the origin
  64761. for (v = 0; v < shape.length; v++) {
  64762. shape[v].subtractInPlace(barycenter);
  64763. }
  64764. var bInfo;
  64765. if (this._particlesIntersect) {
  64766. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  64767. }
  64768. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  64769. // add the particle in the SPS
  64770. var currentPos = this._positions.length;
  64771. var currentInd = this._indices.length;
  64772. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  64773. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  64774. // initialize the particle position
  64775. this.particles[this.nbParticles].position.addInPlace(barycenter);
  64776. this._index += shape.length;
  64777. idx++;
  64778. this.nbParticles++;
  64779. this._shapeCounter++;
  64780. f += size;
  64781. }
  64782. return this;
  64783. };
  64784. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  64785. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  64786. var index = 0;
  64787. var idx = 0;
  64788. for (var p = 0; p < this.particles.length; p++) {
  64789. this._particle = this.particles[p];
  64790. this._shape = this._particle._model._shape;
  64791. if (this._particle.rotationQuaternion) {
  64792. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  64793. }
  64794. else {
  64795. this._yaw = this._particle.rotation.y;
  64796. this._pitch = this._particle.rotation.x;
  64797. this._roll = this._particle.rotation.z;
  64798. this._quaternionRotationYPR();
  64799. }
  64800. this._quaternionToRotationMatrix();
  64801. this._rotMatrix.invertToRef(this._invertMatrix);
  64802. for (var pt = 0; pt < this._shape.length; pt++) {
  64803. idx = index + pt * 3;
  64804. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  64805. this._fixedNormal32[idx] = this._normal.x;
  64806. this._fixedNormal32[idx + 1] = this._normal.y;
  64807. this._fixedNormal32[idx + 2] = this._normal.z;
  64808. }
  64809. index = idx + 3;
  64810. }
  64811. };
  64812. //reset copy
  64813. SolidParticleSystem.prototype._resetCopy = function () {
  64814. this._copy.position.x = 0;
  64815. this._copy.position.y = 0;
  64816. this._copy.position.z = 0;
  64817. this._copy.rotation.x = 0;
  64818. this._copy.rotation.y = 0;
  64819. this._copy.rotation.z = 0;
  64820. this._copy.rotationQuaternion = null;
  64821. this._copy.scaling.x = 1.0;
  64822. this._copy.scaling.y = 1.0;
  64823. this._copy.scaling.z = 1.0;
  64824. this._copy.uvs.x = 0;
  64825. this._copy.uvs.y = 0;
  64826. this._copy.uvs.z = 1.0;
  64827. this._copy.uvs.w = 1.0;
  64828. this._copy.color = null;
  64829. this._copy.translateFromPivot = false;
  64830. };
  64831. // _meshBuilder : inserts the shape model in the global SPS mesh
  64832. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  64833. var i;
  64834. var u = 0;
  64835. var c = 0;
  64836. var n = 0;
  64837. this._resetCopy();
  64838. if (options && options.positionFunction) { // call to custom positionFunction
  64839. options.positionFunction(this._copy, idx, idxInShape);
  64840. this._mustUnrotateFixedNormals = true;
  64841. }
  64842. if (this._copy.rotationQuaternion) {
  64843. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  64844. }
  64845. else {
  64846. this._yaw = this._copy.rotation.y;
  64847. this._pitch = this._copy.rotation.x;
  64848. this._roll = this._copy.rotation.z;
  64849. this._quaternionRotationYPR();
  64850. }
  64851. this._quaternionToRotationMatrix();
  64852. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  64853. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  64854. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  64855. if (this._copy.translateFromPivot) {
  64856. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  64857. }
  64858. else {
  64859. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  64860. }
  64861. for (i = 0; i < shape.length; i++) {
  64862. this._vertex.x = shape[i].x;
  64863. this._vertex.y = shape[i].y;
  64864. this._vertex.z = shape[i].z;
  64865. if (options && options.vertexFunction) {
  64866. options.vertexFunction(this._copy, this._vertex, i);
  64867. }
  64868. this._vertex.x *= this._copy.scaling.x;
  64869. this._vertex.y *= this._copy.scaling.y;
  64870. this._vertex.z *= this._copy.scaling.z;
  64871. this._vertex.x -= this._scaledPivot.x;
  64872. this._vertex.y -= this._scaledPivot.y;
  64873. this._vertex.z -= this._scaledPivot.z;
  64874. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  64875. this._rotated.addInPlace(this._pivotBackTranslation);
  64876. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  64877. if (meshUV) {
  64878. 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);
  64879. u += 2;
  64880. }
  64881. if (this._copy.color) {
  64882. this._color = this._copy.color;
  64883. }
  64884. else if (meshCol && meshCol[c] !== undefined) {
  64885. this._color.r = meshCol[c];
  64886. this._color.g = meshCol[c + 1];
  64887. this._color.b = meshCol[c + 2];
  64888. this._color.a = meshCol[c + 3];
  64889. }
  64890. else {
  64891. this._color.r = 1.0;
  64892. this._color.g = 1.0;
  64893. this._color.b = 1.0;
  64894. this._color.a = 1.0;
  64895. }
  64896. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  64897. c += 4;
  64898. if (!this.recomputeNormals && meshNor) {
  64899. this._normal.x = meshNor[n];
  64900. this._normal.y = meshNor[n + 1];
  64901. this._normal.z = meshNor[n + 2];
  64902. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  64903. normals.push(this._normal.x, this._normal.y, this._normal.z);
  64904. n += 3;
  64905. }
  64906. }
  64907. for (i = 0; i < meshInd.length; i++) {
  64908. var current_ind = p + meshInd[i];
  64909. indices.push(current_ind);
  64910. if (current_ind > 65535) {
  64911. this._needs32Bits = true;
  64912. }
  64913. }
  64914. if (this._pickable) {
  64915. var nbfaces = meshInd.length / 3;
  64916. for (i = 0; i < nbfaces; i++) {
  64917. this.pickedParticles.push({ idx: idx, faceId: i });
  64918. }
  64919. }
  64920. if (this._depthSort) {
  64921. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  64922. }
  64923. return this._copy;
  64924. };
  64925. // returns a shape array from positions array
  64926. SolidParticleSystem.prototype._posToShape = function (positions) {
  64927. var shape = [];
  64928. for (var i = 0; i < positions.length; i += 3) {
  64929. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  64930. }
  64931. return shape;
  64932. };
  64933. // returns a shapeUV array from a Vector4 uvs
  64934. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  64935. var shapeUV = [];
  64936. if (uvs) {
  64937. for (var i = 0; i < uvs.length; i++)
  64938. shapeUV.push(uvs[i]);
  64939. }
  64940. return shapeUV;
  64941. };
  64942. // adds a new particle object in the particles array
  64943. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  64944. if (bInfo === void 0) { bInfo = null; }
  64945. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  64946. this.particles.push(sp);
  64947. return sp;
  64948. };
  64949. /**
  64950. * Adds some particles to the SPS from the model shape. Returns the shape id.
  64951. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  64952. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  64953. * @param nb (positive integer) the number of particles to be created from this model
  64954. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  64955. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  64956. * @returns the number of shapes in the system
  64957. */
  64958. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  64959. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64960. var meshInd = mesh.getIndices();
  64961. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64962. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64963. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64964. var bbInfo;
  64965. if (this._particlesIntersect) {
  64966. bbInfo = mesh.getBoundingInfo();
  64967. }
  64968. var shape = this._posToShape(meshPos);
  64969. var shapeUV = this._uvsToShapeUV(meshUV);
  64970. var posfunc = options ? options.positionFunction : null;
  64971. var vtxfunc = options ? options.vertexFunction : null;
  64972. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  64973. // particles
  64974. var sp;
  64975. var currentCopy;
  64976. var idx = this.nbParticles;
  64977. for (var i = 0; i < nb; i++) {
  64978. var currentPos = this._positions.length;
  64979. var currentInd = this._indices.length;
  64980. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  64981. if (this._updatable) {
  64982. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  64983. sp.position.copyFrom(currentCopy.position);
  64984. sp.rotation.copyFrom(currentCopy.rotation);
  64985. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  64986. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  64987. }
  64988. if (currentCopy.color && sp.color) {
  64989. sp.color.copyFrom(currentCopy.color);
  64990. }
  64991. sp.scaling.copyFrom(currentCopy.scaling);
  64992. sp.uvs.copyFrom(currentCopy.uvs);
  64993. }
  64994. this._index += shape.length;
  64995. idx++;
  64996. }
  64997. this.nbParticles += nb;
  64998. this._shapeCounter++;
  64999. return this._shapeCounter - 1;
  65000. };
  65001. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  65002. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  65003. this._resetCopy();
  65004. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  65005. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  65006. }
  65007. if (this._copy.rotationQuaternion) {
  65008. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65009. }
  65010. else {
  65011. this._yaw = this._copy.rotation.y;
  65012. this._pitch = this._copy.rotation.x;
  65013. this._roll = this._copy.rotation.z;
  65014. this._quaternionRotationYPR();
  65015. }
  65016. this._quaternionToRotationMatrix();
  65017. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65018. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65019. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65020. if (this._copy.translateFromPivot) {
  65021. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65022. }
  65023. else {
  65024. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65025. }
  65026. this._shape = particle._model._shape;
  65027. for (var pt = 0; pt < this._shape.length; pt++) {
  65028. this._vertex.x = this._shape[pt].x;
  65029. this._vertex.y = this._shape[pt].y;
  65030. this._vertex.z = this._shape[pt].z;
  65031. if (particle._model._vertexFunction) {
  65032. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  65033. }
  65034. this._vertex.x *= this._copy.scaling.x;
  65035. this._vertex.y *= this._copy.scaling.y;
  65036. this._vertex.z *= this._copy.scaling.z;
  65037. this._vertex.x -= this._scaledPivot.x;
  65038. this._vertex.y -= this._scaledPivot.y;
  65039. this._vertex.z -= this._scaledPivot.z;
  65040. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  65041. this._rotated.addInPlace(this._pivotBackTranslation);
  65042. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  65043. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  65044. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  65045. }
  65046. particle.position.x = 0.0;
  65047. particle.position.y = 0.0;
  65048. particle.position.z = 0.0;
  65049. particle.rotation.x = 0.0;
  65050. particle.rotation.y = 0.0;
  65051. particle.rotation.z = 0.0;
  65052. particle.rotationQuaternion = null;
  65053. particle.scaling.x = 1.0;
  65054. particle.scaling.y = 1.0;
  65055. particle.scaling.z = 1.0;
  65056. particle.uvs.x = 0.0;
  65057. particle.uvs.y = 0.0;
  65058. particle.uvs.z = 1.0;
  65059. particle.uvs.w = 1.0;
  65060. particle.pivot.x = 0.0;
  65061. particle.pivot.y = 0.0;
  65062. particle.pivot.z = 0.0;
  65063. particle.translateFromPivot = false;
  65064. particle.parentId = null;
  65065. };
  65066. /**
  65067. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  65068. * @returns the SPS.
  65069. */
  65070. SolidParticleSystem.prototype.rebuildMesh = function () {
  65071. for (var p = 0; p < this.particles.length; p++) {
  65072. this._rebuildParticle(this.particles[p]);
  65073. }
  65074. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65075. return this;
  65076. };
  65077. /**
  65078. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  65079. * This method calls `updateParticle()` for each particle of the SPS.
  65080. * For an animated SPS, it is usually called within the render loop.
  65081. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  65082. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  65083. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  65084. * @returns the SPS.
  65085. */
  65086. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  65087. if (start === void 0) { start = 0; }
  65088. if (end === void 0) { end = this.nbParticles - 1; }
  65089. if (update === void 0) { update = true; }
  65090. if (!this._updatable) {
  65091. return this;
  65092. }
  65093. // custom beforeUpdate
  65094. this.beforeUpdateParticles(start, end, update);
  65095. this._cam_axisX.x = 1.0;
  65096. this._cam_axisX.y = 0.0;
  65097. this._cam_axisX.z = 0.0;
  65098. this._cam_axisY.x = 0.0;
  65099. this._cam_axisY.y = 1.0;
  65100. this._cam_axisY.z = 0.0;
  65101. this._cam_axisZ.x = 0.0;
  65102. this._cam_axisZ.y = 0.0;
  65103. this._cam_axisZ.z = 1.0;
  65104. // cases when the World Matrix is to be computed first
  65105. if (this.billboard || this._depthSort) {
  65106. this.mesh.computeWorldMatrix(true);
  65107. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  65108. }
  65109. // if the particles will always face the camera
  65110. if (this.billboard) {
  65111. // compute the camera position and un-rotate it by the current mesh rotation
  65112. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  65113. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  65114. this._cam_axisZ.normalize();
  65115. // same for camera up vector extracted from the cam view matrix
  65116. var view = this._camera.getViewMatrix(true);
  65117. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  65118. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  65119. this._cam_axisY.normalize();
  65120. this._cam_axisX.normalize();
  65121. }
  65122. // if depthSort, compute the camera global position in the mesh local system
  65123. if (this._depthSort) {
  65124. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  65125. }
  65126. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  65127. var idx = 0; // current position index in the global array positions32
  65128. var index = 0; // position start index in the global array positions32 of the current particle
  65129. var colidx = 0; // current color index in the global array colors32
  65130. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  65131. var uvidx = 0; // current uv index in the global array uvs32
  65132. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  65133. var pt = 0; // current index in the particle model shape
  65134. if (this.mesh.isFacetDataEnabled) {
  65135. this._computeBoundingBox = true;
  65136. }
  65137. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  65138. if (this._computeBoundingBox) {
  65139. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  65140. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  65141. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  65142. }
  65143. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  65144. if (this.mesh._boundingInfo) {
  65145. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  65146. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  65147. }
  65148. }
  65149. }
  65150. // particle loop
  65151. index = this.particles[start]._pos;
  65152. var vpos = (index / 3) | 0;
  65153. colorIndex = vpos * 4;
  65154. uvIndex = vpos * 2;
  65155. for (var p = start; p <= end; p++) {
  65156. this._particle = this.particles[p];
  65157. this._shape = this._particle._model._shape;
  65158. this._shapeUV = this._particle._model._shapeUV;
  65159. // call to custom user function to update the particle properties
  65160. this.updateParticle(this._particle);
  65161. // camera-particle distance for depth sorting
  65162. if (this._depthSort && this._depthSortParticles) {
  65163. var dsp = this.depthSortedParticles[p];
  65164. dsp.ind = this._particle._ind;
  65165. dsp.indicesLength = this._particle._model._indicesLength;
  65166. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  65167. }
  65168. // skip the computations for inactive or already invisible particles
  65169. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  65170. // increment indexes for the next particle
  65171. pt = this._shape.length;
  65172. index += pt * 3;
  65173. colorIndex += pt * 4;
  65174. uvIndex += pt * 2;
  65175. continue;
  65176. }
  65177. if (this._particle.isVisible) {
  65178. this._particle._stillInvisible = false; // un-mark permanent invisibility
  65179. this._particleHasParent = (this._particle.parentId !== null);
  65180. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65181. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65182. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65183. // particle rotation matrix
  65184. if (this.billboard) {
  65185. this._particle.rotation.x = 0.0;
  65186. this._particle.rotation.y = 0.0;
  65187. }
  65188. if (this._computeParticleRotation || this.billboard) {
  65189. if (this._particle.rotationQuaternion) {
  65190. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65191. }
  65192. else {
  65193. this._yaw = this._particle.rotation.y;
  65194. this._pitch = this._particle.rotation.x;
  65195. this._roll = this._particle.rotation.z;
  65196. this._quaternionRotationYPR();
  65197. }
  65198. this._quaternionToRotationMatrix();
  65199. }
  65200. if (this._particleHasParent) {
  65201. this._parent = this.particles[this._particle.parentId];
  65202. 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];
  65203. 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];
  65204. 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];
  65205. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  65206. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  65207. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  65208. if (this._computeParticleRotation || this.billboard) {
  65209. 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];
  65210. 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];
  65211. 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];
  65212. 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];
  65213. 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];
  65214. 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];
  65215. 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];
  65216. 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];
  65217. 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];
  65218. }
  65219. }
  65220. else {
  65221. this._particle._globalPosition.x = this._particle.position.x;
  65222. this._particle._globalPosition.y = this._particle.position.y;
  65223. this._particle._globalPosition.z = this._particle.position.z;
  65224. if (this._computeParticleRotation || this.billboard) {
  65225. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  65226. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  65227. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  65228. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  65229. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  65230. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  65231. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  65232. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  65233. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  65234. }
  65235. }
  65236. if (this._particle.translateFromPivot) {
  65237. this._pivotBackTranslation.x = 0.0;
  65238. this._pivotBackTranslation.y = 0.0;
  65239. this._pivotBackTranslation.z = 0.0;
  65240. }
  65241. else {
  65242. this._pivotBackTranslation.x = this._scaledPivot.x;
  65243. this._pivotBackTranslation.y = this._scaledPivot.y;
  65244. this._pivotBackTranslation.z = this._scaledPivot.z;
  65245. }
  65246. // particle vertex loop
  65247. for (pt = 0; pt < this._shape.length; pt++) {
  65248. idx = index + pt * 3;
  65249. colidx = colorIndex + pt * 4;
  65250. uvidx = uvIndex + pt * 2;
  65251. this._vertex.x = this._shape[pt].x;
  65252. this._vertex.y = this._shape[pt].y;
  65253. this._vertex.z = this._shape[pt].z;
  65254. if (this._computeParticleVertex) {
  65255. this.updateParticleVertex(this._particle, this._vertex, pt);
  65256. }
  65257. // positions
  65258. this._vertex.x *= this._particle.scaling.x;
  65259. this._vertex.y *= this._particle.scaling.y;
  65260. this._vertex.z *= this._particle.scaling.z;
  65261. this._vertex.x -= this._scaledPivot.x;
  65262. this._vertex.y -= this._scaledPivot.y;
  65263. this._vertex.z -= this._scaledPivot.z;
  65264. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65265. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65266. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65267. this._rotated.x += this._pivotBackTranslation.x;
  65268. this._rotated.y += this._pivotBackTranslation.y;
  65269. this._rotated.z += this._pivotBackTranslation.z;
  65270. 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;
  65271. 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;
  65272. 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;
  65273. if (this._computeBoundingBox) {
  65274. if (this._positions32[idx] < this._minimum.x) {
  65275. this._minimum.x = this._positions32[idx];
  65276. }
  65277. if (this._positions32[idx] > this._maximum.x) {
  65278. this._maximum.x = this._positions32[idx];
  65279. }
  65280. if (this._positions32[idx + 1] < this._minimum.y) {
  65281. this._minimum.y = this._positions32[idx + 1];
  65282. }
  65283. if (this._positions32[idx + 1] > this._maximum.y) {
  65284. this._maximum.y = this._positions32[idx + 1];
  65285. }
  65286. if (this._positions32[idx + 2] < this._minimum.z) {
  65287. this._minimum.z = this._positions32[idx + 2];
  65288. }
  65289. if (this._positions32[idx + 2] > this._maximum.z) {
  65290. this._maximum.z = this._positions32[idx + 2];
  65291. }
  65292. }
  65293. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  65294. if (!this._computeParticleVertex) {
  65295. this._normal.x = this._fixedNormal32[idx];
  65296. this._normal.y = this._fixedNormal32[idx + 1];
  65297. this._normal.z = this._fixedNormal32[idx + 2];
  65298. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  65299. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  65300. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  65301. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  65302. 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;
  65303. 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;
  65304. }
  65305. if (this._computeParticleColor && this._particle.color) {
  65306. this._colors32[colidx] = this._particle.color.r;
  65307. this._colors32[colidx + 1] = this._particle.color.g;
  65308. this._colors32[colidx + 2] = this._particle.color.b;
  65309. this._colors32[colidx + 3] = this._particle.color.a;
  65310. }
  65311. if (this._computeParticleTexture) {
  65312. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65313. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65314. }
  65315. }
  65316. }
  65317. // particle just set invisible : scaled to zero and positioned at the origin
  65318. else {
  65319. this._particle._stillInvisible = true; // mark the particle as invisible
  65320. for (pt = 0; pt < this._shape.length; pt++) {
  65321. idx = index + pt * 3;
  65322. colidx = colorIndex + pt * 4;
  65323. uvidx = uvIndex + pt * 2;
  65324. this._positions32[idx] = 0.0;
  65325. this._positions32[idx + 1] = 0.0;
  65326. this._positions32[idx + 2] = 0.0;
  65327. this._normals32[idx] = 0.0;
  65328. this._normals32[idx + 1] = 0.0;
  65329. this._normals32[idx + 2] = 0.0;
  65330. if (this._computeParticleColor && this._particle.color) {
  65331. this._colors32[colidx] = this._particle.color.r;
  65332. this._colors32[colidx + 1] = this._particle.color.g;
  65333. this._colors32[colidx + 2] = this._particle.color.b;
  65334. this._colors32[colidx + 3] = this._particle.color.a;
  65335. }
  65336. if (this._computeParticleTexture) {
  65337. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65338. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65339. }
  65340. }
  65341. }
  65342. // if the particle intersections must be computed : update the bbInfo
  65343. if (this._particlesIntersect) {
  65344. var bInfo = this._particle._boundingInfo;
  65345. var bBox = bInfo.boundingBox;
  65346. var bSphere = bInfo.boundingSphere;
  65347. if (!this._bSphereOnly) {
  65348. // place, scale and rotate the particle bbox within the SPS local system, then update it
  65349. for (var b = 0; b < bBox.vectors.length; b++) {
  65350. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  65351. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  65352. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  65353. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65354. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65355. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65356. 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;
  65357. 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;
  65358. 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;
  65359. }
  65360. bBox._update(this.mesh._worldMatrix);
  65361. }
  65362. // place and scale the particle bouding sphere in the SPS local system, then update it
  65363. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  65364. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  65365. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  65366. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  65367. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  65368. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  65369. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  65370. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  65371. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  65372. 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));
  65373. bSphere._update(this.mesh._worldMatrix);
  65374. }
  65375. // increment indexes for the next particle
  65376. index = idx + 3;
  65377. colorIndex = colidx + 4;
  65378. uvIndex = uvidx + 2;
  65379. }
  65380. // if the VBO must be updated
  65381. if (update) {
  65382. if (this._computeParticleColor) {
  65383. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  65384. }
  65385. if (this._computeParticleTexture) {
  65386. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  65387. }
  65388. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65389. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  65390. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  65391. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  65392. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  65393. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  65394. for (var i = 0; i < this._normals32.length; i++) {
  65395. this._fixedNormal32[i] = this._normals32[i];
  65396. }
  65397. }
  65398. if (!this.mesh.areNormalsFrozen) {
  65399. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  65400. }
  65401. }
  65402. if (this._depthSort && this._depthSortParticles) {
  65403. this.depthSortedParticles.sort(this._depthSortFunction);
  65404. var dspl = this.depthSortedParticles.length;
  65405. var sorted = 0;
  65406. var lind = 0;
  65407. var sind = 0;
  65408. var sid = 0;
  65409. for (sorted = 0; sorted < dspl; sorted++) {
  65410. lind = this.depthSortedParticles[sorted].indicesLength;
  65411. sind = this.depthSortedParticles[sorted].ind;
  65412. for (var i = 0; i < lind; i++) {
  65413. this._indices32[sid] = this._indices[sind + i];
  65414. sid++;
  65415. }
  65416. }
  65417. this.mesh.updateIndices(this._indices32);
  65418. }
  65419. }
  65420. if (this._computeBoundingBox) {
  65421. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  65422. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  65423. }
  65424. this.afterUpdateParticles(start, end, update);
  65425. return this;
  65426. };
  65427. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  65428. this._halfroll = this._roll * 0.5;
  65429. this._halfpitch = this._pitch * 0.5;
  65430. this._halfyaw = this._yaw * 0.5;
  65431. this._sinRoll = Math.sin(this._halfroll);
  65432. this._cosRoll = Math.cos(this._halfroll);
  65433. this._sinPitch = Math.sin(this._halfpitch);
  65434. this._cosPitch = Math.cos(this._halfpitch);
  65435. this._sinYaw = Math.sin(this._halfyaw);
  65436. this._cosYaw = Math.cos(this._halfyaw);
  65437. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  65438. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  65439. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  65440. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  65441. };
  65442. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  65443. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  65444. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  65445. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  65446. this._rotMatrix.m[3] = 0;
  65447. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  65448. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  65449. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  65450. this._rotMatrix.m[7] = 0;
  65451. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  65452. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  65453. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  65454. this._rotMatrix.m[11] = 0;
  65455. this._rotMatrix.m[12] = 0;
  65456. this._rotMatrix.m[13] = 0;
  65457. this._rotMatrix.m[14] = 0;
  65458. this._rotMatrix.m[15] = 1.0;
  65459. };
  65460. /**
  65461. * Disposes the SPS.
  65462. */
  65463. SolidParticleSystem.prototype.dispose = function () {
  65464. this.mesh.dispose();
  65465. this.vars = null;
  65466. // drop references to internal big arrays for the GC
  65467. this._positions = null;
  65468. this._indices = null;
  65469. this._normals = null;
  65470. this._uvs = null;
  65471. this._colors = null;
  65472. this._indices32 = null;
  65473. this._positions32 = null;
  65474. this._normals32 = null;
  65475. this._fixedNormal32 = null;
  65476. this._uvs32 = null;
  65477. this._colors32 = null;
  65478. this.pickedParticles = null;
  65479. };
  65480. /**
  65481. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  65482. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65483. * @returns the SPS.
  65484. */
  65485. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  65486. if (!this._isVisibilityBoxLocked) {
  65487. this.mesh.refreshBoundingInfo();
  65488. }
  65489. return this;
  65490. };
  65491. /**
  65492. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  65493. * @param size the size (float) of the visibility box
  65494. * note : this doesn't lock the SPS mesh bounding box.
  65495. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65496. */
  65497. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  65498. var vis = size / 2;
  65499. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  65500. };
  65501. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  65502. /**
  65503. * Gets whether the SPS as always visible or not
  65504. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65505. */
  65506. get: function () {
  65507. return this._alwaysVisible;
  65508. },
  65509. /**
  65510. * Sets the SPS as always visible or not
  65511. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65512. */
  65513. set: function (val) {
  65514. this._alwaysVisible = val;
  65515. this.mesh.alwaysSelectAsActiveMesh = val;
  65516. },
  65517. enumerable: true,
  65518. configurable: true
  65519. });
  65520. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  65521. /**
  65522. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65523. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65524. */
  65525. get: function () {
  65526. return this._isVisibilityBoxLocked;
  65527. },
  65528. /**
  65529. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65530. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65531. */
  65532. set: function (val) {
  65533. this._isVisibilityBoxLocked = val;
  65534. var boundingInfo = this.mesh.getBoundingInfo();
  65535. boundingInfo.isLocked = val;
  65536. },
  65537. enumerable: true,
  65538. configurable: true
  65539. });
  65540. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  65541. /**
  65542. * Gets if `setParticles()` computes the particle rotations or not.
  65543. * Default value : true. The SPS is faster when it's set to false.
  65544. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65545. */
  65546. get: function () {
  65547. return this._computeParticleRotation;
  65548. },
  65549. /**
  65550. * Tells to `setParticles()` to compute the particle rotations or not.
  65551. * Default value : true. The SPS is faster when it's set to false.
  65552. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65553. */
  65554. set: function (val) {
  65555. this._computeParticleRotation = val;
  65556. },
  65557. enumerable: true,
  65558. configurable: true
  65559. });
  65560. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  65561. /**
  65562. * Gets if `setParticles()` computes the particle colors or not.
  65563. * Default value : true. The SPS is faster when it's set to false.
  65564. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65565. */
  65566. get: function () {
  65567. return this._computeParticleColor;
  65568. },
  65569. /**
  65570. * Tells to `setParticles()` to compute the particle colors or not.
  65571. * Default value : true. The SPS is faster when it's set to false.
  65572. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65573. */
  65574. set: function (val) {
  65575. this._computeParticleColor = val;
  65576. },
  65577. enumerable: true,
  65578. configurable: true
  65579. });
  65580. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  65581. /**
  65582. * Gets if `setParticles()` computes the particle textures or not.
  65583. * Default value : true. The SPS is faster when it's set to false.
  65584. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  65585. */
  65586. get: function () {
  65587. return this._computeParticleTexture;
  65588. },
  65589. set: function (val) {
  65590. this._computeParticleTexture = val;
  65591. },
  65592. enumerable: true,
  65593. configurable: true
  65594. });
  65595. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  65596. /**
  65597. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  65598. * Default value : false. The SPS is faster when it's set to false.
  65599. * Note : the particle custom vertex positions aren't stored values.
  65600. */
  65601. get: function () {
  65602. return this._computeParticleVertex;
  65603. },
  65604. /**
  65605. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  65606. * Default value : false. The SPS is faster when it's set to false.
  65607. * Note : the particle custom vertex positions aren't stored values.
  65608. */
  65609. set: function (val) {
  65610. this._computeParticleVertex = val;
  65611. },
  65612. enumerable: true,
  65613. configurable: true
  65614. });
  65615. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  65616. /**
  65617. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  65618. */
  65619. get: function () {
  65620. return this._computeBoundingBox;
  65621. },
  65622. /**
  65623. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  65624. */
  65625. set: function (val) {
  65626. this._computeBoundingBox = val;
  65627. },
  65628. enumerable: true,
  65629. configurable: true
  65630. });
  65631. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  65632. /**
  65633. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  65634. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65635. * Default : `true`
  65636. */
  65637. get: function () {
  65638. return this._depthSortParticles;
  65639. },
  65640. /**
  65641. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  65642. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65643. * Default : `true`
  65644. */
  65645. set: function (val) {
  65646. this._depthSortParticles = val;
  65647. },
  65648. enumerable: true,
  65649. configurable: true
  65650. });
  65651. // =======================================================================
  65652. // Particle behavior logic
  65653. // these following methods may be overwritten by the user to fit his needs
  65654. /**
  65655. * This function does nothing. It may be overwritten to set all the particle first values.
  65656. * The SPS doesn't call this function, you may have to call it by your own.
  65657. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65658. */
  65659. SolidParticleSystem.prototype.initParticles = function () {
  65660. };
  65661. /**
  65662. * This function does nothing. It may be overwritten to recycle a particle.
  65663. * The SPS doesn't call this function, you may have to call it by your own.
  65664. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65665. * @param particle The particle to recycle
  65666. * @returns the recycled particle
  65667. */
  65668. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  65669. return particle;
  65670. };
  65671. /**
  65672. * Updates a particle : this function should be overwritten by the user.
  65673. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  65674. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65675. * @example : just set a particle position or velocity and recycle conditions
  65676. * @param particle The particle to update
  65677. * @returns the updated particle
  65678. */
  65679. SolidParticleSystem.prototype.updateParticle = function (particle) {
  65680. return particle;
  65681. };
  65682. /**
  65683. * Updates a vertex of a particle : it can be overwritten by the user.
  65684. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  65685. * @param particle the current particle
  65686. * @param vertex the current index of the current particle
  65687. * @param pt the index of the current vertex in the particle shape
  65688. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  65689. * @example : just set a vertex particle position
  65690. * @returns the updated vertex
  65691. */
  65692. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  65693. return vertex;
  65694. };
  65695. /**
  65696. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  65697. * This does nothing and may be overwritten by the user.
  65698. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65699. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65700. * @param update the boolean update value actually passed to setParticles()
  65701. */
  65702. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  65703. };
  65704. /**
  65705. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  65706. * This will be passed three parameters.
  65707. * This does nothing and may be overwritten by the user.
  65708. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65709. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65710. * @param update the boolean update value actually passed to setParticles()
  65711. */
  65712. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  65713. };
  65714. return SolidParticleSystem;
  65715. }());
  65716. BABYLON.SolidParticleSystem = SolidParticleSystem;
  65717. })(BABYLON || (BABYLON = {}));
  65718. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  65719. var BABYLON;
  65720. (function (BABYLON) {
  65721. /**
  65722. * Class containing static functions to help procedurally build meshes
  65723. */
  65724. var MeshBuilder = /** @class */ (function () {
  65725. function MeshBuilder() {
  65726. }
  65727. MeshBuilder.updateSideOrientation = function (orientation) {
  65728. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  65729. return BABYLON.Mesh.DOUBLESIDE;
  65730. }
  65731. if (orientation === undefined || orientation === null) {
  65732. return BABYLON.Mesh.FRONTSIDE;
  65733. }
  65734. return orientation;
  65735. };
  65736. /**
  65737. * Creates a box mesh
  65738. * * The parameter `size` sets the size (float) of each box side (default 1)
  65739. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  65740. * * 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)
  65741. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  65742. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65743. * * 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
  65744. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65745. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  65746. * @param name defines the name of the mesh
  65747. * @param options defines the options used to create the mesh
  65748. * @param scene defines the hosting scene
  65749. * @returns the box mesh
  65750. */
  65751. MeshBuilder.CreateBox = function (name, options, scene) {
  65752. if (scene === void 0) { scene = null; }
  65753. var box = new BABYLON.Mesh(name, scene);
  65754. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65755. box._originalBuilderSideOrientation = options.sideOrientation;
  65756. var vertexData = BABYLON.VertexData.CreateBox(options);
  65757. vertexData.applyToMesh(box, options.updatable);
  65758. return box;
  65759. };
  65760. /**
  65761. * Creates a sphere mesh
  65762. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  65763. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value of `diameter`)
  65764. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  65765. * * 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
  65766. * * 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)
  65767. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65768. * * 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
  65769. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65770. * @param name defines the name of the mesh
  65771. * @param options defines the options used to create the mesh
  65772. * @param scene defines the hosting scene
  65773. * @returns the sphere mesh
  65774. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  65775. */
  65776. MeshBuilder.CreateSphere = function (name, options, scene) {
  65777. var sphere = new BABYLON.Mesh(name, scene);
  65778. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65779. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65780. var vertexData = BABYLON.VertexData.CreateSphere(options);
  65781. vertexData.applyToMesh(sphere, options.updatable);
  65782. return sphere;
  65783. };
  65784. /**
  65785. * Creates a plane polygonal mesh. By default, this is a disc
  65786. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  65787. * * 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
  65788. * * 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
  65789. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65790. * * 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
  65791. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65792. * @param name defines the name of the mesh
  65793. * @param options defines the options used to create the mesh
  65794. * @param scene defines the hosting scene
  65795. * @returns the plane polygonal mesh
  65796. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  65797. */
  65798. MeshBuilder.CreateDisc = function (name, options, scene) {
  65799. if (scene === void 0) { scene = null; }
  65800. var disc = new BABYLON.Mesh(name, scene);
  65801. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65802. disc._originalBuilderSideOrientation = options.sideOrientation;
  65803. var vertexData = BABYLON.VertexData.CreateDisc(options);
  65804. vertexData.applyToMesh(disc, options.updatable);
  65805. return disc;
  65806. };
  65807. /**
  65808. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  65809. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  65810. * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value of `radius`)
  65811. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  65812. * * 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
  65813. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65814. * * 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
  65815. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65816. * @param name defines the name of the mesh
  65817. * @param options defines the options used to create the mesh
  65818. * @param scene defines the hosting scene
  65819. * @returns the icosahedron mesh
  65820. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  65821. */
  65822. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  65823. var sphere = new BABYLON.Mesh(name, scene);
  65824. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65825. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65826. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  65827. vertexData.applyToMesh(sphere, options.updatable);
  65828. return sphere;
  65829. };
  65830. ;
  65831. /**
  65832. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  65833. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  65834. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  65835. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  65836. * * 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
  65837. * * 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
  65838. * * 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
  65839. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65840. * * 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
  65841. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65842. * * 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
  65843. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  65844. * * 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
  65845. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  65846. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65847. * @param name defines the name of the mesh
  65848. * @param options defines the options used to create the mesh
  65849. * @param scene defines the hosting scene
  65850. * @returns the ribbon mesh
  65851. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  65852. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65853. */
  65854. MeshBuilder.CreateRibbon = function (name, options, scene) {
  65855. if (scene === void 0) { scene = null; }
  65856. var pathArray = options.pathArray;
  65857. var closeArray = options.closeArray;
  65858. var closePath = options.closePath;
  65859. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65860. var instance = options.instance;
  65861. var updatable = options.updatable;
  65862. if (instance) { // existing ribbon instance update
  65863. // positionFunction : ribbon case
  65864. // only pathArray and sideOrientation parameters are taken into account for positions update
  65865. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  65866. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  65867. var positionFunction = function (positions) {
  65868. var minlg = pathArray[0].length;
  65869. var i = 0;
  65870. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  65871. for (var si = 1; si <= ns; si++) {
  65872. for (var p = 0; p < pathArray.length; p++) {
  65873. var path = pathArray[p];
  65874. var l = path.length;
  65875. minlg = (minlg < l) ? minlg : l;
  65876. var j = 0;
  65877. while (j < minlg) {
  65878. positions[i] = path[j].x;
  65879. positions[i + 1] = path[j].y;
  65880. positions[i + 2] = path[j].z;
  65881. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  65882. BABYLON.Tmp.Vector3[0].x = path[j].x;
  65883. }
  65884. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  65885. BABYLON.Tmp.Vector3[1].x = path[j].x;
  65886. }
  65887. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  65888. BABYLON.Tmp.Vector3[0].y = path[j].y;
  65889. }
  65890. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  65891. BABYLON.Tmp.Vector3[1].y = path[j].y;
  65892. }
  65893. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  65894. BABYLON.Tmp.Vector3[0].z = path[j].z;
  65895. }
  65896. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  65897. BABYLON.Tmp.Vector3[1].z = path[j].z;
  65898. }
  65899. j++;
  65900. i += 3;
  65901. }
  65902. if (instance._closePath) {
  65903. positions[i] = path[0].x;
  65904. positions[i + 1] = path[0].y;
  65905. positions[i + 2] = path[0].z;
  65906. i += 3;
  65907. }
  65908. }
  65909. }
  65910. };
  65911. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65912. positionFunction(positions);
  65913. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  65914. instance._boundingInfo.update(instance._worldMatrix);
  65915. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  65916. if (options.colors) {
  65917. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65918. for (var c = 0; c < options.colors.length; c++) {
  65919. colors[c * 4] = options.colors[c].r;
  65920. colors[c * 4 + 1] = options.colors[c].g;
  65921. colors[c * 4 + 2] = options.colors[c].b;
  65922. colors[c * 4 + 3] = options.colors[c].a;
  65923. }
  65924. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  65925. }
  65926. if (options.uvs) {
  65927. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65928. for (var i = 0; i < options.uvs.length; i++) {
  65929. uvs[i * 2] = options.uvs[i].x;
  65930. uvs[i * 2 + 1] = options.uvs[i].y;
  65931. }
  65932. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  65933. }
  65934. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  65935. var indices = instance.getIndices();
  65936. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65937. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  65938. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  65939. if (instance._closePath) {
  65940. var indexFirst = 0;
  65941. var indexLast = 0;
  65942. for (var p = 0; p < pathArray.length; p++) {
  65943. indexFirst = instance._idx[p] * 3;
  65944. if (p + 1 < pathArray.length) {
  65945. indexLast = (instance._idx[p + 1] - 1) * 3;
  65946. }
  65947. else {
  65948. indexLast = normals.length - 3;
  65949. }
  65950. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  65951. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  65952. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  65953. normals[indexLast] = normals[indexFirst];
  65954. normals[indexLast + 1] = normals[indexFirst + 1];
  65955. normals[indexLast + 2] = normals[indexFirst + 2];
  65956. }
  65957. }
  65958. if (!(instance.areNormalsFrozen)) {
  65959. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  65960. }
  65961. }
  65962. return instance;
  65963. }
  65964. else { // new ribbon creation
  65965. var ribbon = new BABYLON.Mesh(name, scene);
  65966. ribbon._originalBuilderSideOrientation = sideOrientation;
  65967. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  65968. if (closePath) {
  65969. ribbon._idx = vertexData._idx;
  65970. }
  65971. ribbon._closePath = closePath;
  65972. ribbon._closeArray = closeArray;
  65973. vertexData.applyToMesh(ribbon, updatable);
  65974. return ribbon;
  65975. }
  65976. };
  65977. /**
  65978. * Creates a cylinder or a cone mesh
  65979. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  65980. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  65981. * * 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.
  65982. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  65983. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  65984. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  65985. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  65986. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  65987. * * 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).
  65988. * * 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
  65989. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  65990. * * 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
  65991. * * 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.
  65992. * * If `enclose` is false, a ring surface is one element.
  65993. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  65994. * * 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
  65995. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65996. * * 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
  65997. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65998. * @param name defines the name of the mesh
  65999. * @param options defines the options used to create the mesh
  66000. * @param scene defines the hosting scene
  66001. * @returns the cylinder mesh
  66002. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  66003. */
  66004. MeshBuilder.CreateCylinder = function (name, options, scene) {
  66005. var cylinder = new BABYLON.Mesh(name, scene);
  66006. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66007. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  66008. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  66009. vertexData.applyToMesh(cylinder, options.updatable);
  66010. return cylinder;
  66011. };
  66012. /**
  66013. * Creates a torus mesh
  66014. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  66015. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  66016. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  66017. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66018. * * 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
  66019. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66020. * @param name defines the name of the mesh
  66021. * @param options defines the options used to create the mesh
  66022. * @param scene defines the hosting scene
  66023. * @returns the torus mesh
  66024. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  66025. */
  66026. MeshBuilder.CreateTorus = function (name, options, scene) {
  66027. var torus = new BABYLON.Mesh(name, scene);
  66028. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66029. torus._originalBuilderSideOrientation = options.sideOrientation;
  66030. var vertexData = BABYLON.VertexData.CreateTorus(options);
  66031. vertexData.applyToMesh(torus, options.updatable);
  66032. return torus;
  66033. };
  66034. /**
  66035. * Creates a torus knot mesh
  66036. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  66037. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  66038. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  66039. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  66040. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66041. * * 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
  66042. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66043. * @param name defines the name of the mesh
  66044. * @param options defines the options used to create the mesh
  66045. * @param scene defines the hosting scene
  66046. * @returns the torus knot mesh
  66047. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  66048. */
  66049. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  66050. var torusKnot = new BABYLON.Mesh(name, scene);
  66051. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66052. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  66053. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  66054. vertexData.applyToMesh(torusKnot, options.updatable);
  66055. return torusKnot;
  66056. };
  66057. /**
  66058. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  66059. * * 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
  66060. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  66061. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  66062. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  66063. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  66064. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  66065. * * 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
  66066. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  66067. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66068. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  66069. * @param name defines the name of the new line system
  66070. * @param options defines the options used to create the line system
  66071. * @param scene defines the hosting scene
  66072. * @returns a new line system mesh
  66073. */
  66074. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  66075. var instance = options.instance;
  66076. var lines = options.lines;
  66077. var colors = options.colors;
  66078. if (instance) { // lines update
  66079. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66080. var vertexColor;
  66081. var lineColors;
  66082. if (colors) {
  66083. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66084. }
  66085. var i = 0;
  66086. var c = 0;
  66087. for (var l = 0; l < lines.length; l++) {
  66088. var points = lines[l];
  66089. for (var p = 0; p < points.length; p++) {
  66090. positions[i] = points[p].x;
  66091. positions[i + 1] = points[p].y;
  66092. positions[i + 2] = points[p].z;
  66093. if (colors && vertexColor) {
  66094. lineColors = colors[l];
  66095. vertexColor[c] = lineColors[p].r;
  66096. vertexColor[c + 1] = lineColors[p].g;
  66097. vertexColor[c + 2] = lineColors[p].b;
  66098. vertexColor[c + 3] = lineColors[p].a;
  66099. c += 4;
  66100. }
  66101. i += 3;
  66102. }
  66103. }
  66104. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  66105. if (colors && vertexColor) {
  66106. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  66107. }
  66108. return instance;
  66109. }
  66110. // line system creation
  66111. var useVertexColor = (colors) ? true : false;
  66112. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  66113. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  66114. vertexData.applyToMesh(lineSystem, options.updatable);
  66115. return lineSystem;
  66116. };
  66117. /**
  66118. * Creates a line mesh
  66119. * 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
  66120. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  66121. * * The parameter `points` is an array successive Vector3
  66122. * * 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
  66123. * * The optional parameter `colors` is an array of successive Color4, one per line point
  66124. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  66125. * * When updating an instance, remember that only point positions can change, not the number of points
  66126. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66127. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  66128. * @param name defines the name of the new line system
  66129. * @param options defines the options used to create the line system
  66130. * @param scene defines the hosting scene
  66131. * @returns a new line mesh
  66132. */
  66133. MeshBuilder.CreateLines = function (name, options, scene) {
  66134. if (scene === void 0) { scene = null; }
  66135. var colors = (options.colors) ? [options.colors] : null;
  66136. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  66137. return lines;
  66138. };
  66139. /**
  66140. * Creates a dashed line mesh
  66141. * * 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
  66142. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  66143. * * The parameter `points` is an array successive Vector3
  66144. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  66145. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  66146. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  66147. * * 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
  66148. * * When updating an instance, remember that only point positions can change, not the number of points
  66149. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66150. * @param name defines the name of the mesh
  66151. * @param options defines the options used to create the mesh
  66152. * @param scene defines the hosting scene
  66153. * @returns the dashed line mesh
  66154. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  66155. */
  66156. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  66157. if (scene === void 0) { scene = null; }
  66158. var points = options.points;
  66159. var instance = options.instance;
  66160. var gapSize = options.gapSize || 1;
  66161. var dashSize = options.dashSize || 3;
  66162. if (instance) { // dashed lines update
  66163. var positionFunction = function (positions) {
  66164. var curvect = BABYLON.Vector3.Zero();
  66165. var nbSeg = positions.length / 6;
  66166. var lg = 0;
  66167. var nb = 0;
  66168. var shft = 0;
  66169. var dashshft = 0;
  66170. var curshft = 0;
  66171. var p = 0;
  66172. var i = 0;
  66173. var j = 0;
  66174. for (i = 0; i < points.length - 1; i++) {
  66175. points[i + 1].subtractToRef(points[i], curvect);
  66176. lg += curvect.length();
  66177. }
  66178. shft = lg / nbSeg;
  66179. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  66180. for (i = 0; i < points.length - 1; i++) {
  66181. points[i + 1].subtractToRef(points[i], curvect);
  66182. nb = Math.floor(curvect.length() / shft);
  66183. curvect.normalize();
  66184. j = 0;
  66185. while (j < nb && p < positions.length) {
  66186. curshft = shft * j;
  66187. positions[p] = points[i].x + curshft * curvect.x;
  66188. positions[p + 1] = points[i].y + curshft * curvect.y;
  66189. positions[p + 2] = points[i].z + curshft * curvect.z;
  66190. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  66191. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  66192. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  66193. p += 6;
  66194. j++;
  66195. }
  66196. }
  66197. while (p < positions.length) {
  66198. positions[p] = points[i].x;
  66199. positions[p + 1] = points[i].y;
  66200. positions[p + 2] = points[i].z;
  66201. p += 3;
  66202. }
  66203. };
  66204. instance.updateMeshPositions(positionFunction, false);
  66205. return instance;
  66206. }
  66207. // dashed lines creation
  66208. var dashedLines = new BABYLON.LinesMesh(name, scene);
  66209. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  66210. vertexData.applyToMesh(dashedLines, options.updatable);
  66211. dashedLines.dashSize = dashSize;
  66212. dashedLines.gapSize = gapSize;
  66213. return dashedLines;
  66214. };
  66215. /**
  66216. * 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.
  66217. * * 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.
  66218. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  66219. * * 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.
  66220. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  66221. * * 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
  66222. * * 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
  66223. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  66224. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66225. * * 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
  66226. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  66227. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66228. * @param name defines the name of the mesh
  66229. * @param options defines the options used to create the mesh
  66230. * @param scene defines the hosting scene
  66231. * @returns the extruded shape mesh
  66232. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66233. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66234. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66235. */
  66236. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  66237. if (scene === void 0) { scene = null; }
  66238. var path = options.path;
  66239. var shape = options.shape;
  66240. var scale = options.scale || 1;
  66241. var rotation = options.rotation || 0;
  66242. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66243. var updatable = options.updatable;
  66244. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66245. var instance = options.instance || null;
  66246. var invertUV = options.invertUV || false;
  66247. 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);
  66248. };
  66249. /**
  66250. * Creates an custom extruded shape mesh.
  66251. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  66252. * * 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.
  66253. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  66254. * * 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
  66255. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  66256. * * 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
  66257. * * It must returns a float value that will be the scale value applied to the shape on each path point
  66258. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  66259. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  66260. * * 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
  66261. * * 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
  66262. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  66263. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66264. * * 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
  66265. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66266. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66267. * @param name defines the name of the mesh
  66268. * @param options defines the options used to create the mesh
  66269. * @param scene defines the hosting scene
  66270. * @returns the custom extruded shape mesh
  66271. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  66272. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66273. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66274. */
  66275. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  66276. var path = options.path;
  66277. var shape = options.shape;
  66278. var scaleFunction = options.scaleFunction || (function () { return 1; });
  66279. var rotationFunction = options.rotationFunction || (function () { return 0; });
  66280. var ribbonCloseArray = options.ribbonCloseArray || false;
  66281. var ribbonClosePath = options.ribbonClosePath || false;
  66282. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66283. var updatable = options.updatable;
  66284. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66285. var instance = options.instance;
  66286. var invertUV = options.invertUV || false;
  66287. 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);
  66288. };
  66289. /**
  66290. * Creates lathe mesh.
  66291. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  66292. * * 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
  66293. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  66294. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  66295. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  66296. * * 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
  66297. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  66298. * * 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
  66299. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66300. * * 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
  66301. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66302. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66303. * @param name defines the name of the mesh
  66304. * @param options defines the options used to create the mesh
  66305. * @param scene defines the hosting scene
  66306. * @returns the lathe mesh
  66307. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  66308. */
  66309. MeshBuilder.CreateLathe = function (name, options, scene) {
  66310. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  66311. var closed = (options.closed === undefined) ? true : options.closed;
  66312. var shape = options.shape;
  66313. var radius = options.radius || 1;
  66314. var tessellation = options.tessellation || 64;
  66315. var clip = options.clip || 0;
  66316. var updatable = options.updatable;
  66317. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66318. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66319. var pi2 = Math.PI * 2;
  66320. var paths = new Array();
  66321. var invertUV = options.invertUV || false;
  66322. var i = 0;
  66323. var p = 0;
  66324. var step = pi2 / tessellation * arc;
  66325. var rotated;
  66326. var path = new Array();
  66327. for (i = 0; i <= tessellation - clip; i++) {
  66328. var path = [];
  66329. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  66330. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  66331. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  66332. }
  66333. for (p = 0; p < shape.length; p++) {
  66334. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  66335. path.push(rotated);
  66336. }
  66337. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  66338. 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));
  66339. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  66340. }
  66341. paths.push(path);
  66342. }
  66343. // lathe ribbon
  66344. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66345. return lathe;
  66346. };
  66347. /**
  66348. * Creates a plane mesh
  66349. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  66350. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  66351. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  66352. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66353. * * 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
  66354. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66355. * @param name defines the name of the mesh
  66356. * @param options defines the options used to create the mesh
  66357. * @param scene defines the hosting scene
  66358. * @returns the plane mesh
  66359. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66360. */
  66361. MeshBuilder.CreatePlane = function (name, options, scene) {
  66362. var plane = new BABYLON.Mesh(name, scene);
  66363. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66364. plane._originalBuilderSideOrientation = options.sideOrientation;
  66365. var vertexData = BABYLON.VertexData.CreatePlane(options);
  66366. vertexData.applyToMesh(plane, options.updatable);
  66367. if (options.sourcePlane) {
  66368. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  66369. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  66370. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  66371. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  66372. plane.rotate(vectorProduct, product);
  66373. }
  66374. }
  66375. return plane;
  66376. };
  66377. /**
  66378. * Creates a ground mesh
  66379. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  66380. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  66381. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66382. * @param name defines the name of the mesh
  66383. * @param options defines the options used to create the mesh
  66384. * @param scene defines the hosting scene
  66385. * @returns the ground mesh
  66386. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66387. */
  66388. MeshBuilder.CreateGround = function (name, options, scene) {
  66389. var ground = new BABYLON.GroundMesh(name, scene);
  66390. ground._setReady(false);
  66391. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  66392. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  66393. ground._width = options.width || 1;
  66394. ground._height = options.height || 1;
  66395. ground._maxX = ground._width / 2;
  66396. ground._maxZ = ground._height / 2;
  66397. ground._minX = -ground._maxX;
  66398. ground._minZ = -ground._maxZ;
  66399. var vertexData = BABYLON.VertexData.CreateGround(options);
  66400. vertexData.applyToMesh(ground, options.updatable);
  66401. ground._setReady(true);
  66402. return ground;
  66403. };
  66404. /**
  66405. * Creates a tiled ground mesh
  66406. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  66407. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  66408. * * 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
  66409. * * 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
  66410. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66411. * @param name defines the name of the mesh
  66412. * @param options defines the options used to create the mesh
  66413. * @param scene defines the hosting scene
  66414. * @returns the tiled ground mesh
  66415. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  66416. */
  66417. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  66418. var tiledGround = new BABYLON.Mesh(name, scene);
  66419. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  66420. vertexData.applyToMesh(tiledGround, options.updatable);
  66421. return tiledGround;
  66422. };
  66423. /**
  66424. * Creates a ground mesh from a height map
  66425. * * The parameter `url` sets the URL of the height map image resource.
  66426. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  66427. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  66428. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  66429. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  66430. * * 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.
  66431. * * 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).
  66432. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  66433. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66434. * @param name defines the name of the mesh
  66435. * @param url defines the url to the height map
  66436. * @param options defines the options used to create the mesh
  66437. * @param scene defines the hosting scene
  66438. * @returns the ground mesh
  66439. * @see http://doc.babylonjs.com/babylon101/height_map
  66440. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  66441. */
  66442. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  66443. var width = options.width || 10.0;
  66444. var height = options.height || 10.0;
  66445. var subdivisions = options.subdivisions || 1 | 0;
  66446. var minHeight = options.minHeight || 0.0;
  66447. var maxHeight = options.maxHeight || 1.0;
  66448. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  66449. var alphaFilter = options.alphaFilter || 0.0;
  66450. var updatable = options.updatable;
  66451. var onReady = options.onReady;
  66452. var ground = new BABYLON.GroundMesh(name, scene);
  66453. ground._subdivisionsX = subdivisions;
  66454. ground._subdivisionsY = subdivisions;
  66455. ground._width = width;
  66456. ground._height = height;
  66457. ground._maxX = ground._width / 2.0;
  66458. ground._maxZ = ground._height / 2.0;
  66459. ground._minX = -ground._maxX;
  66460. ground._minZ = -ground._maxZ;
  66461. ground._setReady(false);
  66462. var onload = function (img) {
  66463. // Getting height map data
  66464. var canvas = document.createElement("canvas");
  66465. var context = canvas.getContext("2d");
  66466. if (!context) {
  66467. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  66468. }
  66469. if (scene.isDisposed) {
  66470. return;
  66471. }
  66472. var bufferWidth = img.width;
  66473. var bufferHeight = img.height;
  66474. canvas.width = bufferWidth;
  66475. canvas.height = bufferHeight;
  66476. context.drawImage(img, 0, 0);
  66477. // Create VertexData from map data
  66478. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  66479. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  66480. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  66481. width: width, height: height,
  66482. subdivisions: subdivisions,
  66483. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  66484. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  66485. alphaFilter: alphaFilter
  66486. });
  66487. vertexData.applyToMesh(ground, updatable);
  66488. //execute ready callback, if set
  66489. if (onReady) {
  66490. onReady(ground);
  66491. }
  66492. ground._setReady(true);
  66493. };
  66494. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  66495. return ground;
  66496. };
  66497. /**
  66498. * Creates a polygon mesh
  66499. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  66500. * * 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
  66501. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66502. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66503. * * 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)
  66504. * * Remember you can only change the shape positions, not their number when updating a polygon
  66505. * @param name defines the name of the mesh
  66506. * @param options defines the options used to create the mesh
  66507. * @param scene defines the hosting scene
  66508. * @returns the polygon mesh
  66509. */
  66510. MeshBuilder.CreatePolygon = function (name, options, scene) {
  66511. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66512. var shape = options.shape;
  66513. var holes = options.holes || [];
  66514. var depth = options.depth || 0;
  66515. var contours = [];
  66516. var hole = [];
  66517. for (var i = 0; i < shape.length; i++) {
  66518. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  66519. }
  66520. var epsilon = 0.00000001;
  66521. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  66522. contours.pop();
  66523. }
  66524. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  66525. for (var hNb = 0; hNb < holes.length; hNb++) {
  66526. hole = [];
  66527. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  66528. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  66529. }
  66530. polygonTriangulation.addHole(hole);
  66531. }
  66532. var polygon = polygonTriangulation.build(options.updatable, depth);
  66533. polygon._originalBuilderSideOrientation = options.sideOrientation;
  66534. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  66535. vertexData.applyToMesh(polygon, options.updatable);
  66536. return polygon;
  66537. };
  66538. ;
  66539. /**
  66540. * Creates an extruded polygon mesh, with depth in the Y direction.
  66541. * * 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)
  66542. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66543. * @param name defines the name of the mesh
  66544. * @param options defines the options used to create the mesh
  66545. * @param scene defines the hosting scene
  66546. * @returns the polygon mesh
  66547. */
  66548. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  66549. return MeshBuilder.CreatePolygon(name, options, scene);
  66550. };
  66551. ;
  66552. /**
  66553. * Creates a tube mesh.
  66554. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66555. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  66556. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  66557. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  66558. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  66559. * * 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)
  66560. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  66561. * * 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
  66562. * * 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
  66563. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66564. * * 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
  66565. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66566. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66567. * @param name defines the name of the mesh
  66568. * @param options defines the options used to create the mesh
  66569. * @param scene defines the hosting scene
  66570. * @returns the tube mesh
  66571. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66572. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  66573. */
  66574. MeshBuilder.CreateTube = function (name, options, scene) {
  66575. var path = options.path;
  66576. var instance = options.instance;
  66577. var radius = 1.0;
  66578. if (instance) {
  66579. radius = instance.radius;
  66580. }
  66581. if (options.radius !== undefined) {
  66582. radius = options.radius;
  66583. }
  66584. ;
  66585. var tessellation = options.tessellation || 64 | 0;
  66586. var radiusFunction = options.radiusFunction || null;
  66587. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66588. var invertUV = options.invertUV || false;
  66589. var updatable = options.updatable;
  66590. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66591. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  66592. // tube geometry
  66593. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  66594. var tangents = path3D.getTangents();
  66595. var normals = path3D.getNormals();
  66596. var distances = path3D.getDistances();
  66597. var pi2 = Math.PI * 2;
  66598. var step = pi2 / tessellation * arc;
  66599. var returnRadius = function () { return radius; };
  66600. var radiusFunctionFinal = radiusFunction || returnRadius;
  66601. var circlePath;
  66602. var rad;
  66603. var normal;
  66604. var rotated;
  66605. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66606. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66607. for (var i = 0; i < path.length; i++) {
  66608. rad = radiusFunctionFinal(i, distances[i]); // current radius
  66609. circlePath = Array(); // current circle array
  66610. normal = normals[i]; // current normal
  66611. for (var t = 0; t < tessellation; t++) {
  66612. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  66613. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  66614. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  66615. rotated.scaleInPlace(rad).addInPlace(path[i]);
  66616. circlePath[t] = rotated;
  66617. }
  66618. circlePaths[index] = circlePath;
  66619. index++;
  66620. }
  66621. // cap
  66622. var capPath = function (nbPoints, pathIndex) {
  66623. var pointCap = Array();
  66624. for (var i = 0; i < nbPoints; i++) {
  66625. pointCap.push(path[pathIndex]);
  66626. }
  66627. return pointCap;
  66628. };
  66629. switch (cap) {
  66630. case BABYLON.Mesh.NO_CAP:
  66631. break;
  66632. case BABYLON.Mesh.CAP_START:
  66633. circlePaths[0] = capPath(tessellation, 0);
  66634. circlePaths[1] = circlePaths[2].slice(0);
  66635. break;
  66636. case BABYLON.Mesh.CAP_END:
  66637. circlePaths[index] = circlePaths[index - 1].slice(0);
  66638. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66639. break;
  66640. case BABYLON.Mesh.CAP_ALL:
  66641. circlePaths[0] = capPath(tessellation, 0);
  66642. circlePaths[1] = circlePaths[2].slice(0);
  66643. circlePaths[index] = circlePaths[index - 1].slice(0);
  66644. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66645. break;
  66646. default:
  66647. break;
  66648. }
  66649. return circlePaths;
  66650. };
  66651. var path3D;
  66652. var pathArray;
  66653. if (instance) { // tube update
  66654. var arc = options.arc || instance.arc;
  66655. path3D = (instance.path3D).update(path);
  66656. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  66657. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  66658. instance.path3D = path3D;
  66659. instance.pathArray = pathArray;
  66660. instance.arc = arc;
  66661. instance.radius = radius;
  66662. return instance;
  66663. }
  66664. // tube creation
  66665. path3D = new BABYLON.Path3D(path);
  66666. var newPathArray = new Array();
  66667. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66668. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  66669. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66670. tube.pathArray = pathArray;
  66671. tube.path3D = path3D;
  66672. tube.tessellation = tessellation;
  66673. tube.cap = cap;
  66674. tube.arc = options.arc;
  66675. tube.radius = radius;
  66676. return tube;
  66677. };
  66678. /**
  66679. * Creates a polyhedron mesh
  66680. * * 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
  66681. * * The parameter `size` (positive float, default 1) sets the polygon size
  66682. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  66683. * * 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`
  66684. * * 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
  66685. * * 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)`)
  66686. * * 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
  66687. * * 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
  66688. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66689. * * 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
  66690. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66691. * @param name defines the name of the mesh
  66692. * @param options defines the options used to create the mesh
  66693. * @param scene defines the hosting scene
  66694. * @returns the polyhedron mesh
  66695. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  66696. */
  66697. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  66698. var polyhedron = new BABYLON.Mesh(name, scene);
  66699. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66700. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  66701. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  66702. vertexData.applyToMesh(polyhedron, options.updatable);
  66703. return polyhedron;
  66704. };
  66705. /**
  66706. * Creates a decal mesh.
  66707. * 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
  66708. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  66709. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  66710. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  66711. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  66712. * @param name defines the name of the mesh
  66713. * @param sourceMesh defines the mesh where the decal must be applied
  66714. * @param options defines the options used to create the mesh
  66715. * @param scene defines the hosting scene
  66716. * @returns the decal mesh
  66717. * @see http://doc.babylonjs.com/how_to/decals
  66718. */
  66719. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  66720. var indices = sourceMesh.getIndices();
  66721. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66722. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66723. var position = options.position || BABYLON.Vector3.Zero();
  66724. var normal = options.normal || BABYLON.Vector3.Up();
  66725. var size = options.size || BABYLON.Vector3.One();
  66726. var angle = options.angle || 0;
  66727. // Getting correct rotation
  66728. if (!normal) {
  66729. var target = new BABYLON.Vector3(0, 0, 1);
  66730. var camera = sourceMesh.getScene().activeCamera;
  66731. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  66732. normal = camera.globalPosition.subtract(cameraWorldTarget);
  66733. }
  66734. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  66735. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  66736. var pitch = Math.atan2(normal.y, len);
  66737. // Matrix
  66738. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  66739. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  66740. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  66741. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  66742. var vertexData = new BABYLON.VertexData();
  66743. vertexData.indices = [];
  66744. vertexData.positions = [];
  66745. vertexData.normals = [];
  66746. vertexData.uvs = [];
  66747. var currentVertexDataIndex = 0;
  66748. var extractDecalVector3 = function (indexId) {
  66749. var result = new BABYLON.PositionNormalVertex();
  66750. if (!indices || !positions || !normals) {
  66751. return result;
  66752. }
  66753. var vertexId = indices[indexId];
  66754. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  66755. // Send vector to decal local world
  66756. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  66757. // Get normal
  66758. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  66759. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  66760. return result;
  66761. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  66762. var clip = function (vertices, axis) {
  66763. if (vertices.length === 0) {
  66764. return vertices;
  66765. }
  66766. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  66767. var clipVertices = function (v0, v1) {
  66768. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  66769. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  66770. };
  66771. var result = new Array();
  66772. for (var index = 0; index < vertices.length; index += 3) {
  66773. var v1Out;
  66774. var v2Out;
  66775. var v3Out;
  66776. var total = 0;
  66777. var nV1 = null;
  66778. var nV2 = null;
  66779. var nV3 = null;
  66780. var nV4 = null;
  66781. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  66782. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  66783. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  66784. v1Out = d1 > 0;
  66785. v2Out = d2 > 0;
  66786. v3Out = d3 > 0;
  66787. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  66788. switch (total) {
  66789. case 0:
  66790. result.push(vertices[index]);
  66791. result.push(vertices[index + 1]);
  66792. result.push(vertices[index + 2]);
  66793. break;
  66794. case 1:
  66795. if (v1Out) {
  66796. nV1 = vertices[index + 1];
  66797. nV2 = vertices[index + 2];
  66798. nV3 = clipVertices(vertices[index], nV1);
  66799. nV4 = clipVertices(vertices[index], nV2);
  66800. }
  66801. if (v2Out) {
  66802. nV1 = vertices[index];
  66803. nV2 = vertices[index + 2];
  66804. nV3 = clipVertices(vertices[index + 1], nV1);
  66805. nV4 = clipVertices(vertices[index + 1], nV2);
  66806. result.push(nV3);
  66807. result.push(nV2.clone());
  66808. result.push(nV1.clone());
  66809. result.push(nV2.clone());
  66810. result.push(nV3.clone());
  66811. result.push(nV4);
  66812. break;
  66813. }
  66814. if (v3Out) {
  66815. nV1 = vertices[index];
  66816. nV2 = vertices[index + 1];
  66817. nV3 = clipVertices(vertices[index + 2], nV1);
  66818. nV4 = clipVertices(vertices[index + 2], nV2);
  66819. }
  66820. if (nV1 && nV2 && nV3 && nV4) {
  66821. result.push(nV1.clone());
  66822. result.push(nV2.clone());
  66823. result.push(nV3);
  66824. result.push(nV4);
  66825. result.push(nV3.clone());
  66826. result.push(nV2.clone());
  66827. }
  66828. break;
  66829. case 2:
  66830. if (!v1Out) {
  66831. nV1 = vertices[index].clone();
  66832. nV2 = clipVertices(nV1, vertices[index + 1]);
  66833. nV3 = clipVertices(nV1, vertices[index + 2]);
  66834. result.push(nV1);
  66835. result.push(nV2);
  66836. result.push(nV3);
  66837. }
  66838. if (!v2Out) {
  66839. nV1 = vertices[index + 1].clone();
  66840. nV2 = clipVertices(nV1, vertices[index + 2]);
  66841. nV3 = clipVertices(nV1, vertices[index]);
  66842. result.push(nV1);
  66843. result.push(nV2);
  66844. result.push(nV3);
  66845. }
  66846. if (!v3Out) {
  66847. nV1 = vertices[index + 2].clone();
  66848. nV2 = clipVertices(nV1, vertices[index]);
  66849. nV3 = clipVertices(nV1, vertices[index + 1]);
  66850. result.push(nV1);
  66851. result.push(nV2);
  66852. result.push(nV3);
  66853. }
  66854. break;
  66855. case 3:
  66856. break;
  66857. }
  66858. }
  66859. return result;
  66860. };
  66861. for (var index = 0; index < indices.length; index += 3) {
  66862. var faceVertices = new Array();
  66863. faceVertices.push(extractDecalVector3(index));
  66864. faceVertices.push(extractDecalVector3(index + 1));
  66865. faceVertices.push(extractDecalVector3(index + 2));
  66866. // Clip
  66867. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  66868. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  66869. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  66870. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  66871. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  66872. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  66873. if (faceVertices.length === 0) {
  66874. continue;
  66875. }
  66876. // Add UVs and get back to world
  66877. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  66878. var vertex = faceVertices[vIndex];
  66879. //TODO check for Int32Array | Uint32Array | Uint16Array
  66880. vertexData.indices.push(currentVertexDataIndex);
  66881. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  66882. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  66883. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  66884. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  66885. currentVertexDataIndex++;
  66886. }
  66887. }
  66888. // Return mesh
  66889. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  66890. vertexData.applyToMesh(decal);
  66891. decal.position = position.clone();
  66892. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  66893. return decal;
  66894. };
  66895. // Privates
  66896. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  66897. // extrusion geometry
  66898. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  66899. var tangents = path3D.getTangents();
  66900. var normals = path3D.getNormals();
  66901. var binormals = path3D.getBinormals();
  66902. var distances = path3D.getDistances();
  66903. var angle = 0;
  66904. var returnScale = function () { return scale !== null ? scale : 1; };
  66905. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  66906. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  66907. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  66908. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66909. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66910. for (var i = 0; i < curve.length; i++) {
  66911. var shapePath = new Array();
  66912. var angleStep = rotate(i, distances[i]);
  66913. var scaleRatio = scl(i, distances[i]);
  66914. for (var p = 0; p < shape.length; p++) {
  66915. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  66916. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  66917. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  66918. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  66919. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  66920. shapePath[p] = rotated;
  66921. }
  66922. shapePaths[index] = shapePath;
  66923. angle += angleStep;
  66924. index++;
  66925. }
  66926. // cap
  66927. var capPath = function (shapePath) {
  66928. var pointCap = Array();
  66929. var barycenter = BABYLON.Vector3.Zero();
  66930. var i;
  66931. for (i = 0; i < shapePath.length; i++) {
  66932. barycenter.addInPlace(shapePath[i]);
  66933. }
  66934. barycenter.scaleInPlace(1.0 / shapePath.length);
  66935. for (i = 0; i < shapePath.length; i++) {
  66936. pointCap.push(barycenter);
  66937. }
  66938. return pointCap;
  66939. };
  66940. switch (cap) {
  66941. case BABYLON.Mesh.NO_CAP:
  66942. break;
  66943. case BABYLON.Mesh.CAP_START:
  66944. shapePaths[0] = capPath(shapePaths[2]);
  66945. shapePaths[1] = shapePaths[2];
  66946. break;
  66947. case BABYLON.Mesh.CAP_END:
  66948. shapePaths[index] = shapePaths[index - 1];
  66949. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66950. break;
  66951. case BABYLON.Mesh.CAP_ALL:
  66952. shapePaths[0] = capPath(shapePaths[2]);
  66953. shapePaths[1] = shapePaths[2];
  66954. shapePaths[index] = shapePaths[index - 1];
  66955. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66956. break;
  66957. default:
  66958. break;
  66959. }
  66960. return shapePaths;
  66961. };
  66962. var path3D;
  66963. var pathArray;
  66964. if (instance) { // instance update
  66965. path3D = (instance.path3D).update(curve);
  66966. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  66967. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  66968. return instance;
  66969. }
  66970. // extruded shape creation
  66971. path3D = new BABYLON.Path3D(curve);
  66972. var newShapePaths = new Array();
  66973. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66974. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  66975. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  66976. extrudedGeneric.pathArray = pathArray;
  66977. extrudedGeneric.path3D = path3D;
  66978. extrudedGeneric.cap = cap;
  66979. return extrudedGeneric;
  66980. };
  66981. return MeshBuilder;
  66982. }());
  66983. BABYLON.MeshBuilder = MeshBuilder;
  66984. })(BABYLON || (BABYLON = {}));
  66985. //# sourceMappingURL=babylon.meshBuilder.js.map
  66986. var BABYLON;
  66987. (function (BABYLON) {
  66988. /**
  66989. * Draco compression (https://google.github.io/draco/)
  66990. *
  66991. * This class wraps the Draco module.
  66992. *
  66993. * **Encoder**
  66994. *
  66995. * The encoder is not currently implemented.
  66996. *
  66997. * **Decoder**
  66998. *
  66999. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  67000. *
  67001. * To update the configuration, use the following code:
  67002. * ```javascript
  67003. * BABYLON.DracoCompression.Configuration = {
  67004. * decoder: {
  67005. * wasmUrl: "<url to the WebAssembly library>",
  67006. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  67007. * fallbackUrl: "<url to the fallback JavaScript library>",
  67008. * }
  67009. * };
  67010. * ```
  67011. *
  67012. * 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.
  67013. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  67014. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  67015. *
  67016. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  67017. * ```javascript
  67018. * var dracoCompression = new BABYLON.DracoCompression();
  67019. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  67020. * [BABYLON.VertexBuffer.PositionKind]: 0
  67021. * });
  67022. * ```
  67023. *
  67024. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  67025. */
  67026. var DracoCompression = /** @class */ (function () {
  67027. /**
  67028. * Constructor
  67029. */
  67030. function DracoCompression() {
  67031. }
  67032. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  67033. /**
  67034. * Returns true if the decoder is available.
  67035. */
  67036. get: function () {
  67037. if (typeof DracoDecoderModule !== "undefined") {
  67038. return true;
  67039. }
  67040. var decoder = DracoCompression.Configuration.decoder;
  67041. if (decoder) {
  67042. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67043. return true;
  67044. }
  67045. if (decoder.fallbackUrl) {
  67046. return true;
  67047. }
  67048. }
  67049. return false;
  67050. },
  67051. enumerable: true,
  67052. configurable: true
  67053. });
  67054. /**
  67055. * Stop all async operations and release resources.
  67056. */
  67057. DracoCompression.prototype.dispose = function () {
  67058. };
  67059. /**
  67060. * Decode Draco compressed mesh data to vertex data.
  67061. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  67062. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  67063. * @returns A promise that resolves with the decoded vertex data
  67064. */
  67065. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  67066. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  67067. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  67068. var module = wrappedModule.module;
  67069. var vertexData = new BABYLON.VertexData();
  67070. var buffer = new module.DecoderBuffer();
  67071. buffer.Init(dataView, dataView.byteLength);
  67072. var decoder = new module.Decoder();
  67073. var geometry;
  67074. var status;
  67075. try {
  67076. var type = decoder.GetEncodedGeometryType(buffer);
  67077. switch (type) {
  67078. case module.TRIANGULAR_MESH:
  67079. geometry = new module.Mesh();
  67080. status = decoder.DecodeBufferToMesh(buffer, geometry);
  67081. break;
  67082. case module.POINT_CLOUD:
  67083. geometry = new module.PointCloud();
  67084. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  67085. break;
  67086. default:
  67087. throw new Error("Invalid geometry type " + type);
  67088. }
  67089. if (!status.ok() || !geometry.ptr) {
  67090. throw new Error(status.error_msg());
  67091. }
  67092. var numPoints = geometry.num_points();
  67093. if (type === module.TRIANGULAR_MESH) {
  67094. var numFaces = geometry.num_faces();
  67095. var faceIndices = new module.DracoInt32Array();
  67096. try {
  67097. var indices = new Uint32Array(numFaces * 3);
  67098. for (var i = 0; i < numFaces; i++) {
  67099. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  67100. var offset = i * 3;
  67101. indices[offset + 0] = faceIndices.GetValue(0);
  67102. indices[offset + 1] = faceIndices.GetValue(1);
  67103. indices[offset + 2] = faceIndices.GetValue(2);
  67104. }
  67105. vertexData.indices = indices;
  67106. }
  67107. finally {
  67108. module.destroy(faceIndices);
  67109. }
  67110. }
  67111. for (var kind in attributes) {
  67112. var uniqueId = attributes[kind];
  67113. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  67114. var dracoData = new module.DracoFloat32Array();
  67115. try {
  67116. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  67117. var babylonData = new Float32Array(numPoints * attribute.num_components());
  67118. for (var i = 0; i < babylonData.length; i++) {
  67119. babylonData[i] = dracoData.GetValue(i);
  67120. }
  67121. vertexData.set(babylonData, kind);
  67122. }
  67123. finally {
  67124. module.destroy(dracoData);
  67125. }
  67126. }
  67127. }
  67128. finally {
  67129. if (geometry) {
  67130. module.destroy(geometry);
  67131. }
  67132. module.destroy(decoder);
  67133. module.destroy(buffer);
  67134. }
  67135. return vertexData;
  67136. });
  67137. };
  67138. DracoCompression._GetDecoderModule = function () {
  67139. if (!DracoCompression._DecoderModulePromise) {
  67140. var promise = null;
  67141. var config_1 = {};
  67142. if (typeof DracoDecoderModule !== "undefined") {
  67143. promise = Promise.resolve();
  67144. }
  67145. else {
  67146. var decoder = DracoCompression.Configuration.decoder;
  67147. if (decoder) {
  67148. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67149. promise = Promise.all([
  67150. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  67151. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  67152. config_1.wasmBinary = data;
  67153. })
  67154. ]);
  67155. }
  67156. else if (decoder.fallbackUrl) {
  67157. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  67158. }
  67159. }
  67160. }
  67161. if (!promise) {
  67162. throw new Error("Draco decoder module is not available");
  67163. }
  67164. DracoCompression._DecoderModulePromise = promise.then(function () {
  67165. return new Promise(function (resolve) {
  67166. config_1.onModuleLoaded = function (decoderModule) {
  67167. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  67168. resolve({ module: decoderModule });
  67169. };
  67170. DracoDecoderModule(config_1);
  67171. });
  67172. });
  67173. }
  67174. return DracoCompression._DecoderModulePromise;
  67175. };
  67176. DracoCompression._LoadScriptAsync = function (url) {
  67177. return new Promise(function (resolve, reject) {
  67178. BABYLON.Tools.LoadScript(url, function () {
  67179. resolve();
  67180. }, function (message) {
  67181. reject(new Error(message));
  67182. });
  67183. });
  67184. };
  67185. DracoCompression._LoadFileAsync = function (url) {
  67186. return new Promise(function (resolve, reject) {
  67187. BABYLON.Tools.LoadFile(url, function (data) {
  67188. resolve(data);
  67189. }, undefined, undefined, true, function (request, exception) {
  67190. reject(exception);
  67191. });
  67192. });
  67193. };
  67194. /**
  67195. * The configuration. Defaults to the following urls:
  67196. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  67197. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  67198. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  67199. */
  67200. DracoCompression.Configuration = {
  67201. decoder: {
  67202. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  67203. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  67204. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  67205. }
  67206. };
  67207. return DracoCompression;
  67208. }());
  67209. BABYLON.DracoCompression = DracoCompression;
  67210. })(BABYLON || (BABYLON = {}));
  67211. //# sourceMappingURL=babylon.dracoCompression.js.map
  67212. var BABYLON;
  67213. (function (BABYLON) {
  67214. // Sets the default audio engine to Babylon JS.
  67215. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  67216. /**
  67217. * This represents the default audio engine used in babylon.
  67218. * It is responsible to play, synchronize and analyse sounds throughout the application.
  67219. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67220. */
  67221. var AudioEngine = /** @class */ (function () {
  67222. /**
  67223. * Instantiates a new audio engine.
  67224. *
  67225. * There should be only one per page as some browsers restrict the number
  67226. * of audio contexts you can create.
  67227. * @param engine defines the hosting engine
  67228. */
  67229. function AudioEngine(engine) {
  67230. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  67231. var _this = this;
  67232. this._audioContext = null;
  67233. this._audioContextInitialized = false;
  67234. this._muteButton = null;
  67235. /**
  67236. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  67237. */
  67238. this.canUseWebAudio = false;
  67239. /**
  67240. * Defines if Babylon should emit a warning if WebAudio is not supported.
  67241. * @ignoreNaming
  67242. */
  67243. this.WarnedWebAudioUnsupported = false;
  67244. /**
  67245. * Gets whether or not mp3 are supported by your browser.
  67246. */
  67247. this.isMP3supported = false;
  67248. /**
  67249. * Gets whether or not ogg are supported by your browser.
  67250. */
  67251. this.isOGGsupported = false;
  67252. /**
  67253. * Gets whether audio has been unlocked on the device.
  67254. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  67255. * a user interaction has happened.
  67256. */
  67257. this.unlocked = true;
  67258. /**
  67259. * Defines if the audio engine relies on a custom unlocked button.
  67260. * In this case, the embedded button will not be displayed.
  67261. */
  67262. this.useCustomUnlockedButton = false;
  67263. /**
  67264. * Event raised when audio has been unlocked on the browser.
  67265. */
  67266. this.onAudioUnlockedObservable = new BABYLON.Observable();
  67267. /**
  67268. * Event raised when audio has been locked on the browser.
  67269. */
  67270. this.onAudioLockedObservable = new BABYLON.Observable();
  67271. this._tryToRun = false;
  67272. this._onResize = function () {
  67273. _this._moveButtonToTopLeft();
  67274. };
  67275. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  67276. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  67277. this.canUseWebAudio = true;
  67278. }
  67279. var audioElem = document.createElement('audio');
  67280. this._engine = engine;
  67281. try {
  67282. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  67283. this.isMP3supported = true;
  67284. }
  67285. }
  67286. catch (e) {
  67287. // protect error during capability check.
  67288. }
  67289. try {
  67290. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  67291. this.isOGGsupported = true;
  67292. }
  67293. }
  67294. catch (e) {
  67295. // protect error during capability check.
  67296. }
  67297. }
  67298. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  67299. /**
  67300. * Gets the current AudioContext if available.
  67301. */
  67302. get: function () {
  67303. if (!this._audioContextInitialized) {
  67304. this._initializeAudioContext();
  67305. }
  67306. else {
  67307. if (!this.unlocked && !this._muteButton) {
  67308. this._displayMuteButton();
  67309. }
  67310. }
  67311. return this._audioContext;
  67312. },
  67313. enumerable: true,
  67314. configurable: true
  67315. });
  67316. /**
  67317. * Flags the audio engine in Locked state.
  67318. * This happens due to new browser policies preventing audio to autoplay.
  67319. */
  67320. AudioEngine.prototype.lock = function () {
  67321. this._triggerSuspendedState();
  67322. };
  67323. /**
  67324. * Unlocks the audio engine once a user action has been done on the dom.
  67325. * This is helpful to resume play once browser policies have been satisfied.
  67326. */
  67327. AudioEngine.prototype.unlock = function () {
  67328. this._triggerRunningState();
  67329. };
  67330. AudioEngine.prototype._resumeAudioContext = function () {
  67331. var result;
  67332. if (this._audioContext.resume) {
  67333. result = this._audioContext.resume();
  67334. }
  67335. return result || Promise.resolve();
  67336. };
  67337. AudioEngine.prototype._initializeAudioContext = function () {
  67338. var _this = this;
  67339. try {
  67340. if (this.canUseWebAudio) {
  67341. this._audioContext = new AudioContext();
  67342. // create a global volume gain node
  67343. this.masterGain = this._audioContext.createGain();
  67344. this.masterGain.gain.value = 1;
  67345. this.masterGain.connect(this._audioContext.destination);
  67346. this._audioContextInitialized = true;
  67347. if (this._audioContext.state === "running") {
  67348. // Do not wait for the promise to unlock.
  67349. this._triggerRunningState();
  67350. }
  67351. else {
  67352. if (this._audioContext && this._audioContext.resume) {
  67353. this._resumeAudioContext().then(function () {
  67354. _this._triggerRunningState();
  67355. }).catch(function () {
  67356. // Can not resume automatically
  67357. // Needs user action
  67358. _this.lock();
  67359. });
  67360. }
  67361. }
  67362. }
  67363. }
  67364. catch (e) {
  67365. this.canUseWebAudio = false;
  67366. BABYLON.Tools.Error("Web Audio: " + e.message);
  67367. }
  67368. };
  67369. AudioEngine.prototype._triggerRunningState = function () {
  67370. var _this = this;
  67371. if (this._tryToRun) {
  67372. return;
  67373. }
  67374. this._tryToRun = true;
  67375. this._resumeAudioContext()
  67376. .then(function () {
  67377. _this._tryToRun = false;
  67378. _this.unlocked = true;
  67379. if (_this._muteButton) {
  67380. _this._hideMuteButton();
  67381. }
  67382. // Notify users that the audio stack is unlocked/unmuted
  67383. _this.onAudioUnlockedObservable.notifyObservers(_this);
  67384. }).catch(function () {
  67385. _this._tryToRun = false;
  67386. _this.unlocked = false;
  67387. });
  67388. };
  67389. AudioEngine.prototype._triggerSuspendedState = function () {
  67390. this.unlocked = false;
  67391. this.onAudioLockedObservable.notifyObservers(this);
  67392. this._displayMuteButton();
  67393. };
  67394. AudioEngine.prototype._displayMuteButton = function () {
  67395. var _this = this;
  67396. if (this.useCustomUnlockedButton) {
  67397. return;
  67398. }
  67399. this._canvas = this._engine.getRenderingCanvas();
  67400. this._muteButton = document.createElement("BUTTON");
  67401. this._muteButton.className = "babylonUnmuteIcon";
  67402. this._muteButton.id = "babylonUnmuteIconBtn";
  67403. this._muteButton.title = "Unmute";
  67404. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  67405. var style = document.createElement('style');
  67406. style.appendChild(document.createTextNode(css));
  67407. document.getElementsByTagName('head')[0].appendChild(style);
  67408. document.body.appendChild(this._muteButton);
  67409. this._moveButtonToTopLeft();
  67410. this._muteButton.addEventListener('mousedown', function () {
  67411. _this._triggerRunningState();
  67412. }, true);
  67413. this._muteButton.addEventListener('touchend', function () {
  67414. _this._triggerRunningState();
  67415. }, true);
  67416. this._muteButton.addEventListener('click', function () {
  67417. _this._triggerRunningState();
  67418. }, true);
  67419. window.addEventListener("resize", this._onResize);
  67420. };
  67421. AudioEngine.prototype._moveButtonToTopLeft = function () {
  67422. if (this._canvas && this._muteButton) {
  67423. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  67424. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  67425. }
  67426. };
  67427. AudioEngine.prototype._hideMuteButton = function () {
  67428. if (this._muteButton) {
  67429. document.body.removeChild(this._muteButton);
  67430. this._muteButton = null;
  67431. }
  67432. };
  67433. /**
  67434. * Destroy and release the resources associated with the audio ccontext.
  67435. */
  67436. AudioEngine.prototype.dispose = function () {
  67437. if (this.canUseWebAudio && this._audioContextInitialized) {
  67438. if (this._connectedAnalyser && this._audioContext) {
  67439. this._connectedAnalyser.stopDebugCanvas();
  67440. this._connectedAnalyser.dispose();
  67441. this.masterGain.disconnect();
  67442. this.masterGain.connect(this._audioContext.destination);
  67443. this._connectedAnalyser = null;
  67444. }
  67445. this.masterGain.gain.value = 1;
  67446. }
  67447. this.WarnedWebAudioUnsupported = false;
  67448. this._hideMuteButton();
  67449. window.removeEventListener("resize", this._onResize);
  67450. this.onAudioUnlockedObservable.clear();
  67451. this.onAudioLockedObservable.clear();
  67452. };
  67453. /**
  67454. * Gets the global volume sets on the master gain.
  67455. * @returns the global volume if set or -1 otherwise
  67456. */
  67457. AudioEngine.prototype.getGlobalVolume = function () {
  67458. if (this.canUseWebAudio && this._audioContextInitialized) {
  67459. return this.masterGain.gain.value;
  67460. }
  67461. else {
  67462. return -1;
  67463. }
  67464. };
  67465. /**
  67466. * Sets the global volume of your experience (sets on the master gain).
  67467. * @param newVolume Defines the new global volume of the application
  67468. */
  67469. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  67470. if (this.canUseWebAudio && this._audioContextInitialized) {
  67471. this.masterGain.gain.value = newVolume;
  67472. }
  67473. };
  67474. /**
  67475. * Connect the audio engine to an audio analyser allowing some amazing
  67476. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  67477. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  67478. * @param analyser The analyser to connect to the engine
  67479. */
  67480. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  67481. if (this._connectedAnalyser) {
  67482. this._connectedAnalyser.stopDebugCanvas();
  67483. }
  67484. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  67485. this._connectedAnalyser = analyser;
  67486. this.masterGain.disconnect();
  67487. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  67488. }
  67489. };
  67490. return AudioEngine;
  67491. }());
  67492. BABYLON.AudioEngine = AudioEngine;
  67493. })(BABYLON || (BABYLON = {}));
  67494. //# sourceMappingURL=babylon.audioEngine.js.map
  67495. var BABYLON;
  67496. (function (BABYLON) {
  67497. /**
  67498. * Defines a sound that can be played in the application.
  67499. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  67500. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67501. */
  67502. var Sound = /** @class */ (function () {
  67503. /**
  67504. * Create a sound and attach it to a scene
  67505. * @param name Name of your sound
  67506. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  67507. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  67508. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  67509. */
  67510. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  67511. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  67512. var _this = this;
  67513. /**
  67514. * Does the sound autoplay once loaded.
  67515. */
  67516. this.autoplay = false;
  67517. /**
  67518. * Does the sound loop after it finishes playing once.
  67519. */
  67520. this.loop = false;
  67521. /**
  67522. * Does the sound use a custom attenuation curve to simulate the falloff
  67523. * happening when the source gets further away from the camera.
  67524. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  67525. */
  67526. this.useCustomAttenuation = false;
  67527. /**
  67528. * Is this sound currently played.
  67529. */
  67530. this.isPlaying = false;
  67531. /**
  67532. * Is this sound currently paused.
  67533. */
  67534. this.isPaused = false;
  67535. /**
  67536. * Does this sound enables spatial sound.
  67537. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67538. */
  67539. this.spatialSound = false;
  67540. /**
  67541. * Define the reference distance the sound should be heard perfectly.
  67542. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67543. */
  67544. this.refDistance = 1;
  67545. /**
  67546. * Define the roll off factor of spatial sounds.
  67547. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67548. */
  67549. this.rolloffFactor = 1;
  67550. /**
  67551. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  67552. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67553. */
  67554. this.maxDistance = 100;
  67555. /**
  67556. * Define the distance attenuation model the sound will follow.
  67557. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67558. */
  67559. this.distanceModel = "linear";
  67560. /**
  67561. * Observable event when the current playing sound finishes.
  67562. */
  67563. this.onEndedObservable = new BABYLON.Observable();
  67564. this._panningModel = "equalpower";
  67565. this._playbackRate = 1;
  67566. this._streaming = false;
  67567. this._startTime = 0;
  67568. this._startOffset = 0;
  67569. this._position = BABYLON.Vector3.Zero();
  67570. /** @hidden */
  67571. this._positionInEmitterSpace = false;
  67572. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  67573. this._volume = 1;
  67574. this._isReadyToPlay = false;
  67575. this._isDirectional = false;
  67576. // Used if you'd like to create a directional sound.
  67577. // If not set, the sound will be omnidirectional
  67578. this._coneInnerAngle = 360;
  67579. this._coneOuterAngle = 360;
  67580. this._coneOuterGain = 0;
  67581. this._isOutputConnected = false;
  67582. this._urlType = "Unknown";
  67583. this.name = name;
  67584. this._scene = scene;
  67585. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67586. if (!compo) {
  67587. compo = new BABYLON.AudioSceneComponent(scene);
  67588. scene._addComponent(compo);
  67589. }
  67590. this._readyToPlayCallback = readyToPlayCallback;
  67591. // Default custom attenuation function is a linear attenuation
  67592. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  67593. if (currentDistance < maxDistance) {
  67594. return currentVolume * (1 - currentDistance / maxDistance);
  67595. }
  67596. else {
  67597. return 0;
  67598. }
  67599. };
  67600. if (options) {
  67601. this.autoplay = options.autoplay || false;
  67602. this.loop = options.loop || false;
  67603. // if volume === 0, we need another way to check this option
  67604. if (options.volume !== undefined) {
  67605. this._volume = options.volume;
  67606. }
  67607. this.spatialSound = options.spatialSound || false;
  67608. this.maxDistance = options.maxDistance || 100;
  67609. this.useCustomAttenuation = options.useCustomAttenuation || false;
  67610. this.rolloffFactor = options.rolloffFactor || 1;
  67611. this.refDistance = options.refDistance || 1;
  67612. this.distanceModel = options.distanceModel || "linear";
  67613. this._playbackRate = options.playbackRate || 1;
  67614. this._streaming = options.streaming || false;
  67615. }
  67616. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67617. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  67618. this._soundGain.gain.value = this._volume;
  67619. this._inputAudioNode = this._soundGain;
  67620. this._outputAudioNode = this._soundGain;
  67621. if (this.spatialSound) {
  67622. this._createSpatialParameters();
  67623. }
  67624. this._scene.mainSoundTrack.AddSound(this);
  67625. var validParameter = true;
  67626. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  67627. if (urlOrArrayBuffer) {
  67628. try {
  67629. if (typeof (urlOrArrayBuffer) === "string") {
  67630. this._urlType = "String";
  67631. }
  67632. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  67633. this._urlType = "ArrayBuffer";
  67634. }
  67635. else if (urlOrArrayBuffer instanceof MediaStream) {
  67636. this._urlType = "MediaStream";
  67637. }
  67638. else if (Array.isArray(urlOrArrayBuffer)) {
  67639. this._urlType = "Array";
  67640. }
  67641. var urls = [];
  67642. var codecSupportedFound = false;
  67643. switch (this._urlType) {
  67644. case "MediaStream":
  67645. this._streaming = true;
  67646. this._isReadyToPlay = true;
  67647. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  67648. if (this.autoplay) {
  67649. this.play();
  67650. }
  67651. if (this._readyToPlayCallback) {
  67652. this._readyToPlayCallback();
  67653. }
  67654. break;
  67655. case "ArrayBuffer":
  67656. if (urlOrArrayBuffer.byteLength > 0) {
  67657. codecSupportedFound = true;
  67658. this._soundLoaded(urlOrArrayBuffer);
  67659. }
  67660. break;
  67661. case "String":
  67662. urls.push(urlOrArrayBuffer);
  67663. case "Array":
  67664. if (urls.length === 0)
  67665. urls = urlOrArrayBuffer;
  67666. // If we found a supported format, we load it immediately and stop the loop
  67667. for (var i = 0; i < urls.length; i++) {
  67668. var url = urls[i];
  67669. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  67670. codecSupportedFound = true;
  67671. }
  67672. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  67673. codecSupportedFound = true;
  67674. }
  67675. if (url.indexOf(".wav", url.length - 4) !== -1) {
  67676. codecSupportedFound = true;
  67677. }
  67678. if (url.indexOf("blob:") !== -1) {
  67679. codecSupportedFound = true;
  67680. }
  67681. if (codecSupportedFound) {
  67682. // Loading sound using XHR2
  67683. if (!this._streaming) {
  67684. this._scene._loadFile(url, function (data) {
  67685. _this._soundLoaded(data);
  67686. }, undefined, true, true, function (exception) {
  67687. if (exception) {
  67688. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  67689. }
  67690. BABYLON.Tools.Error("Sound creation aborted.");
  67691. _this._scene.mainSoundTrack.RemoveSound(_this);
  67692. });
  67693. }
  67694. // Streaming sound using HTML5 Audio tag
  67695. else {
  67696. this._htmlAudioElement = new Audio(url);
  67697. this._htmlAudioElement.controls = false;
  67698. this._htmlAudioElement.loop = this.loop;
  67699. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  67700. this._htmlAudioElement.preload = "auto";
  67701. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  67702. _this._isReadyToPlay = true;
  67703. if (_this.autoplay) {
  67704. _this.play();
  67705. }
  67706. if (_this._readyToPlayCallback) {
  67707. _this._readyToPlayCallback();
  67708. }
  67709. });
  67710. document.body.appendChild(this._htmlAudioElement);
  67711. this._htmlAudioElement.load();
  67712. }
  67713. break;
  67714. }
  67715. }
  67716. break;
  67717. default:
  67718. validParameter = false;
  67719. break;
  67720. }
  67721. if (!validParameter) {
  67722. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  67723. }
  67724. else {
  67725. if (!codecSupportedFound) {
  67726. this._isReadyToPlay = true;
  67727. // Simulating a ready to play event to avoid breaking code path
  67728. if (this._readyToPlayCallback) {
  67729. window.setTimeout(function () {
  67730. if (_this._readyToPlayCallback) {
  67731. _this._readyToPlayCallback();
  67732. }
  67733. }, 1000);
  67734. }
  67735. }
  67736. }
  67737. }
  67738. catch (ex) {
  67739. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  67740. this._scene.mainSoundTrack.RemoveSound(this);
  67741. }
  67742. }
  67743. }
  67744. else {
  67745. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  67746. this._scene.mainSoundTrack.AddSound(this);
  67747. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  67748. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  67749. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  67750. }
  67751. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  67752. if (this._readyToPlayCallback) {
  67753. window.setTimeout(function () {
  67754. if (_this._readyToPlayCallback) {
  67755. _this._readyToPlayCallback();
  67756. }
  67757. }, 1000);
  67758. }
  67759. }
  67760. }
  67761. /**
  67762. * Release the sound and its associated resources
  67763. */
  67764. Sound.prototype.dispose = function () {
  67765. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67766. if (this.isPlaying) {
  67767. this.stop();
  67768. }
  67769. this._isReadyToPlay = false;
  67770. if (this.soundTrackId === -1) {
  67771. this._scene.mainSoundTrack.RemoveSound(this);
  67772. }
  67773. else if (this._scene.soundTracks) {
  67774. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  67775. }
  67776. if (this._soundGain) {
  67777. this._soundGain.disconnect();
  67778. this._soundGain = null;
  67779. }
  67780. if (this._soundPanner) {
  67781. this._soundPanner.disconnect();
  67782. this._soundPanner = null;
  67783. }
  67784. if (this._soundSource) {
  67785. this._soundSource.disconnect();
  67786. this._soundSource = null;
  67787. }
  67788. this._audioBuffer = null;
  67789. if (this._htmlAudioElement) {
  67790. this._htmlAudioElement.pause();
  67791. this._htmlAudioElement.src = "";
  67792. document.body.removeChild(this._htmlAudioElement);
  67793. }
  67794. if (this._streamingSource) {
  67795. this._streamingSource.disconnect();
  67796. }
  67797. if (this._connectedMesh && this._registerFunc) {
  67798. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67799. this._connectedMesh = null;
  67800. }
  67801. }
  67802. };
  67803. /**
  67804. * Gets if the sounds is ready to be played or not.
  67805. * @returns true if ready, otherwise false
  67806. */
  67807. Sound.prototype.isReady = function () {
  67808. return this._isReadyToPlay;
  67809. };
  67810. Sound.prototype._soundLoaded = function (audioData) {
  67811. var _this = this;
  67812. if (!BABYLON.Engine.audioEngine.audioContext) {
  67813. return;
  67814. }
  67815. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  67816. _this._audioBuffer = buffer;
  67817. _this._isReadyToPlay = true;
  67818. if (_this.autoplay) {
  67819. _this.play();
  67820. }
  67821. if (_this._readyToPlayCallback) {
  67822. _this._readyToPlayCallback();
  67823. }
  67824. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  67825. };
  67826. /**
  67827. * Sets the data of the sound from an audiobuffer
  67828. * @param audioBuffer The audioBuffer containing the data
  67829. */
  67830. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  67831. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67832. this._audioBuffer = audioBuffer;
  67833. this._isReadyToPlay = true;
  67834. }
  67835. };
  67836. /**
  67837. * Updates the current sounds options such as maxdistance, loop...
  67838. * @param options A JSON object containing values named as the object properties
  67839. */
  67840. Sound.prototype.updateOptions = function (options) {
  67841. if (options) {
  67842. this.loop = options.loop || this.loop;
  67843. this.maxDistance = options.maxDistance || this.maxDistance;
  67844. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  67845. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  67846. this.refDistance = options.refDistance || this.refDistance;
  67847. this.distanceModel = options.distanceModel || this.distanceModel;
  67848. this._playbackRate = options.playbackRate || this._playbackRate;
  67849. this._updateSpatialParameters();
  67850. if (this.isPlaying) {
  67851. if (this._streaming && this._htmlAudioElement) {
  67852. this._htmlAudioElement.playbackRate = this._playbackRate;
  67853. }
  67854. else {
  67855. if (this._soundSource) {
  67856. this._soundSource.playbackRate.value = this._playbackRate;
  67857. }
  67858. }
  67859. }
  67860. }
  67861. };
  67862. Sound.prototype._createSpatialParameters = function () {
  67863. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67864. if (this._scene.headphone) {
  67865. this._panningModel = "HRTF";
  67866. }
  67867. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  67868. this._updateSpatialParameters();
  67869. this._soundPanner.connect(this._outputAudioNode);
  67870. this._inputAudioNode = this._soundPanner;
  67871. }
  67872. };
  67873. Sound.prototype._updateSpatialParameters = function () {
  67874. if (this.spatialSound && this._soundPanner) {
  67875. if (this.useCustomAttenuation) {
  67876. // Tricks to disable in a way embedded Web Audio attenuation
  67877. this._soundPanner.distanceModel = "linear";
  67878. this._soundPanner.maxDistance = Number.MAX_VALUE;
  67879. this._soundPanner.refDistance = 1;
  67880. this._soundPanner.rolloffFactor = 1;
  67881. this._soundPanner.panningModel = this._panningModel;
  67882. }
  67883. else {
  67884. this._soundPanner.distanceModel = this.distanceModel;
  67885. this._soundPanner.maxDistance = this.maxDistance;
  67886. this._soundPanner.refDistance = this.refDistance;
  67887. this._soundPanner.rolloffFactor = this.rolloffFactor;
  67888. this._soundPanner.panningModel = this._panningModel;
  67889. }
  67890. }
  67891. };
  67892. /**
  67893. * Switch the panning model to HRTF:
  67894. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  67895. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67896. */
  67897. Sound.prototype.switchPanningModelToHRTF = function () {
  67898. this._panningModel = "HRTF";
  67899. this._switchPanningModel();
  67900. };
  67901. /**
  67902. * Switch the panning model to Equal Power:
  67903. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  67904. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67905. */
  67906. Sound.prototype.switchPanningModelToEqualPower = function () {
  67907. this._panningModel = "equalpower";
  67908. this._switchPanningModel();
  67909. };
  67910. Sound.prototype._switchPanningModel = function () {
  67911. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67912. this._soundPanner.panningModel = this._panningModel;
  67913. }
  67914. };
  67915. /**
  67916. * Connect this sound to a sound track audio node like gain...
  67917. * @param soundTrackAudioNode the sound track audio node to connect to
  67918. */
  67919. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  67920. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67921. if (this._isOutputConnected) {
  67922. this._outputAudioNode.disconnect();
  67923. }
  67924. this._outputAudioNode.connect(soundTrackAudioNode);
  67925. this._isOutputConnected = true;
  67926. }
  67927. };
  67928. /**
  67929. * Transform this sound into a directional source
  67930. * @param coneInnerAngle Size of the inner cone in degree
  67931. * @param coneOuterAngle Size of the outer cone in degree
  67932. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  67933. */
  67934. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  67935. if (coneOuterAngle < coneInnerAngle) {
  67936. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  67937. return;
  67938. }
  67939. this._coneInnerAngle = coneInnerAngle;
  67940. this._coneOuterAngle = coneOuterAngle;
  67941. this._coneOuterGain = coneOuterGain;
  67942. this._isDirectional = true;
  67943. if (this.isPlaying && this.loop) {
  67944. this.stop();
  67945. this.play();
  67946. }
  67947. };
  67948. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  67949. /**
  67950. * Gets or sets the inner angle for the directional cone.
  67951. */
  67952. get: function () {
  67953. return this._coneInnerAngle;
  67954. },
  67955. /**
  67956. * Gets or sets the inner angle for the directional cone.
  67957. */
  67958. set: function (value) {
  67959. if (value != this._coneInnerAngle) {
  67960. if (this._coneOuterAngle < value) {
  67961. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67962. return;
  67963. }
  67964. this._coneInnerAngle = value;
  67965. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67966. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  67967. }
  67968. }
  67969. },
  67970. enumerable: true,
  67971. configurable: true
  67972. });
  67973. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  67974. /**
  67975. * Gets or sets the outer angle for the directional cone.
  67976. */
  67977. get: function () {
  67978. return this._coneOuterAngle;
  67979. },
  67980. /**
  67981. * Gets or sets the outer angle for the directional cone.
  67982. */
  67983. set: function (value) {
  67984. if (value != this._coneOuterAngle) {
  67985. if (value < this._coneInnerAngle) {
  67986. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67987. return;
  67988. }
  67989. this._coneOuterAngle = value;
  67990. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67991. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  67992. }
  67993. }
  67994. },
  67995. enumerable: true,
  67996. configurable: true
  67997. });
  67998. /**
  67999. * Sets the position of the emitter if spatial sound is enabled
  68000. * @param newPosition Defines the new posisiton
  68001. */
  68002. Sound.prototype.setPosition = function (newPosition) {
  68003. this._position = newPosition;
  68004. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68005. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68006. }
  68007. };
  68008. /**
  68009. * Sets the local direction of the emitter if spatial sound is enabled
  68010. * @param newLocalDirection Defines the new local direction
  68011. */
  68012. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  68013. this._localDirection = newLocalDirection;
  68014. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  68015. this._updateDirection();
  68016. }
  68017. };
  68018. Sound.prototype._updateDirection = function () {
  68019. if (!this._connectedMesh || !this._soundPanner) {
  68020. return;
  68021. }
  68022. var mat = this._connectedMesh.getWorldMatrix();
  68023. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  68024. direction.normalize();
  68025. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  68026. };
  68027. /** @hidden */
  68028. Sound.prototype.updateDistanceFromListener = function () {
  68029. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  68030. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  68031. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  68032. }
  68033. };
  68034. /**
  68035. * Sets a new custom attenuation function for the sound.
  68036. * @param callback Defines the function used for the attenuation
  68037. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68038. */
  68039. Sound.prototype.setAttenuationFunction = function (callback) {
  68040. this._customAttenuationFunction = callback;
  68041. };
  68042. /**
  68043. * Play the sound
  68044. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  68045. * @param offset (optional) Start the sound setting it at a specific time
  68046. */
  68047. Sound.prototype.play = function (time, offset) {
  68048. var _this = this;
  68049. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  68050. try {
  68051. if (this._startOffset < 0) {
  68052. time = -this._startOffset;
  68053. this._startOffset = 0;
  68054. }
  68055. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68056. if (!this._soundSource || !this._streamingSource) {
  68057. if (this.spatialSound && this._soundPanner) {
  68058. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68059. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68060. }
  68061. if (this._isDirectional) {
  68062. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  68063. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68064. this._soundPanner.coneOuterGain = this._coneOuterGain;
  68065. if (this._connectedMesh) {
  68066. this._updateDirection();
  68067. }
  68068. else {
  68069. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  68070. }
  68071. }
  68072. }
  68073. }
  68074. if (this._streaming) {
  68075. if (!this._streamingSource) {
  68076. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  68077. this._htmlAudioElement.onended = function () { _this._onended(); };
  68078. this._htmlAudioElement.playbackRate = this._playbackRate;
  68079. }
  68080. this._streamingSource.disconnect();
  68081. this._streamingSource.connect(this._inputAudioNode);
  68082. if (this._htmlAudioElement) {
  68083. // required to manage properly the new suspended default state of Chrome
  68084. // When the option 'streaming: true' is used, we need first to wait for
  68085. // the audio engine to be unlocked by a user gesture before trying to play
  68086. // an HTML Audio elememt
  68087. var tryToPlay = function () {
  68088. if (BABYLON.Engine.audioEngine.unlocked) {
  68089. var playPromise = _this._htmlAudioElement.play();
  68090. // In browsers that don’t yet support this functionality,
  68091. // playPromise won’t be defined.
  68092. if (playPromise !== undefined) {
  68093. playPromise.catch(function (error) {
  68094. // Automatic playback failed.
  68095. // Waiting for the audio engine to be unlocked by user click on unmute
  68096. BABYLON.Engine.audioEngine.lock();
  68097. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  68098. });
  68099. }
  68100. }
  68101. else {
  68102. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  68103. }
  68104. };
  68105. tryToPlay();
  68106. }
  68107. }
  68108. else {
  68109. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  68110. this._soundSource.buffer = this._audioBuffer;
  68111. this._soundSource.connect(this._inputAudioNode);
  68112. this._soundSource.loop = this.loop;
  68113. this._soundSource.playbackRate.value = this._playbackRate;
  68114. this._soundSource.onended = function () { _this._onended(); };
  68115. if (this._soundSource.buffer) {
  68116. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  68117. }
  68118. }
  68119. this._startTime = startTime;
  68120. this.isPlaying = true;
  68121. this.isPaused = false;
  68122. }
  68123. catch (ex) {
  68124. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  68125. }
  68126. }
  68127. };
  68128. Sound.prototype._onended = function () {
  68129. this.isPlaying = false;
  68130. if (this.onended) {
  68131. this.onended();
  68132. }
  68133. this.onEndedObservable.notifyObservers(this);
  68134. };
  68135. /**
  68136. * Stop the sound
  68137. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  68138. */
  68139. Sound.prototype.stop = function (time) {
  68140. if (this.isPlaying) {
  68141. if (this._streaming) {
  68142. if (this._htmlAudioElement) {
  68143. this._htmlAudioElement.pause();
  68144. // Test needed for Firefox or it will generate an Invalid State Error
  68145. if (this._htmlAudioElement.currentTime > 0) {
  68146. this._htmlAudioElement.currentTime = 0;
  68147. }
  68148. }
  68149. else {
  68150. this._streamingSource.disconnect();
  68151. }
  68152. }
  68153. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  68154. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68155. this._soundSource.stop(stopTime);
  68156. this._soundSource.onended = function () { };
  68157. if (!this.isPaused) {
  68158. this._startOffset = 0;
  68159. }
  68160. }
  68161. this.isPlaying = false;
  68162. }
  68163. };
  68164. /**
  68165. * Put the sound in pause
  68166. */
  68167. Sound.prototype.pause = function () {
  68168. if (this.isPlaying) {
  68169. this.isPaused = true;
  68170. if (this._streaming) {
  68171. if (this._htmlAudioElement) {
  68172. this._htmlAudioElement.pause();
  68173. }
  68174. else {
  68175. this._streamingSource.disconnect();
  68176. }
  68177. }
  68178. else if (BABYLON.Engine.audioEngine.audioContext) {
  68179. this.stop(0);
  68180. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  68181. }
  68182. }
  68183. };
  68184. /**
  68185. * Sets a dedicated volume for this sounds
  68186. * @param newVolume Define the new volume of the sound
  68187. * @param time Define in how long the sound should be at this value
  68188. */
  68189. Sound.prototype.setVolume = function (newVolume, time) {
  68190. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  68191. if (time && BABYLON.Engine.audioEngine.audioContext) {
  68192. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  68193. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  68194. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  68195. }
  68196. else {
  68197. this._soundGain.gain.value = newVolume;
  68198. }
  68199. }
  68200. this._volume = newVolume;
  68201. };
  68202. /**
  68203. * Set the sound play back rate
  68204. * @param newPlaybackRate Define the playback rate the sound should be played at
  68205. */
  68206. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  68207. this._playbackRate = newPlaybackRate;
  68208. if (this.isPlaying) {
  68209. if (this._streaming && this._htmlAudioElement) {
  68210. this._htmlAudioElement.playbackRate = this._playbackRate;
  68211. }
  68212. else if (this._soundSource) {
  68213. this._soundSource.playbackRate.value = this._playbackRate;
  68214. }
  68215. }
  68216. };
  68217. /**
  68218. * Gets the volume of the sound.
  68219. * @returns the volume of the sound
  68220. */
  68221. Sound.prototype.getVolume = function () {
  68222. return this._volume;
  68223. };
  68224. /**
  68225. * Attach the sound to a dedicated mesh
  68226. * @param meshToConnectTo The mesh to connect the sound with
  68227. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  68228. */
  68229. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  68230. var _this = this;
  68231. if (this._connectedMesh && this._registerFunc) {
  68232. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68233. this._registerFunc = null;
  68234. }
  68235. this._connectedMesh = meshToConnectTo;
  68236. if (!this.spatialSound) {
  68237. this.spatialSound = true;
  68238. this._createSpatialParameters();
  68239. if (this.isPlaying && this.loop) {
  68240. this.stop();
  68241. this.play();
  68242. }
  68243. }
  68244. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  68245. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  68246. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  68247. };
  68248. /**
  68249. * Detach the sound from the previously attached mesh
  68250. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  68251. */
  68252. Sound.prototype.detachFromMesh = function () {
  68253. if (this._connectedMesh && this._registerFunc) {
  68254. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68255. this._registerFunc = null;
  68256. this._connectedMesh = null;
  68257. }
  68258. };
  68259. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  68260. if (!node.getBoundingInfo) {
  68261. return;
  68262. }
  68263. var mesh = node;
  68264. if (this._positionInEmitterSpace) {
  68265. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  68266. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  68267. }
  68268. else {
  68269. var boundingInfo = mesh.getBoundingInfo();
  68270. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  68271. }
  68272. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  68273. this._updateDirection();
  68274. }
  68275. };
  68276. /**
  68277. * Clone the current sound in the scene.
  68278. * @returns the new sound clone
  68279. */
  68280. Sound.prototype.clone = function () {
  68281. var _this = this;
  68282. if (!this._streaming) {
  68283. var setBufferAndRun = function () {
  68284. if (_this._isReadyToPlay) {
  68285. clonedSound._audioBuffer = _this.getAudioBuffer();
  68286. clonedSound._isReadyToPlay = true;
  68287. if (clonedSound.autoplay) {
  68288. clonedSound.play();
  68289. }
  68290. }
  68291. else {
  68292. window.setTimeout(setBufferAndRun, 300);
  68293. }
  68294. };
  68295. var currentOptions = {
  68296. autoplay: this.autoplay, loop: this.loop,
  68297. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  68298. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  68299. refDistance: this.refDistance, distanceModel: this.distanceModel
  68300. };
  68301. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  68302. if (this.useCustomAttenuation) {
  68303. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  68304. }
  68305. clonedSound.setPosition(this._position);
  68306. clonedSound.setPlaybackRate(this._playbackRate);
  68307. setBufferAndRun();
  68308. return clonedSound;
  68309. }
  68310. // Can't clone a streaming sound
  68311. else {
  68312. return null;
  68313. }
  68314. };
  68315. /**
  68316. * Gets the current underlying audio buffer containing the data
  68317. * @returns the audio buffer
  68318. */
  68319. Sound.prototype.getAudioBuffer = function () {
  68320. return this._audioBuffer;
  68321. };
  68322. /**
  68323. * Serializes the Sound in a JSON representation
  68324. * @returns the JSON representation of the sound
  68325. */
  68326. Sound.prototype.serialize = function () {
  68327. var serializationObject = {
  68328. name: this.name,
  68329. url: this.name,
  68330. autoplay: this.autoplay,
  68331. loop: this.loop,
  68332. volume: this._volume,
  68333. spatialSound: this.spatialSound,
  68334. maxDistance: this.maxDistance,
  68335. rolloffFactor: this.rolloffFactor,
  68336. refDistance: this.refDistance,
  68337. distanceModel: this.distanceModel,
  68338. playbackRate: this._playbackRate,
  68339. panningModel: this._panningModel,
  68340. soundTrackId: this.soundTrackId
  68341. };
  68342. if (this.spatialSound) {
  68343. if (this._connectedMesh)
  68344. serializationObject.connectedMeshId = this._connectedMesh.id;
  68345. serializationObject.position = this._position.asArray();
  68346. serializationObject.refDistance = this.refDistance;
  68347. serializationObject.distanceModel = this.distanceModel;
  68348. serializationObject.isDirectional = this._isDirectional;
  68349. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  68350. serializationObject.coneInnerAngle = this._coneInnerAngle;
  68351. serializationObject.coneOuterAngle = this._coneOuterAngle;
  68352. serializationObject.coneOuterGain = this._coneOuterGain;
  68353. }
  68354. return serializationObject;
  68355. };
  68356. /**
  68357. * Parse a JSON representation of a sound to innstantiate in a given scene
  68358. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  68359. * @param scene Define the scene the new parsed sound should be created in
  68360. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  68361. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  68362. * @returns the newly parsed sound
  68363. */
  68364. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  68365. var soundName = parsedSound.name;
  68366. var soundUrl;
  68367. if (parsedSound.url) {
  68368. soundUrl = rootUrl + parsedSound.url;
  68369. }
  68370. else {
  68371. soundUrl = rootUrl + soundName;
  68372. }
  68373. var options = {
  68374. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  68375. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  68376. rolloffFactor: parsedSound.rolloffFactor,
  68377. refDistance: parsedSound.refDistance,
  68378. distanceModel: parsedSound.distanceModel,
  68379. playbackRate: parsedSound.playbackRate
  68380. };
  68381. var newSound;
  68382. if (!sourceSound) {
  68383. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  68384. scene._addPendingData(newSound);
  68385. }
  68386. else {
  68387. var setBufferAndRun = function () {
  68388. if (sourceSound._isReadyToPlay) {
  68389. newSound._audioBuffer = sourceSound.getAudioBuffer();
  68390. newSound._isReadyToPlay = true;
  68391. if (newSound.autoplay) {
  68392. newSound.play();
  68393. }
  68394. }
  68395. else {
  68396. window.setTimeout(setBufferAndRun, 300);
  68397. }
  68398. };
  68399. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  68400. setBufferAndRun();
  68401. }
  68402. if (parsedSound.position) {
  68403. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  68404. newSound.setPosition(soundPosition);
  68405. }
  68406. if (parsedSound.isDirectional) {
  68407. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  68408. if (parsedSound.localDirectionToMesh) {
  68409. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  68410. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  68411. }
  68412. }
  68413. if (parsedSound.connectedMeshId) {
  68414. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  68415. if (connectedMesh) {
  68416. newSound.attachToMesh(connectedMesh);
  68417. }
  68418. }
  68419. return newSound;
  68420. };
  68421. return Sound;
  68422. }());
  68423. BABYLON.Sound = Sound;
  68424. })(BABYLON || (BABYLON = {}));
  68425. //# sourceMappingURL=babylon.sound.js.map
  68426. var BABYLON;
  68427. (function (BABYLON) {
  68428. /**
  68429. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  68430. * It will be also used in a future release to apply effects on a specific track.
  68431. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68432. */
  68433. var SoundTrack = /** @class */ (function () {
  68434. /**
  68435. * Creates a new sound track.
  68436. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68437. * @param scene Define the scene the sound track belongs to
  68438. * @param options
  68439. */
  68440. function SoundTrack(scene, options) {
  68441. if (options === void 0) { options = {}; }
  68442. /**
  68443. * The unique identifier of the sound track in the scene.
  68444. */
  68445. this.id = -1;
  68446. this._isMainTrack = false;
  68447. this._isInitialized = false;
  68448. this._scene = scene;
  68449. this.soundCollection = new Array();
  68450. this._options = options;
  68451. if (!this._isMainTrack && this._scene.soundTracks) {
  68452. this._scene.soundTracks.push(this);
  68453. this.id = this._scene.soundTracks.length - 1;
  68454. }
  68455. }
  68456. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  68457. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68458. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  68459. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  68460. if (this._options) {
  68461. if (this._options.volume) {
  68462. this._outputAudioNode.gain.value = this._options.volume;
  68463. }
  68464. if (this._options.mainTrack) {
  68465. this._isMainTrack = this._options.mainTrack;
  68466. }
  68467. }
  68468. this._isInitialized = true;
  68469. }
  68470. };
  68471. /**
  68472. * Release the sound track and its associated resources
  68473. */
  68474. SoundTrack.prototype.dispose = function () {
  68475. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  68476. if (this._connectedAnalyser) {
  68477. this._connectedAnalyser.stopDebugCanvas();
  68478. }
  68479. while (this.soundCollection.length) {
  68480. this.soundCollection[0].dispose();
  68481. }
  68482. if (this._outputAudioNode) {
  68483. this._outputAudioNode.disconnect();
  68484. }
  68485. this._outputAudioNode = null;
  68486. }
  68487. };
  68488. /**
  68489. * Adds a sound to this sound track
  68490. * @param sound define the cound to add
  68491. * @ignoreNaming
  68492. */
  68493. SoundTrack.prototype.AddSound = function (sound) {
  68494. if (!this._isInitialized) {
  68495. this._initializeSoundTrackAudioGraph();
  68496. }
  68497. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68498. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  68499. }
  68500. if (sound.soundTrackId) {
  68501. if (sound.soundTrackId === -1) {
  68502. this._scene.mainSoundTrack.RemoveSound(sound);
  68503. }
  68504. else if (this._scene.soundTracks) {
  68505. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  68506. }
  68507. }
  68508. this.soundCollection.push(sound);
  68509. sound.soundTrackId = this.id;
  68510. };
  68511. /**
  68512. * Removes a sound to this sound track
  68513. * @param sound define the cound to remove
  68514. * @ignoreNaming
  68515. */
  68516. SoundTrack.prototype.RemoveSound = function (sound) {
  68517. var index = this.soundCollection.indexOf(sound);
  68518. if (index !== -1) {
  68519. this.soundCollection.splice(index, 1);
  68520. }
  68521. };
  68522. /**
  68523. * Set a global volume for the full sound track.
  68524. * @param newVolume Define the new volume of the sound track
  68525. */
  68526. SoundTrack.prototype.setVolume = function (newVolume) {
  68527. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68528. this._outputAudioNode.gain.value = newVolume;
  68529. }
  68530. };
  68531. /**
  68532. * Switch the panning model to HRTF:
  68533. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  68534. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68535. */
  68536. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  68537. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68538. for (var i = 0; i < this.soundCollection.length; i++) {
  68539. this.soundCollection[i].switchPanningModelToHRTF();
  68540. }
  68541. }
  68542. };
  68543. /**
  68544. * Switch the panning model to Equal Power:
  68545. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  68546. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68547. */
  68548. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  68549. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68550. for (var i = 0; i < this.soundCollection.length; i++) {
  68551. this.soundCollection[i].switchPanningModelToEqualPower();
  68552. }
  68553. }
  68554. };
  68555. /**
  68556. * Connect the sound track to an audio analyser allowing some amazing
  68557. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68558. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68559. * @param analyser The analyser to connect to the engine
  68560. */
  68561. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  68562. if (this._connectedAnalyser) {
  68563. this._connectedAnalyser.stopDebugCanvas();
  68564. }
  68565. this._connectedAnalyser = analyser;
  68566. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68567. this._outputAudioNode.disconnect();
  68568. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  68569. }
  68570. };
  68571. return SoundTrack;
  68572. }());
  68573. BABYLON.SoundTrack = SoundTrack;
  68574. })(BABYLON || (BABYLON = {}));
  68575. //# sourceMappingURL=babylon.soundtrack.js.map
  68576. var BABYLON;
  68577. (function (BABYLON) {
  68578. /**
  68579. * Class used to work with sound analyzer using fast fourier transform (FFT)
  68580. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68581. */
  68582. var Analyser = /** @class */ (function () {
  68583. /**
  68584. * Creates a new analyser
  68585. * @param scene defines hosting scene
  68586. */
  68587. function Analyser(scene) {
  68588. /**
  68589. * Gets or sets the smoothing
  68590. * @ignorenaming
  68591. */
  68592. this.SMOOTHING = 0.75;
  68593. /**
  68594. * Gets or sets the FFT table size
  68595. * @ignorenaming
  68596. */
  68597. this.FFT_SIZE = 512;
  68598. /**
  68599. * Gets or sets the bar graph amplitude
  68600. * @ignorenaming
  68601. */
  68602. this.BARGRAPHAMPLITUDE = 256;
  68603. /**
  68604. * Gets or sets the position of the debug canvas
  68605. * @ignorenaming
  68606. */
  68607. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  68608. /**
  68609. * Gets or sets the debug canvas size
  68610. * @ignorenaming
  68611. */
  68612. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  68613. this._scene = scene;
  68614. this._audioEngine = BABYLON.Engine.audioEngine;
  68615. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  68616. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  68617. this._webAudioAnalyser.minDecibels = -140;
  68618. this._webAudioAnalyser.maxDecibels = 0;
  68619. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68620. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68621. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  68622. }
  68623. }
  68624. /**
  68625. * Get the number of data values you will have to play with for the visualization
  68626. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  68627. * @returns a number
  68628. */
  68629. Analyser.prototype.getFrequencyBinCount = function () {
  68630. if (this._audioEngine.canUseWebAudio) {
  68631. return this._webAudioAnalyser.frequencyBinCount;
  68632. }
  68633. else {
  68634. return 0;
  68635. }
  68636. };
  68637. /**
  68638. * Gets the current frequency data as a byte array
  68639. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68640. * @returns a Uint8Array
  68641. */
  68642. Analyser.prototype.getByteFrequencyData = function () {
  68643. if (this._audioEngine.canUseWebAudio) {
  68644. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68645. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68646. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  68647. }
  68648. return this._byteFreqs;
  68649. };
  68650. /**
  68651. * Gets the current waveform as a byte array
  68652. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  68653. * @returns a Uint8Array
  68654. */
  68655. Analyser.prototype.getByteTimeDomainData = function () {
  68656. if (this._audioEngine.canUseWebAudio) {
  68657. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68658. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68659. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  68660. }
  68661. return this._byteTime;
  68662. };
  68663. /**
  68664. * Gets the current frequency data as a float array
  68665. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68666. * @returns a Float32Array
  68667. */
  68668. Analyser.prototype.getFloatFrequencyData = function () {
  68669. if (this._audioEngine.canUseWebAudio) {
  68670. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68671. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68672. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  68673. }
  68674. return this._floatFreqs;
  68675. };
  68676. /**
  68677. * Renders the debug canvas
  68678. */
  68679. Analyser.prototype.drawDebugCanvas = function () {
  68680. var _this = this;
  68681. if (this._audioEngine.canUseWebAudio) {
  68682. if (!this._debugCanvas) {
  68683. this._debugCanvas = document.createElement("canvas");
  68684. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  68685. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  68686. this._debugCanvas.style.position = "absolute";
  68687. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  68688. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  68689. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  68690. document.body.appendChild(this._debugCanvas);
  68691. this._registerFunc = function () {
  68692. _this.drawDebugCanvas();
  68693. };
  68694. this._scene.registerBeforeRender(this._registerFunc);
  68695. }
  68696. if (this._registerFunc && this._debugCanvasContext) {
  68697. var workingArray = this.getByteFrequencyData();
  68698. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  68699. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  68700. // Draw the frequency domain chart.
  68701. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  68702. var value = workingArray[i];
  68703. var percent = value / this.BARGRAPHAMPLITUDE;
  68704. var height = this.DEBUGCANVASSIZE.height * percent;
  68705. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  68706. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  68707. var hue = i / this.getFrequencyBinCount() * 360;
  68708. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  68709. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  68710. }
  68711. }
  68712. }
  68713. };
  68714. /**
  68715. * Stops rendering the debug canvas and removes it
  68716. */
  68717. Analyser.prototype.stopDebugCanvas = function () {
  68718. if (this._debugCanvas) {
  68719. if (this._registerFunc) {
  68720. this._scene.unregisterBeforeRender(this._registerFunc);
  68721. this._registerFunc = null;
  68722. }
  68723. document.body.removeChild(this._debugCanvas);
  68724. this._debugCanvas = null;
  68725. this._debugCanvasContext = null;
  68726. }
  68727. };
  68728. /**
  68729. * Connects two audio nodes
  68730. * @param inputAudioNode defines first node to connect
  68731. * @param outputAudioNode defines second node to connect
  68732. */
  68733. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  68734. if (this._audioEngine.canUseWebAudio) {
  68735. inputAudioNode.connect(this._webAudioAnalyser);
  68736. this._webAudioAnalyser.connect(outputAudioNode);
  68737. }
  68738. };
  68739. /**
  68740. * Releases all associated resources
  68741. */
  68742. Analyser.prototype.dispose = function () {
  68743. if (this._audioEngine.canUseWebAudio) {
  68744. this._webAudioAnalyser.disconnect();
  68745. }
  68746. };
  68747. return Analyser;
  68748. }());
  68749. BABYLON.Analyser = Analyser;
  68750. })(BABYLON || (BABYLON = {}));
  68751. //# sourceMappingURL=babylon.analyser.js.map
  68752. var BABYLON;
  68753. (function (BABYLON) {
  68754. /**
  68755. * Wraps one or more Sound objects and selects one with random weight for playback.
  68756. */
  68757. var WeightedSound = /** @class */ (function () {
  68758. /**
  68759. * Creates a new WeightedSound from the list of sounds given.
  68760. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  68761. * @param sounds Array of Sounds that will be selected from.
  68762. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  68763. */
  68764. function WeightedSound(loop, sounds, weights) {
  68765. var _this = this;
  68766. /** When true a Sound will be selected and played when the current playing Sound completes. */
  68767. this.loop = false;
  68768. this._coneInnerAngle = 360;
  68769. this._coneOuterAngle = 360;
  68770. this._volume = 1;
  68771. /** A Sound is currently playing. */
  68772. this.isPlaying = false;
  68773. /** A Sound is currently paused. */
  68774. this.isPaused = false;
  68775. this._sounds = [];
  68776. this._weights = [];
  68777. if (sounds.length !== weights.length) {
  68778. throw new Error('Sounds length does not equal weights length');
  68779. }
  68780. this.loop = loop;
  68781. this._weights = weights;
  68782. // Normalize the weights
  68783. var weightSum = 0;
  68784. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  68785. var weight = weights_1[_i];
  68786. weightSum += weight;
  68787. }
  68788. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  68789. for (var i = 0; i < this._weights.length; i++) {
  68790. this._weights[i] *= invWeightSum;
  68791. }
  68792. this._sounds = sounds;
  68793. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  68794. var sound = _b[_a];
  68795. sound.onEndedObservable.add(function () { _this._onended(); });
  68796. }
  68797. }
  68798. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  68799. /**
  68800. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  68801. */
  68802. get: function () {
  68803. return this._coneInnerAngle;
  68804. },
  68805. /**
  68806. * The size of cone in degress for a directional sound in which there will be no attenuation.
  68807. */
  68808. set: function (value) {
  68809. if (value !== this._coneInnerAngle) {
  68810. if (this._coneOuterAngle < value) {
  68811. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68812. return;
  68813. }
  68814. this._coneInnerAngle = value;
  68815. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68816. var sound = _a[_i];
  68817. sound.directionalConeInnerAngle = value;
  68818. }
  68819. }
  68820. },
  68821. enumerable: true,
  68822. configurable: true
  68823. });
  68824. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  68825. /**
  68826. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68827. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68828. */
  68829. get: function () {
  68830. return this._coneOuterAngle;
  68831. },
  68832. /**
  68833. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68834. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68835. */
  68836. set: function (value) {
  68837. if (value !== this._coneOuterAngle) {
  68838. if (value < this._coneInnerAngle) {
  68839. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68840. return;
  68841. }
  68842. this._coneOuterAngle = value;
  68843. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68844. var sound = _a[_i];
  68845. sound.directionalConeOuterAngle = value;
  68846. }
  68847. }
  68848. },
  68849. enumerable: true,
  68850. configurable: true
  68851. });
  68852. Object.defineProperty(WeightedSound.prototype, "volume", {
  68853. /**
  68854. * Playback volume.
  68855. */
  68856. get: function () {
  68857. return this._volume;
  68858. },
  68859. /**
  68860. * Playback volume.
  68861. */
  68862. set: function (value) {
  68863. if (value !== this._volume) {
  68864. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68865. var sound = _a[_i];
  68866. sound.setVolume(value);
  68867. }
  68868. }
  68869. },
  68870. enumerable: true,
  68871. configurable: true
  68872. });
  68873. WeightedSound.prototype._onended = function () {
  68874. if (this._currentIndex !== undefined) {
  68875. this._sounds[this._currentIndex].autoplay = false;
  68876. }
  68877. if (this.loop && this.isPlaying) {
  68878. this.play();
  68879. }
  68880. else {
  68881. this.isPlaying = false;
  68882. }
  68883. };
  68884. /**
  68885. * Suspend playback
  68886. */
  68887. WeightedSound.prototype.pause = function () {
  68888. this.isPaused = true;
  68889. if (this._currentIndex !== undefined) {
  68890. this._sounds[this._currentIndex].pause();
  68891. }
  68892. };
  68893. /**
  68894. * Stop playback
  68895. */
  68896. WeightedSound.prototype.stop = function () {
  68897. this.isPlaying = false;
  68898. if (this._currentIndex !== undefined) {
  68899. this._sounds[this._currentIndex].stop();
  68900. }
  68901. };
  68902. /**
  68903. * Start playback.
  68904. * @param startOffset Position the clip head at a specific time in seconds.
  68905. */
  68906. WeightedSound.prototype.play = function (startOffset) {
  68907. if (!this.isPaused) {
  68908. this.stop();
  68909. var randomValue = Math.random();
  68910. var total = 0;
  68911. for (var i = 0; i < this._weights.length; i++) {
  68912. total += this._weights[i];
  68913. if (randomValue <= total) {
  68914. this._currentIndex = i;
  68915. break;
  68916. }
  68917. }
  68918. }
  68919. var sound = this._sounds[this._currentIndex];
  68920. if (sound.isReady()) {
  68921. sound.play(0, this.isPaused ? undefined : startOffset);
  68922. }
  68923. else {
  68924. sound.autoplay = true;
  68925. }
  68926. this.isPlaying = true;
  68927. this.isPaused = false;
  68928. };
  68929. return WeightedSound;
  68930. }());
  68931. BABYLON.WeightedSound = WeightedSound;
  68932. })(BABYLON || (BABYLON = {}));
  68933. //# sourceMappingURL=babylon.weightedsound.js.map
  68934. var BABYLON;
  68935. (function (BABYLON) {
  68936. // Adds the parser to the scene parsers.
  68937. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  68938. // TODO: add sound
  68939. var loadedSounds = [];
  68940. var loadedSound;
  68941. container.sounds = container.sounds || [];
  68942. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68943. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68944. var parsedSound = parsedData.sounds[index];
  68945. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68946. if (!parsedSound.url)
  68947. parsedSound.url = parsedSound.name;
  68948. if (!loadedSounds[parsedSound.url]) {
  68949. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68950. loadedSounds[parsedSound.url] = loadedSound;
  68951. container.sounds.push(loadedSound);
  68952. }
  68953. else {
  68954. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68955. }
  68956. }
  68957. else {
  68958. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68959. }
  68960. }
  68961. }
  68962. loadedSounds = [];
  68963. });
  68964. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  68965. get: function () {
  68966. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68967. if (!compo) {
  68968. compo = new AudioSceneComponent(this);
  68969. this._addComponent(compo);
  68970. }
  68971. if (!this._mainSoundTrack) {
  68972. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  68973. }
  68974. return this._mainSoundTrack;
  68975. },
  68976. enumerable: true,
  68977. configurable: true
  68978. });
  68979. BABYLON.Scene.prototype.getSoundByName = function (name) {
  68980. var index;
  68981. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  68982. if (this.mainSoundTrack.soundCollection[index].name === name) {
  68983. return this.mainSoundTrack.soundCollection[index];
  68984. }
  68985. }
  68986. if (this.soundTracks) {
  68987. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  68988. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  68989. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  68990. return this.soundTracks[sdIndex].soundCollection[index];
  68991. }
  68992. }
  68993. }
  68994. }
  68995. return null;
  68996. };
  68997. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  68998. get: function () {
  68999. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69000. if (!compo) {
  69001. compo = new AudioSceneComponent(this);
  69002. this._addComponent(compo);
  69003. }
  69004. return compo.audioEnabled;
  69005. },
  69006. set: function (value) {
  69007. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69008. if (!compo) {
  69009. compo = new AudioSceneComponent(this);
  69010. this._addComponent(compo);
  69011. }
  69012. if (value) {
  69013. compo.enableAudio();
  69014. }
  69015. else {
  69016. compo.disableAudio();
  69017. }
  69018. },
  69019. enumerable: true,
  69020. configurable: true
  69021. });
  69022. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  69023. get: function () {
  69024. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69025. if (!compo) {
  69026. compo = new AudioSceneComponent(this);
  69027. this._addComponent(compo);
  69028. }
  69029. return compo.headphone;
  69030. },
  69031. set: function (value) {
  69032. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69033. if (!compo) {
  69034. compo = new AudioSceneComponent(this);
  69035. this._addComponent(compo);
  69036. }
  69037. if (value) {
  69038. compo.switchAudioModeForHeadphones();
  69039. }
  69040. else {
  69041. compo.switchAudioModeForNormalSpeakers();
  69042. }
  69043. },
  69044. enumerable: true,
  69045. configurable: true
  69046. });
  69047. /**
  69048. * Defines the sound scene component responsible to manage any sounds
  69049. * in a given scene.
  69050. */
  69051. var AudioSceneComponent = /** @class */ (function () {
  69052. /**
  69053. * Creates a new instance of the component for the given scene
  69054. * @param scene Defines the scene to register the component in
  69055. */
  69056. function AudioSceneComponent(scene) {
  69057. /**
  69058. * The component name helpfull to identify the component in the list of scene components.
  69059. */
  69060. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  69061. this._audioEnabled = true;
  69062. this._headphone = false;
  69063. this.scene = scene;
  69064. scene.soundTracks = new Array();
  69065. scene.sounds = new Array();
  69066. }
  69067. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  69068. /**
  69069. * Gets whether audio is enabled or not.
  69070. * Please use related enable/disable method to switch state.
  69071. */
  69072. get: function () {
  69073. return this._audioEnabled;
  69074. },
  69075. enumerable: true,
  69076. configurable: true
  69077. });
  69078. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  69079. /**
  69080. * Gets whether audio is outputing to headphone or not.
  69081. * Please use the according Switch methods to change output.
  69082. */
  69083. get: function () {
  69084. return this._headphone;
  69085. },
  69086. enumerable: true,
  69087. configurable: true
  69088. });
  69089. /**
  69090. * Registers the component in a given scene
  69091. */
  69092. AudioSceneComponent.prototype.register = function () {
  69093. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  69094. };
  69095. /**
  69096. * Rebuilds the elements related to this component in case of
  69097. * context lost for instance.
  69098. */
  69099. AudioSceneComponent.prototype.rebuild = function () {
  69100. // Nothing to do here. (Not rendering related)
  69101. };
  69102. /**
  69103. * Serializes the component data to the specified json object
  69104. * @param serializationObject The object to serialize to
  69105. */
  69106. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  69107. serializationObject.sounds = [];
  69108. if (this.scene.soundTracks) {
  69109. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  69110. var soundtrack = this.scene.soundTracks[index];
  69111. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  69112. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  69113. }
  69114. }
  69115. }
  69116. };
  69117. /**
  69118. * Adds all the element from the container to the scene
  69119. * @param container the container holding the elements
  69120. */
  69121. AudioSceneComponent.prototype.addFromContainer = function (container) {
  69122. var _this = this;
  69123. if (!container.sounds) {
  69124. return;
  69125. }
  69126. container.sounds.forEach(function (sound) {
  69127. sound.play();
  69128. sound.autoplay = true;
  69129. _this.scene.mainSoundTrack.AddSound(sound);
  69130. });
  69131. };
  69132. /**
  69133. * Removes all the elements in the container from the scene
  69134. * @param container contains the elements to remove
  69135. */
  69136. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  69137. var _this = this;
  69138. if (!container.sounds) {
  69139. return;
  69140. }
  69141. container.sounds.forEach(function (sound) {
  69142. sound.stop();
  69143. sound.autoplay = false;
  69144. _this.scene.mainSoundTrack.RemoveSound(sound);
  69145. });
  69146. };
  69147. /**
  69148. * Disposes the component and the associated ressources.
  69149. */
  69150. AudioSceneComponent.prototype.dispose = function () {
  69151. var scene = this.scene;
  69152. if (scene._mainSoundTrack) {
  69153. scene.mainSoundTrack.dispose();
  69154. }
  69155. if (scene.soundTracks) {
  69156. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  69157. scene.soundTracks[scIndex].dispose();
  69158. }
  69159. }
  69160. };
  69161. /**
  69162. * Disables audio in the associated scene.
  69163. */
  69164. AudioSceneComponent.prototype.disableAudio = function () {
  69165. var scene = this.scene;
  69166. this._audioEnabled = false;
  69167. var i;
  69168. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69169. scene.mainSoundTrack.soundCollection[i].pause();
  69170. }
  69171. if (scene.soundTracks) {
  69172. for (i = 0; i < scene.soundTracks.length; i++) {
  69173. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69174. scene.soundTracks[i].soundCollection[j].pause();
  69175. }
  69176. }
  69177. }
  69178. };
  69179. /**
  69180. * Enables audio in the associated scene.
  69181. */
  69182. AudioSceneComponent.prototype.enableAudio = function () {
  69183. var scene = this.scene;
  69184. this._audioEnabled = true;
  69185. var i;
  69186. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69187. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  69188. scene.mainSoundTrack.soundCollection[i].play();
  69189. }
  69190. }
  69191. if (scene.soundTracks) {
  69192. for (i = 0; i < scene.soundTracks.length; i++) {
  69193. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69194. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  69195. scene.soundTracks[i].soundCollection[j].play();
  69196. }
  69197. }
  69198. }
  69199. }
  69200. };
  69201. /**
  69202. * Switch audio to headphone output.
  69203. */
  69204. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  69205. var scene = this.scene;
  69206. this._headphone = true;
  69207. scene.mainSoundTrack.switchPanningModelToHRTF();
  69208. if (scene.soundTracks) {
  69209. for (var i = 0; i < scene.soundTracks.length; i++) {
  69210. scene.soundTracks[i].switchPanningModelToHRTF();
  69211. }
  69212. }
  69213. };
  69214. /**
  69215. * Switch audio to normal speakers.
  69216. */
  69217. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  69218. var scene = this.scene;
  69219. this._headphone = false;
  69220. scene.mainSoundTrack.switchPanningModelToEqualPower();
  69221. if (scene.soundTracks) {
  69222. for (var i = 0; i < scene.soundTracks.length; i++) {
  69223. scene.soundTracks[i].switchPanningModelToEqualPower();
  69224. }
  69225. }
  69226. };
  69227. AudioSceneComponent.prototype._afterRender = function () {
  69228. var scene = this.scene;
  69229. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  69230. return;
  69231. }
  69232. var listeningCamera;
  69233. var audioEngine = BABYLON.Engine.audioEngine;
  69234. if (scene.activeCameras.length > 0) {
  69235. listeningCamera = scene.activeCameras[0];
  69236. }
  69237. else {
  69238. listeningCamera = scene.activeCamera;
  69239. }
  69240. if (listeningCamera && audioEngine.audioContext) {
  69241. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  69242. // for VR cameras
  69243. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  69244. listeningCamera = listeningCamera.rigCameras[0];
  69245. }
  69246. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  69247. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  69248. cameraDirection.normalize();
  69249. // To avoid some errors on GearVR
  69250. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  69251. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  69252. }
  69253. var i;
  69254. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69255. var sound = scene.mainSoundTrack.soundCollection[i];
  69256. if (sound.useCustomAttenuation) {
  69257. sound.updateDistanceFromListener();
  69258. }
  69259. }
  69260. if (scene.soundTracks) {
  69261. for (i = 0; i < scene.soundTracks.length; i++) {
  69262. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69263. sound = scene.soundTracks[i].soundCollection[j];
  69264. if (sound.useCustomAttenuation) {
  69265. sound.updateDistanceFromListener();
  69266. }
  69267. }
  69268. }
  69269. }
  69270. }
  69271. };
  69272. return AudioSceneComponent;
  69273. }());
  69274. BABYLON.AudioSceneComponent = AudioSceneComponent;
  69275. })(BABYLON || (BABYLON = {}));
  69276. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  69277. var BABYLON;
  69278. (function (BABYLON) {
  69279. /**
  69280. * This defines an action helpful to play a defined sound on a triggered action.
  69281. */
  69282. var PlaySoundAction = /** @class */ (function (_super) {
  69283. __extends(PlaySoundAction, _super);
  69284. /**
  69285. * Instantiate the action
  69286. * @param triggerOptions defines the trigger options
  69287. * @param sound defines the sound to play
  69288. * @param condition defines the trigger related conditions
  69289. */
  69290. function PlaySoundAction(triggerOptions, sound, condition) {
  69291. var _this = _super.call(this, triggerOptions, condition) || this;
  69292. _this._sound = sound;
  69293. return _this;
  69294. }
  69295. /** @hidden */
  69296. PlaySoundAction.prototype._prepare = function () {
  69297. };
  69298. /**
  69299. * Execute the action and play the sound.
  69300. */
  69301. PlaySoundAction.prototype.execute = function () {
  69302. if (this._sound !== undefined)
  69303. this._sound.play();
  69304. };
  69305. /**
  69306. * Serializes the actions and its related information.
  69307. * @param parent defines the object to serialize in
  69308. * @returns the serialized object
  69309. */
  69310. PlaySoundAction.prototype.serialize = function (parent) {
  69311. return _super.prototype._serialize.call(this, {
  69312. name: "PlaySoundAction",
  69313. properties: [{ name: "sound", value: this._sound.name }]
  69314. }, parent);
  69315. };
  69316. return PlaySoundAction;
  69317. }(BABYLON.Action));
  69318. BABYLON.PlaySoundAction = PlaySoundAction;
  69319. /**
  69320. * This defines an action helpful to stop a defined sound on a triggered action.
  69321. */
  69322. var StopSoundAction = /** @class */ (function (_super) {
  69323. __extends(StopSoundAction, _super);
  69324. /**
  69325. * Instantiate the action
  69326. * @param triggerOptions defines the trigger options
  69327. * @param sound defines the sound to stop
  69328. * @param condition defines the trigger related conditions
  69329. */
  69330. function StopSoundAction(triggerOptions, sound, condition) {
  69331. var _this = _super.call(this, triggerOptions, condition) || this;
  69332. _this._sound = sound;
  69333. return _this;
  69334. }
  69335. /** @hidden */
  69336. StopSoundAction.prototype._prepare = function () {
  69337. };
  69338. /**
  69339. * Execute the action and stop the sound.
  69340. */
  69341. StopSoundAction.prototype.execute = function () {
  69342. if (this._sound !== undefined)
  69343. this._sound.stop();
  69344. };
  69345. /**
  69346. * Serializes the actions and its related information.
  69347. * @param parent defines the object to serialize in
  69348. * @returns the serialized object
  69349. */
  69350. StopSoundAction.prototype.serialize = function (parent) {
  69351. return _super.prototype._serialize.call(this, {
  69352. name: "StopSoundAction",
  69353. properties: [{ name: "sound", value: this._sound.name }]
  69354. }, parent);
  69355. };
  69356. return StopSoundAction;
  69357. }(BABYLON.Action));
  69358. BABYLON.StopSoundAction = StopSoundAction;
  69359. })(BABYLON || (BABYLON = {}));
  69360. //# sourceMappingURL=babylon.directAudioActions.js.map
  69361. var BABYLON;
  69362. (function (BABYLON) {
  69363. var CubeTexture = /** @class */ (function (_super) {
  69364. __extends(CubeTexture, _super);
  69365. /**
  69366. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  69367. * as prefiltered data.
  69368. * @param rootUrl defines the url of the texture or the root name of the six images
  69369. * @param scene defines the scene the texture is attached to
  69370. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  69371. * @param noMipmap defines if mipmaps should be created or not
  69372. * @param files defines the six files to load for the different faces
  69373. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  69374. * @param onError defines a callback triggered in case of error during load
  69375. * @param format defines the internal format to use for the texture once loaded
  69376. * @param prefiltered defines whether or not the texture is created from prefiltered data
  69377. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  69378. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69379. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69380. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69381. * @return the cube texture
  69382. */
  69383. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  69384. if (extensions === void 0) { extensions = null; }
  69385. if (noMipmap === void 0) { noMipmap = false; }
  69386. if (files === void 0) { files = null; }
  69387. if (onLoad === void 0) { onLoad = null; }
  69388. if (onError === void 0) { onError = null; }
  69389. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69390. if (prefiltered === void 0) { prefiltered = false; }
  69391. if (forcedExtension === void 0) { forcedExtension = null; }
  69392. if (createPolynomials === void 0) { createPolynomials = false; }
  69393. if (lodScale === void 0) { lodScale = 0.8; }
  69394. if (lodOffset === void 0) { lodOffset = 0; }
  69395. var _this = _super.call(this, scene) || this;
  69396. /**
  69397. * Gets or sets the center of the bounding box associated with the cube texture
  69398. * It must define where the camera used to render the texture was set
  69399. */
  69400. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69401. _this._rotationY = 0;
  69402. /** @hidden */
  69403. _this._prefiltered = false;
  69404. _this.name = rootUrl;
  69405. _this.url = rootUrl;
  69406. _this._noMipmap = noMipmap;
  69407. _this.hasAlpha = false;
  69408. _this._format = format;
  69409. _this.isCube = true;
  69410. _this._textureMatrix = BABYLON.Matrix.Identity();
  69411. _this._createPolynomials = createPolynomials;
  69412. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  69413. if (!rootUrl && !files) {
  69414. return _this;
  69415. }
  69416. var lastDot = rootUrl.lastIndexOf(".");
  69417. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  69418. var isDDS = (extension === ".dds");
  69419. var isEnv = (extension === ".env");
  69420. if (isEnv) {
  69421. _this.gammaSpace = false;
  69422. _this._prefiltered = false;
  69423. }
  69424. else {
  69425. _this._prefiltered = prefiltered;
  69426. if (prefiltered) {
  69427. _this.gammaSpace = false;
  69428. }
  69429. }
  69430. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  69431. if (!files) {
  69432. if (!isEnv && !isDDS && !extensions) {
  69433. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  69434. }
  69435. files = [];
  69436. if (extensions) {
  69437. for (var index = 0; index < extensions.length; index++) {
  69438. files.push(rootUrl + extensions[index]);
  69439. }
  69440. }
  69441. }
  69442. _this._files = files;
  69443. if (!_this._texture) {
  69444. if (!scene.useDelayedTextureLoading) {
  69445. if (prefiltered) {
  69446. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  69447. }
  69448. else {
  69449. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  69450. }
  69451. }
  69452. else {
  69453. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  69454. }
  69455. }
  69456. else if (onLoad) {
  69457. if (_this._texture.isReady) {
  69458. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  69459. }
  69460. else {
  69461. _this._texture.onLoadedObservable.add(onLoad);
  69462. }
  69463. }
  69464. return _this;
  69465. }
  69466. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  69467. get: function () {
  69468. return this._boundingBoxSize;
  69469. },
  69470. /**
  69471. * Gets or sets the size of the bounding box associated with the cube texture
  69472. * When defined, the cubemap will switch to local mode
  69473. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69474. * @example https://www.babylonjs-playground.com/#RNASML
  69475. */
  69476. set: function (value) {
  69477. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69478. return;
  69479. }
  69480. this._boundingBoxSize = value;
  69481. var scene = this.getScene();
  69482. if (scene) {
  69483. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69484. }
  69485. },
  69486. enumerable: true,
  69487. configurable: true
  69488. });
  69489. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  69490. /**
  69491. * Gets texture matrix rotation angle around Y axis radians.
  69492. */
  69493. get: function () {
  69494. return this._rotationY;
  69495. },
  69496. /**
  69497. * Sets texture matrix rotation angle around Y axis in radians.
  69498. */
  69499. set: function (value) {
  69500. this._rotationY = value;
  69501. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  69502. },
  69503. enumerable: true,
  69504. configurable: true
  69505. });
  69506. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  69507. var rootUrlKey = "";
  69508. files.forEach(function (url) { return rootUrlKey += url; });
  69509. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  69510. };
  69511. /**
  69512. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  69513. * @param url defines the url of the prefiltered texture
  69514. * @param scene defines the scene the texture is attached to
  69515. * @param forcedExtension defines the extension of the file if different from the url
  69516. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69517. * @return the prefiltered texture
  69518. */
  69519. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  69520. if (forcedExtension === void 0) { forcedExtension = null; }
  69521. if (createPolynomials === void 0) { createPolynomials = true; }
  69522. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  69523. };
  69524. // Methods
  69525. CubeTexture.prototype.delayLoad = function () {
  69526. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69527. return;
  69528. }
  69529. var scene = this.getScene();
  69530. if (!scene) {
  69531. return;
  69532. }
  69533. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69534. this._texture = this._getFromCache(this.url, this._noMipmap);
  69535. if (!this._texture) {
  69536. if (this._prefiltered) {
  69537. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  69538. }
  69539. else {
  69540. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  69541. }
  69542. }
  69543. };
  69544. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  69545. return this._textureMatrix;
  69546. };
  69547. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69548. this._textureMatrix = value;
  69549. };
  69550. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69551. var texture = BABYLON.SerializationHelper.Parse(function () {
  69552. var prefiltered = false;
  69553. if (parsedTexture.prefiltered) {
  69554. prefiltered = parsedTexture.prefiltered;
  69555. }
  69556. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  69557. }, parsedTexture, scene);
  69558. // Local Cubemaps
  69559. if (parsedTexture.boundingBoxPosition) {
  69560. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  69561. }
  69562. if (parsedTexture.boundingBoxSize) {
  69563. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  69564. }
  69565. // Animations
  69566. if (parsedTexture.animations) {
  69567. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  69568. var parsedAnimation = parsedTexture.animations[animationIndex];
  69569. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69570. }
  69571. }
  69572. return texture;
  69573. };
  69574. CubeTexture.prototype.clone = function () {
  69575. var _this = this;
  69576. return BABYLON.SerializationHelper.Clone(function () {
  69577. var scene = _this.getScene();
  69578. if (!scene) {
  69579. return _this;
  69580. }
  69581. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  69582. }, this);
  69583. };
  69584. __decorate([
  69585. BABYLON.serialize("rotationY")
  69586. ], CubeTexture.prototype, "rotationY", null);
  69587. return CubeTexture;
  69588. }(BABYLON.BaseTexture));
  69589. BABYLON.CubeTexture = CubeTexture;
  69590. })(BABYLON || (BABYLON = {}));
  69591. //# sourceMappingURL=babylon.cubeTexture.js.map
  69592. var BABYLON;
  69593. (function (BABYLON) {
  69594. /**
  69595. * Raw cube texture where the raw buffers are passed in
  69596. */
  69597. var RawCubeTexture = /** @class */ (function (_super) {
  69598. __extends(RawCubeTexture, _super);
  69599. /**
  69600. * Creates a cube texture where the raw buffers are passed in.
  69601. * @param scene defines the scene the texture is attached to
  69602. * @param data defines the array of data to use to create each face
  69603. * @param size defines the size of the textures
  69604. * @param format defines the format of the data
  69605. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  69606. * @param generateMipMaps defines if the engine should generate the mip levels
  69607. * @param invertY defines if data must be stored with Y axis inverted
  69608. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  69609. * @param compression defines the compression used (null by default)
  69610. */
  69611. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  69612. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69613. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69614. if (generateMipMaps === void 0) { generateMipMaps = false; }
  69615. if (invertY === void 0) { invertY = false; }
  69616. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69617. if (compression === void 0) { compression = null; }
  69618. var _this = _super.call(this, "", scene) || this;
  69619. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  69620. return _this;
  69621. }
  69622. /**
  69623. * Updates the raw cube texture.
  69624. * @param data defines the data to store
  69625. * @param format defines the data format
  69626. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  69627. * @param invertY defines if data must be stored with Y axis inverted
  69628. * @param compression defines the compression used (null by default)
  69629. * @param level defines which level of the texture to update
  69630. */
  69631. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  69632. if (compression === void 0) { compression = null; }
  69633. if (level === void 0) { level = 0; }
  69634. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  69635. };
  69636. /**
  69637. * Updates a raw cube texture with RGBD encoded data.
  69638. * @param data defines the array of data [mipmap][face] to use to create each face
  69639. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  69640. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69641. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69642. * @returns a promsie that resolves when the operation is complete
  69643. */
  69644. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  69645. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  69646. if (lodScale === void 0) { lodScale = 0.8; }
  69647. if (lodOffset === void 0) { lodOffset = 0; }
  69648. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  69649. };
  69650. /**
  69651. * Clones the raw cube texture.
  69652. * @return a new cube texture
  69653. */
  69654. RawCubeTexture.prototype.clone = function () {
  69655. var _this = this;
  69656. return BABYLON.SerializationHelper.Clone(function () {
  69657. var scene = _this.getScene();
  69658. var internalTexture = _this._texture;
  69659. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  69660. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  69661. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  69662. }
  69663. return texture;
  69664. }, this);
  69665. };
  69666. /** @hidden */
  69667. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  69668. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  69669. internalTexture._bufferViewArrayArray = data;
  69670. internalTexture._lodGenerationScale = lodScale;
  69671. internalTexture._lodGenerationOffset = lodOffset;
  69672. internalTexture._sphericalPolynomial = sphericalPolynomial;
  69673. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  69674. internalTexture.isReady = true;
  69675. });
  69676. };
  69677. return RawCubeTexture;
  69678. }(BABYLON.CubeTexture));
  69679. BABYLON.RawCubeTexture = RawCubeTexture;
  69680. })(BABYLON || (BABYLON = {}));
  69681. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  69682. var BABYLON;
  69683. (function (BABYLON) {
  69684. var RenderTargetTexture = /** @class */ (function (_super) {
  69685. __extends(RenderTargetTexture, _super);
  69686. /**
  69687. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  69688. * or used a shadow, depth texture...
  69689. * @param name The friendly name of the texture
  69690. * @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)
  69691. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  69692. * @param generateMipMaps True if mip maps need to be generated after render.
  69693. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  69694. * @param type The type of the buffer in the RTT (int, half float, float...)
  69695. * @param isCube True if a cube texture needs to be created
  69696. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  69697. * @param generateDepthBuffer True to generate a depth buffer
  69698. * @param generateStencilBuffer True to generate a stencil buffer
  69699. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  69700. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  69701. */
  69702. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  69703. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  69704. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69705. if (isCube === void 0) { isCube = false; }
  69706. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69707. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  69708. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  69709. if (isMulti === void 0) { isMulti = false; }
  69710. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69711. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69712. _this.isCube = isCube;
  69713. _this.renderParticles = true;
  69714. _this.renderSprites = false;
  69715. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  69716. _this.ignoreCameraViewport = false;
  69717. // Events
  69718. /**
  69719. * An event triggered when the texture is unbind.
  69720. */
  69721. _this.onBeforeBindObservable = new BABYLON.Observable();
  69722. /**
  69723. * An event triggered when the texture is unbind.
  69724. */
  69725. _this.onAfterUnbindObservable = new BABYLON.Observable();
  69726. /**
  69727. * An event triggered before rendering the texture
  69728. */
  69729. _this.onBeforeRenderObservable = new BABYLON.Observable();
  69730. /**
  69731. * An event triggered after rendering the texture
  69732. */
  69733. _this.onAfterRenderObservable = new BABYLON.Observable();
  69734. /**
  69735. * An event triggered after the texture clear
  69736. */
  69737. _this.onClearObservable = new BABYLON.Observable();
  69738. _this._currentRefreshId = -1;
  69739. _this._refreshRate = 1;
  69740. _this._samples = 1;
  69741. /**
  69742. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  69743. * It must define where the camera used to render the texture is set
  69744. */
  69745. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69746. scene = _this.getScene();
  69747. if (!scene) {
  69748. return _this;
  69749. }
  69750. _this.renderList = new Array();
  69751. _this._engine = scene.getEngine();
  69752. _this.name = name;
  69753. _this.isRenderTarget = true;
  69754. _this._initialSizeParameter = size;
  69755. _this._processSizeParameter(size);
  69756. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  69757. });
  69758. _this._generateMipMaps = generateMipMaps ? true : false;
  69759. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  69760. // Rendering groups
  69761. _this._renderingManager = new BABYLON.RenderingManager(scene);
  69762. _this._renderingManager._useSceneAutoClearSetup = true;
  69763. if (isMulti) {
  69764. return _this;
  69765. }
  69766. _this._renderTargetOptions = {
  69767. generateMipMaps: generateMipMaps,
  69768. type: type,
  69769. format: format,
  69770. samplingMode: samplingMode,
  69771. generateDepthBuffer: generateDepthBuffer,
  69772. generateStencilBuffer: generateStencilBuffer
  69773. };
  69774. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  69775. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69776. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69777. }
  69778. if (isCube) {
  69779. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  69780. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  69781. _this._textureMatrix = BABYLON.Matrix.Identity();
  69782. }
  69783. else {
  69784. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  69785. }
  69786. return _this;
  69787. }
  69788. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  69789. get: function () {
  69790. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  69791. },
  69792. enumerable: true,
  69793. configurable: true
  69794. });
  69795. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  69796. get: function () {
  69797. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  69798. },
  69799. enumerable: true,
  69800. configurable: true
  69801. });
  69802. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  69803. get: function () {
  69804. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  69805. },
  69806. enumerable: true,
  69807. configurable: true
  69808. });
  69809. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  69810. /**
  69811. * Use this list to define the list of mesh you want to render.
  69812. */
  69813. get: function () {
  69814. return this._renderList;
  69815. },
  69816. set: function (value) {
  69817. this._renderList = value;
  69818. if (this._renderList) {
  69819. this._hookArray(this._renderList);
  69820. }
  69821. },
  69822. enumerable: true,
  69823. configurable: true
  69824. });
  69825. RenderTargetTexture.prototype._hookArray = function (array) {
  69826. var _this = this;
  69827. var oldPush = array.push;
  69828. array.push = function () {
  69829. var items = [];
  69830. for (var _i = 0; _i < arguments.length; _i++) {
  69831. items[_i] = arguments[_i];
  69832. }
  69833. var result = oldPush.apply(array, items);
  69834. _this.getScene().meshes.forEach(function (mesh) {
  69835. mesh._markSubMeshesAsLightDirty();
  69836. });
  69837. return result;
  69838. };
  69839. var oldSplice = array.splice;
  69840. array.splice = function (index, deleteCount) {
  69841. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69842. _this.getScene().meshes.forEach(function (mesh) {
  69843. mesh._markSubMeshesAsLightDirty();
  69844. });
  69845. return deleted;
  69846. };
  69847. };
  69848. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  69849. set: function (callback) {
  69850. if (this._onAfterUnbindObserver) {
  69851. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  69852. }
  69853. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  69854. },
  69855. enumerable: true,
  69856. configurable: true
  69857. });
  69858. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  69859. set: function (callback) {
  69860. if (this._onBeforeRenderObserver) {
  69861. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69862. }
  69863. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69864. },
  69865. enumerable: true,
  69866. configurable: true
  69867. });
  69868. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  69869. set: function (callback) {
  69870. if (this._onAfterRenderObserver) {
  69871. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69872. }
  69873. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69874. },
  69875. enumerable: true,
  69876. configurable: true
  69877. });
  69878. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  69879. set: function (callback) {
  69880. if (this._onClearObserver) {
  69881. this.onClearObservable.remove(this._onClearObserver);
  69882. }
  69883. this._onClearObserver = this.onClearObservable.add(callback);
  69884. },
  69885. enumerable: true,
  69886. configurable: true
  69887. });
  69888. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  69889. get: function () {
  69890. return this._renderTargetOptions;
  69891. },
  69892. enumerable: true,
  69893. configurable: true
  69894. });
  69895. RenderTargetTexture.prototype._onRatioRescale = function () {
  69896. if (this._sizeRatio) {
  69897. this.resize(this._initialSizeParameter);
  69898. }
  69899. };
  69900. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  69901. get: function () {
  69902. return this._boundingBoxSize;
  69903. },
  69904. /**
  69905. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  69906. * When defined, the cubemap will switch to local mode
  69907. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69908. * @example https://www.babylonjs-playground.com/#RNASML
  69909. */
  69910. set: function (value) {
  69911. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69912. return;
  69913. }
  69914. this._boundingBoxSize = value;
  69915. var scene = this.getScene();
  69916. if (scene) {
  69917. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69918. }
  69919. },
  69920. enumerable: true,
  69921. configurable: true
  69922. });
  69923. /**
  69924. * Creates a depth stencil texture.
  69925. * This is only available in WebGL 2 or with the depth texture extension available.
  69926. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  69927. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  69928. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  69929. */
  69930. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  69931. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  69932. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  69933. if (generateStencil === void 0) { generateStencil = false; }
  69934. if (!this.getScene()) {
  69935. return;
  69936. }
  69937. var engine = this.getScene().getEngine();
  69938. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  69939. bilinearFiltering: bilinearFiltering,
  69940. comparisonFunction: comparisonFunction,
  69941. generateStencil: generateStencil,
  69942. isCube: this.isCube
  69943. });
  69944. engine.setFrameBufferDepthStencilTexture(this);
  69945. };
  69946. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  69947. if (size.ratio) {
  69948. this._sizeRatio = size.ratio;
  69949. this._size = {
  69950. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  69951. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  69952. };
  69953. }
  69954. else {
  69955. this._size = size;
  69956. }
  69957. };
  69958. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  69959. get: function () {
  69960. return this._samples;
  69961. },
  69962. set: function (value) {
  69963. if (this._samples === value) {
  69964. return;
  69965. }
  69966. var scene = this.getScene();
  69967. if (!scene) {
  69968. return;
  69969. }
  69970. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  69971. },
  69972. enumerable: true,
  69973. configurable: true
  69974. });
  69975. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  69976. this._currentRefreshId = -1;
  69977. };
  69978. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  69979. get: function () {
  69980. return this._refreshRate;
  69981. },
  69982. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69983. set: function (value) {
  69984. this._refreshRate = value;
  69985. this.resetRefreshCounter();
  69986. },
  69987. enumerable: true,
  69988. configurable: true
  69989. });
  69990. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  69991. if (!this._postProcessManager) {
  69992. var scene = this.getScene();
  69993. if (!scene) {
  69994. return;
  69995. }
  69996. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  69997. this._postProcesses = new Array();
  69998. }
  69999. this._postProcesses.push(postProcess);
  70000. this._postProcesses[0].autoClear = false;
  70001. };
  70002. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  70003. if (!this._postProcesses) {
  70004. return;
  70005. }
  70006. if (dispose) {
  70007. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  70008. var postProcess = _a[_i];
  70009. postProcess.dispose();
  70010. }
  70011. }
  70012. this._postProcesses = [];
  70013. };
  70014. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  70015. if (!this._postProcesses) {
  70016. return;
  70017. }
  70018. var index = this._postProcesses.indexOf(postProcess);
  70019. if (index === -1) {
  70020. return;
  70021. }
  70022. this._postProcesses.splice(index, 1);
  70023. if (this._postProcesses.length > 0) {
  70024. this._postProcesses[0].autoClear = false;
  70025. }
  70026. };
  70027. /** @hidden */
  70028. RenderTargetTexture.prototype._shouldRender = function () {
  70029. if (this._currentRefreshId === -1) { // At least render once
  70030. this._currentRefreshId = 1;
  70031. return true;
  70032. }
  70033. if (this.refreshRate === this._currentRefreshId) {
  70034. this._currentRefreshId = 1;
  70035. return true;
  70036. }
  70037. this._currentRefreshId++;
  70038. return false;
  70039. };
  70040. RenderTargetTexture.prototype.getRenderSize = function () {
  70041. if (this._size.width) {
  70042. return this._size.width;
  70043. }
  70044. return this._size;
  70045. };
  70046. RenderTargetTexture.prototype.getRenderWidth = function () {
  70047. if (this._size.width) {
  70048. return this._size.width;
  70049. }
  70050. return this._size;
  70051. };
  70052. RenderTargetTexture.prototype.getRenderHeight = function () {
  70053. if (this._size.width) {
  70054. return this._size.height;
  70055. }
  70056. return this._size;
  70057. };
  70058. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  70059. get: function () {
  70060. return true;
  70061. },
  70062. enumerable: true,
  70063. configurable: true
  70064. });
  70065. RenderTargetTexture.prototype.scale = function (ratio) {
  70066. var newSize = this.getRenderSize() * ratio;
  70067. this.resize(newSize);
  70068. };
  70069. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  70070. if (this.isCube) {
  70071. return this._textureMatrix;
  70072. }
  70073. return _super.prototype.getReflectionTextureMatrix.call(this);
  70074. };
  70075. RenderTargetTexture.prototype.resize = function (size) {
  70076. this.releaseInternalTexture();
  70077. var scene = this.getScene();
  70078. if (!scene) {
  70079. return;
  70080. }
  70081. this._processSizeParameter(size);
  70082. if (this.isCube) {
  70083. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  70084. }
  70085. else {
  70086. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  70087. }
  70088. };
  70089. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  70090. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  70091. if (dumpForDebug === void 0) { dumpForDebug = false; }
  70092. var scene = this.getScene();
  70093. if (!scene) {
  70094. return;
  70095. }
  70096. var engine = scene.getEngine();
  70097. if (this.useCameraPostProcesses !== undefined) {
  70098. useCameraPostProcess = this.useCameraPostProcesses;
  70099. }
  70100. if (this._waitingRenderList) {
  70101. this.renderList = [];
  70102. for (var index = 0; index < this._waitingRenderList.length; index++) {
  70103. var id = this._waitingRenderList[index];
  70104. var mesh_1 = scene.getMeshByID(id);
  70105. if (mesh_1) {
  70106. this.renderList.push(mesh_1);
  70107. }
  70108. }
  70109. delete this._waitingRenderList;
  70110. }
  70111. // Is predicate defined?
  70112. if (this.renderListPredicate) {
  70113. if (this.renderList) {
  70114. this.renderList.splice(0); // Clear previous renderList
  70115. }
  70116. else {
  70117. this.renderList = [];
  70118. }
  70119. var scene = this.getScene();
  70120. if (!scene) {
  70121. return;
  70122. }
  70123. var sceneMeshes = scene.meshes;
  70124. for (var index = 0; index < sceneMeshes.length; index++) {
  70125. var mesh = sceneMeshes[index];
  70126. if (this.renderListPredicate(mesh)) {
  70127. this.renderList.push(mesh);
  70128. }
  70129. }
  70130. }
  70131. this.onBeforeBindObservable.notifyObservers(this);
  70132. // Set custom projection.
  70133. // Needs to be before binding to prevent changing the aspect ratio.
  70134. var camera;
  70135. if (this.activeCamera) {
  70136. camera = this.activeCamera;
  70137. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  70138. if (this.activeCamera !== scene.activeCamera) {
  70139. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  70140. }
  70141. }
  70142. else {
  70143. camera = scene.activeCamera;
  70144. if (camera) {
  70145. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  70146. }
  70147. }
  70148. // Prepare renderingManager
  70149. this._renderingManager.reset();
  70150. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  70151. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  70152. var sceneRenderId = scene.getRenderId();
  70153. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  70154. var mesh = currentRenderList[meshIndex];
  70155. if (mesh) {
  70156. if (!mesh.isReady(this.refreshRate === 0)) {
  70157. this.resetRefreshCounter();
  70158. continue;
  70159. }
  70160. mesh._preActivateForIntermediateRendering(sceneRenderId);
  70161. var isMasked = void 0;
  70162. if (!this.renderList && camera) {
  70163. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  70164. }
  70165. else {
  70166. isMasked = false;
  70167. }
  70168. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  70169. mesh._activate(sceneRenderId);
  70170. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  70171. var subMesh = mesh.subMeshes[subIndex];
  70172. scene._activeIndices.addCount(subMesh.indexCount, false);
  70173. this._renderingManager.dispatch(subMesh, mesh);
  70174. }
  70175. }
  70176. }
  70177. }
  70178. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  70179. var particleSystem = scene.particleSystems[particleIndex];
  70180. var emitter = particleSystem.emitter;
  70181. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  70182. continue;
  70183. }
  70184. if (currentRenderList.indexOf(emitter) >= 0) {
  70185. this._renderingManager.dispatchParticles(particleSystem);
  70186. }
  70187. }
  70188. if (this.isCube) {
  70189. for (var face = 0; face < 6; face++) {
  70190. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  70191. scene.incrementRenderId();
  70192. scene.resetCachedMaterial();
  70193. }
  70194. }
  70195. else {
  70196. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  70197. }
  70198. this.onAfterUnbindObservable.notifyObservers(this);
  70199. if (scene.activeCamera) {
  70200. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  70201. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  70202. }
  70203. engine.setViewport(scene.activeCamera.viewport);
  70204. }
  70205. scene.resetCachedMaterial();
  70206. };
  70207. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  70208. var minimum = 128;
  70209. var x = renderDimension * scale;
  70210. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  70211. // Ensure we don't exceed the render dimension (while staying POT)
  70212. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  70213. };
  70214. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70215. var _this = this;
  70216. if (!this._texture) {
  70217. return;
  70218. }
  70219. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  70220. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70221. });
  70222. };
  70223. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  70224. var scene = this.getScene();
  70225. if (!scene) {
  70226. return;
  70227. }
  70228. var engine = scene.getEngine();
  70229. if (!this._texture) {
  70230. return;
  70231. }
  70232. // Bind
  70233. if (this._postProcessManager) {
  70234. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  70235. }
  70236. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  70237. if (this._texture) {
  70238. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  70239. }
  70240. }
  70241. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  70242. // Clear
  70243. if (this.onClearObservable.hasObservers()) {
  70244. this.onClearObservable.notifyObservers(engine);
  70245. }
  70246. else {
  70247. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  70248. }
  70249. if (!this._doNotChangeAspectRatio) {
  70250. scene.updateTransformMatrix(true);
  70251. }
  70252. // Render
  70253. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  70254. if (this._postProcessManager) {
  70255. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  70256. }
  70257. else if (useCameraPostProcess) {
  70258. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  70259. }
  70260. if (!this._doNotChangeAspectRatio) {
  70261. scene.updateTransformMatrix(true);
  70262. }
  70263. // Dump ?
  70264. if (dumpForDebug) {
  70265. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  70266. }
  70267. // Unbind
  70268. if (!this.isCube || faceIndex === 5) {
  70269. if (this.isCube) {
  70270. if (faceIndex === 5) {
  70271. engine.generateMipMapsForCubemap(this._texture);
  70272. }
  70273. }
  70274. this.unbindFrameBuffer(engine, faceIndex);
  70275. }
  70276. else {
  70277. this.onAfterRenderObservable.notifyObservers(faceIndex);
  70278. }
  70279. };
  70280. /**
  70281. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  70282. * This allowed control for front to back rendering or reversly depending of the special needs.
  70283. *
  70284. * @param renderingGroupId The rendering group id corresponding to its index
  70285. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  70286. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  70287. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  70288. */
  70289. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  70290. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  70291. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  70292. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  70293. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  70294. };
  70295. /**
  70296. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  70297. *
  70298. * @param renderingGroupId The rendering group id corresponding to its index
  70299. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  70300. */
  70301. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  70302. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  70303. this._renderingManager._useSceneAutoClearSetup = false;
  70304. };
  70305. RenderTargetTexture.prototype.clone = function () {
  70306. var textureSize = this.getSize();
  70307. 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);
  70308. // Base texture
  70309. newTexture.hasAlpha = this.hasAlpha;
  70310. newTexture.level = this.level;
  70311. // RenderTarget Texture
  70312. newTexture.coordinatesMode = this.coordinatesMode;
  70313. if (this.renderList) {
  70314. newTexture.renderList = this.renderList.slice(0);
  70315. }
  70316. return newTexture;
  70317. };
  70318. RenderTargetTexture.prototype.serialize = function () {
  70319. if (!this.name) {
  70320. return null;
  70321. }
  70322. var serializationObject = _super.prototype.serialize.call(this);
  70323. serializationObject.renderTargetSize = this.getRenderSize();
  70324. serializationObject.renderList = [];
  70325. if (this.renderList) {
  70326. for (var index = 0; index < this.renderList.length; index++) {
  70327. serializationObject.renderList.push(this.renderList[index].id);
  70328. }
  70329. }
  70330. return serializationObject;
  70331. };
  70332. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  70333. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  70334. var objBuffer = this.getInternalTexture();
  70335. var scene = this.getScene();
  70336. if (objBuffer && scene) {
  70337. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  70338. }
  70339. };
  70340. RenderTargetTexture.prototype.dispose = function () {
  70341. if (this._postProcessManager) {
  70342. this._postProcessManager.dispose();
  70343. this._postProcessManager = null;
  70344. }
  70345. this.clearPostProcesses(true);
  70346. if (this._resizeObserver) {
  70347. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  70348. this._resizeObserver = null;
  70349. }
  70350. this.renderList = null;
  70351. // Remove from custom render targets
  70352. var scene = this.getScene();
  70353. if (!scene) {
  70354. return;
  70355. }
  70356. var index = scene.customRenderTargets.indexOf(this);
  70357. if (index >= 0) {
  70358. scene.customRenderTargets.splice(index, 1);
  70359. }
  70360. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  70361. var camera = _a[_i];
  70362. index = camera.customRenderTargets.indexOf(this);
  70363. if (index >= 0) {
  70364. camera.customRenderTargets.splice(index, 1);
  70365. }
  70366. }
  70367. _super.prototype.dispose.call(this);
  70368. };
  70369. /** @hidden */
  70370. RenderTargetTexture.prototype._rebuild = function () {
  70371. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70372. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70373. }
  70374. if (this._postProcessManager) {
  70375. this._postProcessManager._rebuild();
  70376. }
  70377. };
  70378. /**
  70379. * Clear the info related to rendering groups preventing retention point in material dispose.
  70380. */
  70381. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  70382. if (this._renderingManager) {
  70383. this._renderingManager.freeRenderingGroups();
  70384. }
  70385. };
  70386. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  70387. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  70388. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  70389. return RenderTargetTexture;
  70390. }(BABYLON.Texture));
  70391. BABYLON.RenderTargetTexture = RenderTargetTexture;
  70392. })(BABYLON || (BABYLON = {}));
  70393. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  70394. var BABYLON;
  70395. (function (BABYLON) {
  70396. ;
  70397. var MultiRenderTarget = /** @class */ (function (_super) {
  70398. __extends(MultiRenderTarget, _super);
  70399. function MultiRenderTarget(name, size, count, scene, options) {
  70400. var _this = this;
  70401. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  70402. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  70403. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  70404. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  70405. _this._engine = scene.getEngine();
  70406. if (!_this.isSupported) {
  70407. _this.dispose();
  70408. return;
  70409. }
  70410. var types = [];
  70411. var samplingModes = [];
  70412. for (var i = 0; i < count; i++) {
  70413. if (options && options.types && options.types[i] !== undefined) {
  70414. types.push(options.types[i]);
  70415. }
  70416. else {
  70417. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70418. }
  70419. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  70420. samplingModes.push(options.samplingModes[i]);
  70421. }
  70422. else {
  70423. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70424. }
  70425. }
  70426. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  70427. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  70428. _this._size = size;
  70429. _this._multiRenderTargetOptions = {
  70430. samplingModes: samplingModes,
  70431. generateMipMaps: generateMipMaps,
  70432. generateDepthBuffer: generateDepthBuffer,
  70433. generateStencilBuffer: generateStencilBuffer,
  70434. generateDepthTexture: generateDepthTexture,
  70435. types: types,
  70436. textureCount: count
  70437. };
  70438. _this._createInternalTextures();
  70439. _this._createTextures();
  70440. return _this;
  70441. }
  70442. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  70443. get: function () {
  70444. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  70445. },
  70446. enumerable: true,
  70447. configurable: true
  70448. });
  70449. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  70450. get: function () {
  70451. return this._textures;
  70452. },
  70453. enumerable: true,
  70454. configurable: true
  70455. });
  70456. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  70457. get: function () {
  70458. return this._textures[this._textures.length - 1];
  70459. },
  70460. enumerable: true,
  70461. configurable: true
  70462. });
  70463. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  70464. set: function (wrap) {
  70465. if (this._textures) {
  70466. for (var i = 0; i < this._textures.length; i++) {
  70467. this._textures[i].wrapU = wrap;
  70468. }
  70469. }
  70470. },
  70471. enumerable: true,
  70472. configurable: true
  70473. });
  70474. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  70475. set: function (wrap) {
  70476. if (this._textures) {
  70477. for (var i = 0; i < this._textures.length; i++) {
  70478. this._textures[i].wrapV = wrap;
  70479. }
  70480. }
  70481. },
  70482. enumerable: true,
  70483. configurable: true
  70484. });
  70485. /** @hidden */
  70486. MultiRenderTarget.prototype._rebuild = function () {
  70487. this.releaseInternalTextures();
  70488. this._createInternalTextures();
  70489. for (var i = 0; i < this._internalTextures.length; i++) {
  70490. var texture = this._textures[i];
  70491. texture._texture = this._internalTextures[i];
  70492. }
  70493. // Keeps references to frame buffer and stencil/depth buffer
  70494. this._texture = this._internalTextures[0];
  70495. };
  70496. MultiRenderTarget.prototype._createInternalTextures = function () {
  70497. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  70498. };
  70499. MultiRenderTarget.prototype._createTextures = function () {
  70500. this._textures = [];
  70501. for (var i = 0; i < this._internalTextures.length; i++) {
  70502. var texture = new BABYLON.Texture(null, this.getScene());
  70503. texture._texture = this._internalTextures[i];
  70504. this._textures.push(texture);
  70505. }
  70506. // Keeps references to frame buffer and stencil/depth buffer
  70507. this._texture = this._internalTextures[0];
  70508. };
  70509. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  70510. get: function () {
  70511. return this._samples;
  70512. },
  70513. set: function (value) {
  70514. if (this._samples === value) {
  70515. return;
  70516. }
  70517. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  70518. },
  70519. enumerable: true,
  70520. configurable: true
  70521. });
  70522. MultiRenderTarget.prototype.resize = function (size) {
  70523. this.releaseInternalTextures();
  70524. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  70525. this._createInternalTextures();
  70526. };
  70527. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70528. var _this = this;
  70529. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  70530. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70531. });
  70532. };
  70533. MultiRenderTarget.prototype.dispose = function () {
  70534. this.releaseInternalTextures();
  70535. _super.prototype.dispose.call(this);
  70536. };
  70537. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  70538. if (!this._internalTextures) {
  70539. return;
  70540. }
  70541. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  70542. if (this._internalTextures[i] !== undefined) {
  70543. this._internalTextures[i].dispose();
  70544. this._internalTextures.splice(i, 1);
  70545. }
  70546. }
  70547. };
  70548. return MultiRenderTarget;
  70549. }(BABYLON.RenderTargetTexture));
  70550. BABYLON.MultiRenderTarget = MultiRenderTarget;
  70551. })(BABYLON || (BABYLON = {}));
  70552. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  70553. var BABYLON;
  70554. (function (BABYLON) {
  70555. var MirrorTexture = /** @class */ (function (_super) {
  70556. __extends(MirrorTexture, _super);
  70557. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  70558. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70559. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70560. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70561. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  70562. _this.scene = scene;
  70563. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  70564. _this._transformMatrix = BABYLON.Matrix.Zero();
  70565. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  70566. _this._adaptiveBlurKernel = 0;
  70567. _this._blurKernelX = 0;
  70568. _this._blurKernelY = 0;
  70569. _this._blurRatio = 1.0;
  70570. _this.ignoreCameraViewport = true;
  70571. _this._updateGammaSpace();
  70572. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70573. _this._updateGammaSpace;
  70574. });
  70575. _this.onBeforeRenderObservable.add(function () {
  70576. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  70577. _this._savedViewMatrix = scene.getViewMatrix();
  70578. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  70579. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  70580. scene.clipPlane = _this.mirrorPlane;
  70581. scene.getEngine().cullBackFaces = false;
  70582. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  70583. });
  70584. _this.onAfterRenderObservable.add(function () {
  70585. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  70586. scene.getEngine().cullBackFaces = true;
  70587. scene._mirroredCameraPosition = null;
  70588. delete scene.clipPlane;
  70589. });
  70590. return _this;
  70591. }
  70592. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  70593. get: function () {
  70594. return this._blurRatio;
  70595. },
  70596. set: function (value) {
  70597. if (this._blurRatio === value) {
  70598. return;
  70599. }
  70600. this._blurRatio = value;
  70601. this._preparePostProcesses();
  70602. },
  70603. enumerable: true,
  70604. configurable: true
  70605. });
  70606. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  70607. set: function (value) {
  70608. this._adaptiveBlurKernel = value;
  70609. this._autoComputeBlurKernel();
  70610. },
  70611. enumerable: true,
  70612. configurable: true
  70613. });
  70614. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  70615. set: function (value) {
  70616. this.blurKernelX = value;
  70617. this.blurKernelY = value;
  70618. },
  70619. enumerable: true,
  70620. configurable: true
  70621. });
  70622. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  70623. get: function () {
  70624. return this._blurKernelX;
  70625. },
  70626. set: function (value) {
  70627. if (this._blurKernelX === value) {
  70628. return;
  70629. }
  70630. this._blurKernelX = value;
  70631. this._preparePostProcesses();
  70632. },
  70633. enumerable: true,
  70634. configurable: true
  70635. });
  70636. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  70637. get: function () {
  70638. return this._blurKernelY;
  70639. },
  70640. set: function (value) {
  70641. if (this._blurKernelY === value) {
  70642. return;
  70643. }
  70644. this._blurKernelY = value;
  70645. this._preparePostProcesses();
  70646. },
  70647. enumerable: true,
  70648. configurable: true
  70649. });
  70650. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  70651. var engine = this.getScene().getEngine();
  70652. var dw = this.getRenderWidth() / engine.getRenderWidth();
  70653. var dh = this.getRenderHeight() / engine.getRenderHeight();
  70654. this.blurKernelX = this._adaptiveBlurKernel * dw;
  70655. this.blurKernelY = this._adaptiveBlurKernel * dh;
  70656. };
  70657. MirrorTexture.prototype._onRatioRescale = function () {
  70658. if (this._sizeRatio) {
  70659. this.resize(this._initialSizeParameter);
  70660. if (!this._adaptiveBlurKernel) {
  70661. this._preparePostProcesses();
  70662. }
  70663. }
  70664. if (this._adaptiveBlurKernel) {
  70665. this._autoComputeBlurKernel();
  70666. }
  70667. };
  70668. MirrorTexture.prototype._updateGammaSpace = function () {
  70669. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  70670. };
  70671. MirrorTexture.prototype._preparePostProcesses = function () {
  70672. this.clearPostProcesses(true);
  70673. if (this._blurKernelX && this._blurKernelY) {
  70674. var engine = this.getScene().getEngine();
  70675. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70676. 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);
  70677. this._blurX.autoClear = false;
  70678. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  70679. this._blurX.inputTexture = this._texture;
  70680. }
  70681. else {
  70682. this._blurX.alwaysForcePOT = true;
  70683. }
  70684. 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);
  70685. this._blurY.autoClear = false;
  70686. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  70687. this.addPostProcess(this._blurX);
  70688. this.addPostProcess(this._blurY);
  70689. }
  70690. else {
  70691. if (this._blurY) {
  70692. this.removePostProcess(this._blurY);
  70693. this._blurY.dispose();
  70694. this._blurY = null;
  70695. }
  70696. if (this._blurX) {
  70697. this.removePostProcess(this._blurX);
  70698. this._blurX.dispose();
  70699. this._blurX = null;
  70700. }
  70701. }
  70702. };
  70703. MirrorTexture.prototype.clone = function () {
  70704. var scene = this.getScene();
  70705. if (!scene) {
  70706. return this;
  70707. }
  70708. var textureSize = this.getSize();
  70709. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  70710. // Base texture
  70711. newTexture.hasAlpha = this.hasAlpha;
  70712. newTexture.level = this.level;
  70713. // Mirror Texture
  70714. newTexture.mirrorPlane = this.mirrorPlane.clone();
  70715. if (this.renderList) {
  70716. newTexture.renderList = this.renderList.slice(0);
  70717. }
  70718. return newTexture;
  70719. };
  70720. MirrorTexture.prototype.serialize = function () {
  70721. if (!this.name) {
  70722. return null;
  70723. }
  70724. var serializationObject = _super.prototype.serialize.call(this);
  70725. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  70726. return serializationObject;
  70727. };
  70728. MirrorTexture.prototype.dispose = function () {
  70729. _super.prototype.dispose.call(this);
  70730. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  70731. };
  70732. return MirrorTexture;
  70733. }(BABYLON.RenderTargetTexture));
  70734. BABYLON.MirrorTexture = MirrorTexture;
  70735. })(BABYLON || (BABYLON = {}));
  70736. //# sourceMappingURL=babylon.mirrorTexture.js.map
  70737. var BABYLON;
  70738. (function (BABYLON) {
  70739. /**
  70740. * Creates a refraction texture used by refraction channel of the standard material.
  70741. * @param name the texture name
  70742. * @param size size of the underlying texture
  70743. * @param scene root scene
  70744. */
  70745. var RefractionTexture = /** @class */ (function (_super) {
  70746. __extends(RefractionTexture, _super);
  70747. function RefractionTexture(name, size, scene, generateMipMaps) {
  70748. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  70749. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  70750. _this.depth = 2.0;
  70751. _this.onBeforeRenderObservable.add(function () {
  70752. scene.clipPlane = _this.refractionPlane;
  70753. });
  70754. _this.onAfterRenderObservable.add(function () {
  70755. delete scene.clipPlane;
  70756. });
  70757. return _this;
  70758. }
  70759. RefractionTexture.prototype.clone = function () {
  70760. var scene = this.getScene();
  70761. if (!scene) {
  70762. return this;
  70763. }
  70764. var textureSize = this.getSize();
  70765. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  70766. // Base texture
  70767. newTexture.hasAlpha = this.hasAlpha;
  70768. newTexture.level = this.level;
  70769. // Refraction Texture
  70770. newTexture.refractionPlane = this.refractionPlane.clone();
  70771. if (this.renderList) {
  70772. newTexture.renderList = this.renderList.slice(0);
  70773. }
  70774. newTexture.depth = this.depth;
  70775. return newTexture;
  70776. };
  70777. RefractionTexture.prototype.serialize = function () {
  70778. if (!this.name) {
  70779. return null;
  70780. }
  70781. var serializationObject = _super.prototype.serialize.call(this);
  70782. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  70783. serializationObject.depth = this.depth;
  70784. return serializationObject;
  70785. };
  70786. return RefractionTexture;
  70787. }(BABYLON.RenderTargetTexture));
  70788. BABYLON.RefractionTexture = RefractionTexture;
  70789. })(BABYLON || (BABYLON = {}));
  70790. //# sourceMappingURL=babylon.refractionTexture.js.map
  70791. var BABYLON;
  70792. (function (BABYLON) {
  70793. /**
  70794. * A class extending {BABYLON.Texture} allowing drawing on a texture
  70795. * @see http://doc.babylonjs.com/how_to/dynamictexture
  70796. */
  70797. var DynamicTexture = /** @class */ (function (_super) {
  70798. __extends(DynamicTexture, _super);
  70799. /**
  70800. * Creates a {BABYLON.DynamicTexture}
  70801. * @param name defines the name of the texture
  70802. * @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
  70803. * @param scene defines the scene where you want the texture
  70804. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  70805. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  70806. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  70807. */
  70808. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  70809. if (scene === void 0) { scene = null; }
  70810. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70811. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70812. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  70813. _this.name = name;
  70814. _this._engine = _this.getScene().getEngine();
  70815. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70816. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70817. _this._generateMipMaps = generateMipMaps;
  70818. if (options.getContext) {
  70819. _this._canvas = options;
  70820. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70821. }
  70822. else {
  70823. _this._canvas = document.createElement("canvas");
  70824. if (options.width || options.width === 0) {
  70825. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70826. }
  70827. else {
  70828. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  70829. }
  70830. }
  70831. var textureSize = _this.getSize();
  70832. _this._canvas.width = textureSize.width;
  70833. _this._canvas.height = textureSize.height;
  70834. _this._context = _this._canvas.getContext("2d");
  70835. return _this;
  70836. }
  70837. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  70838. /**
  70839. * Gets the current state of canRescale
  70840. */
  70841. get: function () {
  70842. return true;
  70843. },
  70844. enumerable: true,
  70845. configurable: true
  70846. });
  70847. DynamicTexture.prototype._recreate = function (textureSize) {
  70848. this._canvas.width = textureSize.width;
  70849. this._canvas.height = textureSize.height;
  70850. this.releaseInternalTexture();
  70851. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  70852. };
  70853. /**
  70854. * Scales the texture
  70855. * @param ratio the scale factor to apply to both width and height
  70856. */
  70857. DynamicTexture.prototype.scale = function (ratio) {
  70858. var textureSize = this.getSize();
  70859. textureSize.width *= ratio;
  70860. textureSize.height *= ratio;
  70861. this._recreate(textureSize);
  70862. };
  70863. /**
  70864. * Resizes the texture
  70865. * @param width the new width
  70866. * @param height the new height
  70867. */
  70868. DynamicTexture.prototype.scaleTo = function (width, height) {
  70869. var textureSize = this.getSize();
  70870. textureSize.width = width;
  70871. textureSize.height = height;
  70872. this._recreate(textureSize);
  70873. };
  70874. /**
  70875. * Gets the context of the canvas used by the texture
  70876. * @returns the canvas context of the dynamic texture
  70877. */
  70878. DynamicTexture.prototype.getContext = function () {
  70879. return this._context;
  70880. };
  70881. /**
  70882. * Clears the texture
  70883. */
  70884. DynamicTexture.prototype.clear = function () {
  70885. var size = this.getSize();
  70886. this._context.fillRect(0, 0, size.width, size.height);
  70887. };
  70888. /**
  70889. * Updates the texture
  70890. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70891. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  70892. */
  70893. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  70894. if (premulAlpha === void 0) { premulAlpha = false; }
  70895. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  70896. };
  70897. /**
  70898. * Draws text onto the texture
  70899. * @param text defines the text to be drawn
  70900. * @param x defines the placement of the text from the left
  70901. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  70902. * @param font defines the font to be used with font-style, font-size, font-name
  70903. * @param color defines the color used for the text
  70904. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  70905. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70906. * @param update defines whether texture is immediately update (default is true)
  70907. */
  70908. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  70909. if (update === void 0) { update = true; }
  70910. var size = this.getSize();
  70911. if (clearColor) {
  70912. this._context.fillStyle = clearColor;
  70913. this._context.fillRect(0, 0, size.width, size.height);
  70914. }
  70915. this._context.font = font;
  70916. if (x === null || x === undefined) {
  70917. var textSize = this._context.measureText(text);
  70918. x = (size.width - textSize.width) / 2;
  70919. }
  70920. if (y === null || y === undefined) {
  70921. var fontSize = parseInt((font.replace(/\D/g, '')));
  70922. y = (size.height / 2) + (fontSize / 3.65);
  70923. }
  70924. this._context.fillStyle = color;
  70925. this._context.fillText(text, x, y);
  70926. if (update) {
  70927. this.update(invertY);
  70928. }
  70929. };
  70930. /**
  70931. * Clones the texture
  70932. * @returns the clone of the texture.
  70933. */
  70934. DynamicTexture.prototype.clone = function () {
  70935. var scene = this.getScene();
  70936. if (!scene) {
  70937. return this;
  70938. }
  70939. var textureSize = this.getSize();
  70940. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  70941. // Base texture
  70942. newTexture.hasAlpha = this.hasAlpha;
  70943. newTexture.level = this.level;
  70944. // Dynamic Texture
  70945. newTexture.wrapU = this.wrapU;
  70946. newTexture.wrapV = this.wrapV;
  70947. return newTexture;
  70948. };
  70949. /**
  70950. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  70951. * @returns a serialized dynamic texture object
  70952. */
  70953. DynamicTexture.prototype.serialize = function () {
  70954. var scene = this.getScene();
  70955. if (scene && !scene.isReady()) {
  70956. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  70957. }
  70958. var serializationObject = _super.prototype.serialize.call(this);
  70959. serializationObject.base64String = this._canvas.toDataURL();
  70960. serializationObject.invertY = this._invertY;
  70961. serializationObject.samplingMode = this.samplingMode;
  70962. return serializationObject;
  70963. };
  70964. /** @hidden */
  70965. DynamicTexture.prototype._rebuild = function () {
  70966. this.update();
  70967. };
  70968. return DynamicTexture;
  70969. }(BABYLON.Texture));
  70970. BABYLON.DynamicTexture = DynamicTexture;
  70971. })(BABYLON || (BABYLON = {}));
  70972. //# sourceMappingURL=babylon.dynamicTexture.js.map
  70973. var BABYLON;
  70974. (function (BABYLON) {
  70975. var VideoTexture = /** @class */ (function (_super) {
  70976. __extends(VideoTexture, _super);
  70977. /**
  70978. * Creates a video texture.
  70979. * Sample : https://doc.babylonjs.com/how_to/video_texture
  70980. * @param {string | null} name optional name, will detect from video source, if not defined
  70981. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  70982. * @param {BABYLON.Scene} scene is obviously the current scene.
  70983. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  70984. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  70985. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  70986. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  70987. */
  70988. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  70989. if (generateMipMaps === void 0) { generateMipMaps = false; }
  70990. if (invertY === void 0) { invertY = false; }
  70991. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70992. if (settings === void 0) { settings = {
  70993. autoPlay: true,
  70994. loop: true,
  70995. autoUpdateTexture: true,
  70996. }; }
  70997. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  70998. _this._onUserActionRequestedObservable = null;
  70999. _this._stillImageCaptured = false;
  71000. _this._poster = false;
  71001. _this._createInternalTexture = function () {
  71002. if (_this._texture != null) {
  71003. if (_this._poster) {
  71004. _this._texture.dispose();
  71005. _this._poster = false;
  71006. }
  71007. else {
  71008. return;
  71009. }
  71010. }
  71011. if (!_this._engine.needPOTTextures ||
  71012. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  71013. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71014. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71015. }
  71016. else {
  71017. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71018. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71019. _this._generateMipMaps = false;
  71020. }
  71021. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  71022. if (!_this.video.autoplay) {
  71023. var oldHandler_1 = _this.video.onplaying;
  71024. var error_1 = false;
  71025. _this.video.onplaying = function () {
  71026. _this.video.onplaying = oldHandler_1;
  71027. _this._texture.isReady = true;
  71028. _this._updateInternalTexture();
  71029. if (!error_1) {
  71030. _this.video.pause();
  71031. }
  71032. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71033. _this.onLoadObservable.notifyObservers(_this);
  71034. }
  71035. };
  71036. var playing = _this.video.play();
  71037. if (playing) {
  71038. playing.then(function () {
  71039. // Everything is good.
  71040. })
  71041. .catch(function () {
  71042. error_1 = true;
  71043. // On Chrome for instance, new policies might prevent playing without user interaction.
  71044. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  71045. _this._onUserActionRequestedObservable.notifyObservers(_this);
  71046. }
  71047. });
  71048. }
  71049. else {
  71050. _this.video.onplaying = oldHandler_1;
  71051. _this._texture.isReady = true;
  71052. _this._updateInternalTexture();
  71053. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71054. _this.onLoadObservable.notifyObservers(_this);
  71055. }
  71056. }
  71057. }
  71058. else {
  71059. _this._texture.isReady = true;
  71060. _this._updateInternalTexture();
  71061. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71062. _this.onLoadObservable.notifyObservers(_this);
  71063. }
  71064. }
  71065. };
  71066. _this.reset = function () {
  71067. if (_this._texture == null) {
  71068. return;
  71069. }
  71070. if (!_this._poster) {
  71071. _this._texture.dispose();
  71072. _this._texture = null;
  71073. }
  71074. };
  71075. _this._updateInternalTexture = function (e) {
  71076. if (_this._texture == null || !_this._texture.isReady) {
  71077. return;
  71078. }
  71079. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  71080. return;
  71081. }
  71082. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  71083. };
  71084. _this._engine = _this.getScene().getEngine();
  71085. _this._generateMipMaps = generateMipMaps;
  71086. _this._samplingMode = samplingMode;
  71087. _this.autoUpdateTexture = settings.autoUpdateTexture;
  71088. _this.name = name || _this._getName(src);
  71089. _this.video = _this._getVideo(src);
  71090. if (settings.poster) {
  71091. _this.video.poster = settings.poster;
  71092. }
  71093. if (settings.autoPlay !== undefined) {
  71094. _this.video.autoplay = settings.autoPlay;
  71095. }
  71096. if (settings.loop !== undefined) {
  71097. _this.video.loop = settings.loop;
  71098. }
  71099. _this.video.setAttribute("playsinline", "");
  71100. _this.video.addEventListener("canplay", _this._createInternalTexture);
  71101. _this.video.addEventListener("paused", _this._updateInternalTexture);
  71102. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  71103. _this.video.addEventListener("emptied", _this.reset);
  71104. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  71105. _this._createInternalTexture();
  71106. }
  71107. if (settings.poster) {
  71108. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  71109. _this._poster = true;
  71110. }
  71111. return _this;
  71112. }
  71113. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  71114. get: function () {
  71115. if (!this._onUserActionRequestedObservable) {
  71116. this._onUserActionRequestedObservable = new BABYLON.Observable();
  71117. }
  71118. return this._onUserActionRequestedObservable;
  71119. },
  71120. enumerable: true,
  71121. configurable: true
  71122. });
  71123. VideoTexture.prototype._getName = function (src) {
  71124. if (src instanceof HTMLVideoElement) {
  71125. return src.currentSrc;
  71126. }
  71127. if (typeof src === "object") {
  71128. return src.toString();
  71129. }
  71130. return src;
  71131. };
  71132. ;
  71133. VideoTexture.prototype._getVideo = function (src) {
  71134. if (src instanceof HTMLVideoElement) {
  71135. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  71136. return src;
  71137. }
  71138. var video = document.createElement("video");
  71139. if (typeof src === "string") {
  71140. BABYLON.Tools.SetCorsBehavior(src, video);
  71141. video.src = src;
  71142. }
  71143. else {
  71144. BABYLON.Tools.SetCorsBehavior(src[0], video);
  71145. src.forEach(function (url) {
  71146. var source = document.createElement("source");
  71147. source.src = url;
  71148. video.appendChild(source);
  71149. });
  71150. }
  71151. return video;
  71152. };
  71153. ;
  71154. /**
  71155. * @hidden Internal method to initiate `update`.
  71156. */
  71157. VideoTexture.prototype._rebuild = function () {
  71158. this.update();
  71159. };
  71160. /**
  71161. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  71162. */
  71163. VideoTexture.prototype.update = function () {
  71164. if (!this.autoUpdateTexture) {
  71165. // Expecting user to call `updateTexture` manually
  71166. return;
  71167. }
  71168. this.updateTexture(true);
  71169. };
  71170. /**
  71171. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  71172. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  71173. */
  71174. VideoTexture.prototype.updateTexture = function (isVisible) {
  71175. if (!isVisible) {
  71176. return;
  71177. }
  71178. if (this.video.paused && this._stillImageCaptured) {
  71179. return;
  71180. }
  71181. this._stillImageCaptured = true;
  71182. this._updateInternalTexture();
  71183. };
  71184. /**
  71185. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  71186. * @param url New url.
  71187. */
  71188. VideoTexture.prototype.updateURL = function (url) {
  71189. this.video.src = url;
  71190. };
  71191. VideoTexture.prototype.dispose = function () {
  71192. _super.prototype.dispose.call(this);
  71193. if (this._onUserActionRequestedObservable) {
  71194. this._onUserActionRequestedObservable.clear();
  71195. this._onUserActionRequestedObservable = null;
  71196. }
  71197. this.video.removeEventListener("canplay", this._createInternalTexture);
  71198. this.video.removeEventListener("paused", this._updateInternalTexture);
  71199. this.video.removeEventListener("seeked", this._updateInternalTexture);
  71200. this.video.removeEventListener("emptied", this.reset);
  71201. this.video.pause();
  71202. };
  71203. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  71204. var video = document.createElement("video");
  71205. video.setAttribute('autoplay', '');
  71206. video.setAttribute('muted', '');
  71207. video.setAttribute('playsinline', '');
  71208. var constraintsDeviceId;
  71209. if (constraints && constraints.deviceId) {
  71210. constraintsDeviceId = {
  71211. exact: constraints.deviceId,
  71212. };
  71213. }
  71214. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  71215. if (navigator.mediaDevices) {
  71216. navigator.mediaDevices.getUserMedia({ video: constraints })
  71217. .then(function (stream) {
  71218. if (video.mozSrcObject !== undefined) {
  71219. // hack for Firefox < 19
  71220. video.mozSrcObject = stream;
  71221. }
  71222. else {
  71223. video.srcObject = stream;
  71224. }
  71225. var onPlaying = function () {
  71226. if (onReady) {
  71227. onReady(new VideoTexture("video", video, scene, true, true));
  71228. }
  71229. video.removeEventListener("playing", onPlaying);
  71230. };
  71231. video.addEventListener("playing", onPlaying);
  71232. video.play();
  71233. })
  71234. .catch(function (err) {
  71235. BABYLON.Tools.Error(err.name);
  71236. });
  71237. }
  71238. else {
  71239. navigator.getUserMedia =
  71240. navigator.getUserMedia ||
  71241. navigator.webkitGetUserMedia ||
  71242. navigator.mozGetUserMedia ||
  71243. navigator.msGetUserMedia;
  71244. if (navigator.getUserMedia) {
  71245. navigator.getUserMedia({
  71246. video: {
  71247. deviceId: constraintsDeviceId,
  71248. width: {
  71249. min: (constraints && constraints.minWidth) || 256,
  71250. max: (constraints && constraints.maxWidth) || 640,
  71251. },
  71252. height: {
  71253. min: (constraints && constraints.minHeight) || 256,
  71254. max: (constraints && constraints.maxHeight) || 480,
  71255. },
  71256. },
  71257. }, function (stream) {
  71258. if (video.mozSrcObject !== undefined) {
  71259. // hack for Firefox < 19
  71260. video.mozSrcObject = stream;
  71261. }
  71262. else {
  71263. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  71264. }
  71265. video.play();
  71266. if (onReady) {
  71267. onReady(new VideoTexture("video", video, scene, true, true));
  71268. }
  71269. }, function (e) {
  71270. BABYLON.Tools.Error(e.name);
  71271. });
  71272. }
  71273. }
  71274. };
  71275. return VideoTexture;
  71276. }(BABYLON.Texture));
  71277. BABYLON.VideoTexture = VideoTexture;
  71278. })(BABYLON || (BABYLON = {}));
  71279. //# sourceMappingURL=babylon.videoTexture.js.map
  71280. var BABYLON;
  71281. (function (BABYLON) {
  71282. var RawTexture = /** @class */ (function (_super) {
  71283. __extends(RawTexture, _super);
  71284. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  71285. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71286. if (invertY === void 0) { invertY = false; }
  71287. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71288. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71289. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71290. _this.format = format;
  71291. _this._engine = scene.getEngine();
  71292. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  71293. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71294. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71295. return _this;
  71296. }
  71297. RawTexture.prototype.update = function (data) {
  71298. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71299. };
  71300. // Statics
  71301. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71302. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71303. if (invertY === void 0) { invertY = false; }
  71304. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71305. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  71306. };
  71307. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71308. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71309. if (invertY === void 0) { invertY = false; }
  71310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71311. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71312. };
  71313. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71314. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71315. if (invertY === void 0) { invertY = false; }
  71316. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71317. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71318. };
  71319. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71320. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71321. if (invertY === void 0) { invertY = false; }
  71322. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71323. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71324. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  71325. };
  71326. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71327. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71328. if (invertY === void 0) { invertY = false; }
  71329. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71330. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71331. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  71332. };
  71333. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71334. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71335. if (invertY === void 0) { invertY = false; }
  71336. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71337. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71338. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  71339. };
  71340. return RawTexture;
  71341. }(BABYLON.Texture));
  71342. BABYLON.RawTexture = RawTexture;
  71343. })(BABYLON || (BABYLON = {}));
  71344. //# sourceMappingURL=babylon.rawTexture.js.map
  71345. var BABYLON;
  71346. (function (BABYLON) {
  71347. /**
  71348. * Class used to store 3D textures containing user data
  71349. */
  71350. var RawTexture3D = /** @class */ (function (_super) {
  71351. __extends(RawTexture3D, _super);
  71352. /**
  71353. * Create a new RawTexture3D
  71354. * @param data defines the data of the texture
  71355. * @param width defines the width of the texture
  71356. * @param height defines the height of the texture
  71357. * @param depth defines the depth of the texture
  71358. * @param format defines the texture format to use
  71359. * @param scene defines the hosting scene
  71360. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  71361. * @param invertY defines if texture must be stored with Y axis inverted
  71362. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  71363. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  71364. */
  71365. function RawTexture3D(data, width, height, depth,
  71366. /** Gets or sets the texture format to use */
  71367. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  71368. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71369. if (invertY === void 0) { invertY = false; }
  71370. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71371. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71372. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71373. _this.format = format;
  71374. _this._engine = scene.getEngine();
  71375. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  71376. _this.is3D = true;
  71377. return _this;
  71378. }
  71379. /**
  71380. * Update the texture with new data
  71381. * @param data defines the data to store in the texture
  71382. */
  71383. RawTexture3D.prototype.update = function (data) {
  71384. if (!this._texture) {
  71385. return;
  71386. }
  71387. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71388. };
  71389. return RawTexture3D;
  71390. }(BABYLON.Texture));
  71391. BABYLON.RawTexture3D = RawTexture3D;
  71392. })(BABYLON || (BABYLON = {}));
  71393. //# sourceMappingURL=babylon.rawTexture3D.js.map
  71394. var BABYLON;
  71395. (function (BABYLON) {
  71396. /**
  71397. * PostProcessManager is used to manage one or more post processes or post process pipelines
  71398. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71399. */
  71400. var PostProcessManager = /** @class */ (function () {
  71401. /**
  71402. * Creates a new instance PostProcess
  71403. * @param scene The scene that the post process is associated with.
  71404. */
  71405. function PostProcessManager(scene) {
  71406. this._vertexBuffers = {};
  71407. this._scene = scene;
  71408. }
  71409. PostProcessManager.prototype._prepareBuffers = function () {
  71410. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  71411. return;
  71412. }
  71413. // VBO
  71414. var vertices = [];
  71415. vertices.push(1, 1);
  71416. vertices.push(-1, 1);
  71417. vertices.push(-1, -1);
  71418. vertices.push(1, -1);
  71419. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71420. this._buildIndexBuffer();
  71421. };
  71422. PostProcessManager.prototype._buildIndexBuffer = function () {
  71423. // Indices
  71424. var indices = [];
  71425. indices.push(0);
  71426. indices.push(1);
  71427. indices.push(2);
  71428. indices.push(0);
  71429. indices.push(2);
  71430. indices.push(3);
  71431. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  71432. };
  71433. /**
  71434. * Rebuilds the vertex buffers of the manager.
  71435. * @hidden
  71436. */
  71437. PostProcessManager.prototype._rebuild = function () {
  71438. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71439. if (!vb) {
  71440. return;
  71441. }
  71442. vb._rebuild();
  71443. this._buildIndexBuffer();
  71444. };
  71445. // Methods
  71446. /**
  71447. * Prepares a frame to be run through a post process.
  71448. * @param sourceTexture The input texture to the post procesess. (default: null)
  71449. * @param postProcesses An array of post processes to be run. (default: null)
  71450. * @returns True if the post processes were able to be run.
  71451. * @hidden
  71452. */
  71453. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  71454. if (sourceTexture === void 0) { sourceTexture = null; }
  71455. if (postProcesses === void 0) { postProcesses = null; }
  71456. var camera = this._scene.activeCamera;
  71457. if (!camera) {
  71458. return false;
  71459. }
  71460. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71461. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71462. return false;
  71463. }
  71464. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  71465. return true;
  71466. };
  71467. /**
  71468. * Manually render a set of post processes to a texture.
  71469. * @param postProcesses An array of post processes to be run.
  71470. * @param targetTexture The target texture to render to.
  71471. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  71472. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  71473. * @param lodLevel defines which lod of the texture to render to
  71474. */
  71475. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  71476. if (targetTexture === void 0) { targetTexture = null; }
  71477. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71478. if (faceIndex === void 0) { faceIndex = 0; }
  71479. if (lodLevel === void 0) { lodLevel = 0; }
  71480. var engine = this._scene.getEngine();
  71481. for (var index = 0; index < postProcesses.length; index++) {
  71482. if (index < postProcesses.length - 1) {
  71483. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  71484. }
  71485. else {
  71486. if (targetTexture) {
  71487. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  71488. }
  71489. else {
  71490. engine.restoreDefaultFramebuffer();
  71491. }
  71492. }
  71493. var pp = postProcesses[index];
  71494. var effect = pp.apply();
  71495. if (effect) {
  71496. pp.onBeforeRenderObservable.notifyObservers(effect);
  71497. // VBOs
  71498. this._prepareBuffers();
  71499. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71500. // Draw order
  71501. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71502. pp.onAfterRenderObservable.notifyObservers(effect);
  71503. }
  71504. }
  71505. // Restore depth buffer
  71506. engine.setDepthBuffer(true);
  71507. engine.setDepthWrite(true);
  71508. };
  71509. /**
  71510. * Finalize the result of the output of the postprocesses.
  71511. * @param doNotPresent If true the result will not be displayed to the screen.
  71512. * @param targetTexture The target texture to render to.
  71513. * @param faceIndex The index of the face to bind the target texture to.
  71514. * @param postProcesses The array of post processes to render.
  71515. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  71516. * @hidden
  71517. */
  71518. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  71519. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71520. var camera = this._scene.activeCamera;
  71521. if (!camera) {
  71522. return;
  71523. }
  71524. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71525. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71526. return;
  71527. }
  71528. var engine = this._scene.getEngine();
  71529. for (var index = 0, len = postProcesses.length; index < len; index++) {
  71530. var pp = postProcesses[index];
  71531. if (index < len - 1) {
  71532. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  71533. }
  71534. else {
  71535. if (targetTexture) {
  71536. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  71537. pp._outputTexture = targetTexture;
  71538. }
  71539. else {
  71540. engine.restoreDefaultFramebuffer();
  71541. pp._outputTexture = null;
  71542. }
  71543. }
  71544. if (doNotPresent) {
  71545. break;
  71546. }
  71547. var effect = pp.apply();
  71548. if (effect) {
  71549. pp.onBeforeRenderObservable.notifyObservers(effect);
  71550. // VBOs
  71551. this._prepareBuffers();
  71552. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71553. // Draw order
  71554. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71555. pp.onAfterRenderObservable.notifyObservers(effect);
  71556. }
  71557. }
  71558. // Restore states
  71559. engine.setDepthBuffer(true);
  71560. engine.setDepthWrite(true);
  71561. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71562. };
  71563. /**
  71564. * Disposes of the post process manager.
  71565. */
  71566. PostProcessManager.prototype.dispose = function () {
  71567. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71568. if (buffer) {
  71569. buffer.dispose();
  71570. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71571. }
  71572. if (this._indexBuffer) {
  71573. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71574. this._indexBuffer = null;
  71575. }
  71576. };
  71577. return PostProcessManager;
  71578. }());
  71579. BABYLON.PostProcessManager = PostProcessManager;
  71580. })(BABYLON || (BABYLON = {}));
  71581. //# sourceMappingURL=babylon.postProcessManager.js.map
  71582. var BABYLON;
  71583. (function (BABYLON) {
  71584. /**
  71585. * PostProcess can be used to apply a shader to a texture after it has been rendered
  71586. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71587. */
  71588. var PostProcess = /** @class */ (function () {
  71589. /**
  71590. * Creates a new instance PostProcess
  71591. * @param name The name of the PostProcess.
  71592. * @param fragmentUrl The url of the fragment shader to be used.
  71593. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  71594. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  71595. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  71596. * @param camera The camera to apply the render pass to.
  71597. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71598. * @param engine The engine which the post process will be applied. (default: current engine)
  71599. * @param reusable If the post process can be reused on the same frame. (default: false)
  71600. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  71601. * @param textureType Type of textures used when performing the post process. (default: 0)
  71602. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  71603. * @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
  71604. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  71605. */
  71606. function PostProcess(
  71607. /** Name of the PostProcess. */
  71608. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  71609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  71610. if (defines === void 0) { defines = null; }
  71611. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71612. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  71613. if (blockCompilation === void 0) { blockCompilation = false; }
  71614. this.name = name;
  71615. /**
  71616. * Width of the texture to apply the post process on
  71617. */
  71618. this.width = -1;
  71619. /**
  71620. * Height of the texture to apply the post process on
  71621. */
  71622. this.height = -1;
  71623. /**
  71624. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  71625. * @hidden
  71626. */
  71627. this._outputTexture = null;
  71628. /**
  71629. * If the buffer needs to be cleared before applying the post process. (default: true)
  71630. * Should be set to false if shader will overwrite all previous pixels.
  71631. */
  71632. this.autoClear = true;
  71633. /**
  71634. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  71635. */
  71636. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  71637. /**
  71638. * Animations to be used for the post processing
  71639. */
  71640. this.animations = new Array();
  71641. /**
  71642. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  71643. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  71644. */
  71645. this.enablePixelPerfectMode = false;
  71646. /**
  71647. * Force the postprocess to be applied without taking in account viewport
  71648. */
  71649. this.forceFullscreenViewport = true;
  71650. /**
  71651. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  71652. *
  71653. * | Value | Type | Description |
  71654. * | ----- | ----------------------------------- | ----------- |
  71655. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  71656. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  71657. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  71658. *
  71659. */
  71660. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  71661. /**
  71662. * Force textures to be a power of two (default: false)
  71663. */
  71664. this.alwaysForcePOT = false;
  71665. this._samples = 1;
  71666. /**
  71667. * Modify the scale of the post process to be the same as the viewport (default: false)
  71668. */
  71669. this.adaptScaleToCurrentViewport = false;
  71670. this._reusable = false;
  71671. /**
  71672. * Smart array of input and output textures for the post process.
  71673. * @hidden
  71674. */
  71675. this._textures = new BABYLON.SmartArray(2);
  71676. /**
  71677. * The index in _textures that corresponds to the output texture.
  71678. * @hidden
  71679. */
  71680. this._currentRenderTextureInd = 0;
  71681. this._scaleRatio = new BABYLON.Vector2(1, 1);
  71682. this._texelSize = BABYLON.Vector2.Zero();
  71683. // Events
  71684. /**
  71685. * An event triggered when the postprocess is activated.
  71686. */
  71687. this.onActivateObservable = new BABYLON.Observable();
  71688. /**
  71689. * An event triggered when the postprocess changes its size.
  71690. */
  71691. this.onSizeChangedObservable = new BABYLON.Observable();
  71692. /**
  71693. * An event triggered when the postprocess applies its effect.
  71694. */
  71695. this.onApplyObservable = new BABYLON.Observable();
  71696. /**
  71697. * An event triggered before rendering the postprocess
  71698. */
  71699. this.onBeforeRenderObservable = new BABYLON.Observable();
  71700. /**
  71701. * An event triggered after rendering the postprocess
  71702. */
  71703. this.onAfterRenderObservable = new BABYLON.Observable();
  71704. if (camera != null) {
  71705. this._camera = camera;
  71706. this._scene = camera.getScene();
  71707. camera.attachPostProcess(this);
  71708. this._engine = this._scene.getEngine();
  71709. this._scene.postProcesses.push(this);
  71710. }
  71711. else if (engine) {
  71712. this._engine = engine;
  71713. this._engine.postProcesses.push(this);
  71714. }
  71715. this._options = options;
  71716. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  71717. this._reusable = reusable || false;
  71718. this._textureType = textureType;
  71719. this._samplers = samplers || [];
  71720. this._samplers.push("textureSampler");
  71721. this._fragmentUrl = fragmentUrl;
  71722. this._vertexUrl = vertexUrl;
  71723. this._parameters = parameters || [];
  71724. this._parameters.push("scale");
  71725. this._indexParameters = indexParameters;
  71726. if (!blockCompilation) {
  71727. this.updateEffect(defines);
  71728. }
  71729. }
  71730. Object.defineProperty(PostProcess.prototype, "samples", {
  71731. /**
  71732. * Number of sample textures (default: 1)
  71733. */
  71734. get: function () {
  71735. return this._samples;
  71736. },
  71737. set: function (n) {
  71738. var _this = this;
  71739. this._samples = n;
  71740. this._textures.forEach(function (texture) {
  71741. if (texture.samples !== _this._samples) {
  71742. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  71743. }
  71744. });
  71745. },
  71746. enumerable: true,
  71747. configurable: true
  71748. });
  71749. Object.defineProperty(PostProcess.prototype, "onActivate", {
  71750. /**
  71751. * A function that is added to the onActivateObservable
  71752. */
  71753. set: function (callback) {
  71754. if (this._onActivateObserver) {
  71755. this.onActivateObservable.remove(this._onActivateObserver);
  71756. }
  71757. if (callback) {
  71758. this._onActivateObserver = this.onActivateObservable.add(callback);
  71759. }
  71760. },
  71761. enumerable: true,
  71762. configurable: true
  71763. });
  71764. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  71765. /**
  71766. * A function that is added to the onSizeChangedObservable
  71767. */
  71768. set: function (callback) {
  71769. if (this._onSizeChangedObserver) {
  71770. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  71771. }
  71772. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  71773. },
  71774. enumerable: true,
  71775. configurable: true
  71776. });
  71777. Object.defineProperty(PostProcess.prototype, "onApply", {
  71778. /**
  71779. * A function that is added to the onApplyObservable
  71780. */
  71781. set: function (callback) {
  71782. if (this._onApplyObserver) {
  71783. this.onApplyObservable.remove(this._onApplyObserver);
  71784. }
  71785. this._onApplyObserver = this.onApplyObservable.add(callback);
  71786. },
  71787. enumerable: true,
  71788. configurable: true
  71789. });
  71790. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  71791. /**
  71792. * A function that is added to the onBeforeRenderObservable
  71793. */
  71794. set: function (callback) {
  71795. if (this._onBeforeRenderObserver) {
  71796. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71797. }
  71798. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71799. },
  71800. enumerable: true,
  71801. configurable: true
  71802. });
  71803. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  71804. /**
  71805. * A function that is added to the onAfterRenderObservable
  71806. */
  71807. set: function (callback) {
  71808. if (this._onAfterRenderObserver) {
  71809. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71810. }
  71811. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71812. },
  71813. enumerable: true,
  71814. configurable: true
  71815. });
  71816. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  71817. /**
  71818. * 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
  71819. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  71820. */
  71821. get: function () {
  71822. return this._textures.data[this._currentRenderTextureInd];
  71823. },
  71824. set: function (value) {
  71825. this._forcedOutputTexture = value;
  71826. },
  71827. enumerable: true,
  71828. configurable: true
  71829. });
  71830. /**
  71831. * Gets the camera which post process is applied to.
  71832. * @returns The camera the post process is applied to.
  71833. */
  71834. PostProcess.prototype.getCamera = function () {
  71835. return this._camera;
  71836. };
  71837. Object.defineProperty(PostProcess.prototype, "texelSize", {
  71838. /**
  71839. * Gets the texel size of the postprocess.
  71840. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  71841. */
  71842. get: function () {
  71843. if (this._shareOutputWithPostProcess) {
  71844. return this._shareOutputWithPostProcess.texelSize;
  71845. }
  71846. if (this._forcedOutputTexture) {
  71847. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  71848. }
  71849. return this._texelSize;
  71850. },
  71851. enumerable: true,
  71852. configurable: true
  71853. });
  71854. /**
  71855. * Gets the engine which this post process belongs to.
  71856. * @returns The engine the post process was enabled with.
  71857. */
  71858. PostProcess.prototype.getEngine = function () {
  71859. return this._engine;
  71860. };
  71861. /**
  71862. * The effect that is created when initializing the post process.
  71863. * @returns The created effect corrisponding the the postprocess.
  71864. */
  71865. PostProcess.prototype.getEffect = function () {
  71866. return this._effect;
  71867. };
  71868. /**
  71869. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  71870. * @param postProcess The post process to share the output with.
  71871. * @returns This post process.
  71872. */
  71873. PostProcess.prototype.shareOutputWith = function (postProcess) {
  71874. this._disposeTextures();
  71875. this._shareOutputWithPostProcess = postProcess;
  71876. return this;
  71877. };
  71878. /**
  71879. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  71880. * This should be called if the post process that shares output with this post process is disabled/disposed.
  71881. */
  71882. PostProcess.prototype.useOwnOutput = function () {
  71883. if (this._textures.length == 0) {
  71884. this._textures = new BABYLON.SmartArray(2);
  71885. }
  71886. this._shareOutputWithPostProcess = null;
  71887. };
  71888. /**
  71889. * Updates the effect with the current post process compile time values and recompiles the shader.
  71890. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  71891. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  71892. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  71893. * @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
  71894. * @param onCompiled Called when the shader has been compiled.
  71895. * @param onError Called if there is an error when compiling a shader.
  71896. */
  71897. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  71898. if (defines === void 0) { defines = null; }
  71899. if (uniforms === void 0) { uniforms = null; }
  71900. if (samplers === void 0) { samplers = null; }
  71901. 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);
  71902. };
  71903. /**
  71904. * The post process is reusable if it can be used multiple times within one frame.
  71905. * @returns If the post process is reusable
  71906. */
  71907. PostProcess.prototype.isReusable = function () {
  71908. return this._reusable;
  71909. };
  71910. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  71911. PostProcess.prototype.markTextureDirty = function () {
  71912. this.width = -1;
  71913. };
  71914. /**
  71915. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  71916. * 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.
  71917. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  71918. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  71919. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  71920. * @returns The target texture that was bound to be written to.
  71921. */
  71922. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  71923. var _this = this;
  71924. if (sourceTexture === void 0) { sourceTexture = null; }
  71925. camera = camera || this._camera;
  71926. var scene = camera.getScene();
  71927. var engine = scene.getEngine();
  71928. var maxSize = engine.getCaps().maxTextureSize;
  71929. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  71930. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  71931. // 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
  71932. var webVRCamera = camera.parent;
  71933. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  71934. requiredWidth /= 2;
  71935. }
  71936. var desiredWidth = (this._options.width || requiredWidth);
  71937. var desiredHeight = this._options.height || requiredHeight;
  71938. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  71939. if (this.adaptScaleToCurrentViewport) {
  71940. var currentViewport = engine.currentViewport;
  71941. if (currentViewport) {
  71942. desiredWidth *= currentViewport.width;
  71943. desiredHeight *= currentViewport.height;
  71944. }
  71945. }
  71946. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  71947. if (!this._options.width) {
  71948. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  71949. }
  71950. if (!this._options.height) {
  71951. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  71952. }
  71953. }
  71954. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  71955. if (this._textures.length > 0) {
  71956. for (var i = 0; i < this._textures.length; i++) {
  71957. this._engine._releaseTexture(this._textures.data[i]);
  71958. }
  71959. this._textures.reset();
  71960. }
  71961. this.width = desiredWidth;
  71962. this.height = desiredHeight;
  71963. var textureSize = { width: this.width, height: this.height };
  71964. var textureOptions = {
  71965. generateMipMaps: false,
  71966. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  71967. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  71968. samplingMode: this.renderTargetSamplingMode,
  71969. type: this._textureType
  71970. };
  71971. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71972. if (this._reusable) {
  71973. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71974. }
  71975. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  71976. this.onSizeChangedObservable.notifyObservers(this);
  71977. }
  71978. this._textures.forEach(function (texture) {
  71979. if (texture.samples !== _this.samples) {
  71980. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  71981. }
  71982. });
  71983. }
  71984. var target;
  71985. if (this._shareOutputWithPostProcess) {
  71986. target = this._shareOutputWithPostProcess.inputTexture;
  71987. }
  71988. else if (this._forcedOutputTexture) {
  71989. target = this._forcedOutputTexture;
  71990. this.width = this._forcedOutputTexture.width;
  71991. this.height = this._forcedOutputTexture.height;
  71992. }
  71993. else {
  71994. target = this.inputTexture;
  71995. }
  71996. // Bind the input of this post process to be used as the output of the previous post process.
  71997. if (this.enablePixelPerfectMode) {
  71998. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  71999. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  72000. }
  72001. else {
  72002. this._scaleRatio.copyFromFloats(1, 1);
  72003. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  72004. }
  72005. this.onActivateObservable.notifyObservers(camera);
  72006. // Clear
  72007. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  72008. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  72009. }
  72010. if (this._reusable) {
  72011. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  72012. }
  72013. return target;
  72014. };
  72015. Object.defineProperty(PostProcess.prototype, "isSupported", {
  72016. /**
  72017. * If the post process is supported.
  72018. */
  72019. get: function () {
  72020. return this._effect.isSupported;
  72021. },
  72022. enumerable: true,
  72023. configurable: true
  72024. });
  72025. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  72026. /**
  72027. * The aspect ratio of the output texture.
  72028. */
  72029. get: function () {
  72030. if (this._shareOutputWithPostProcess) {
  72031. return this._shareOutputWithPostProcess.aspectRatio;
  72032. }
  72033. if (this._forcedOutputTexture) {
  72034. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  72035. }
  72036. return this.width / this.height;
  72037. },
  72038. enumerable: true,
  72039. configurable: true
  72040. });
  72041. /**
  72042. * Get a value indicating if the post-process is ready to be used
  72043. * @returns true if the post-process is ready (shader is compiled)
  72044. */
  72045. PostProcess.prototype.isReady = function () {
  72046. return this._effect && this._effect.isReady();
  72047. };
  72048. /**
  72049. * Binds all textures and uniforms to the shader, this will be run on every pass.
  72050. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  72051. */
  72052. PostProcess.prototype.apply = function () {
  72053. // Check
  72054. if (!this._effect || !this._effect.isReady())
  72055. return null;
  72056. // States
  72057. this._engine.enableEffect(this._effect);
  72058. this._engine.setState(false);
  72059. this._engine.setDepthBuffer(false);
  72060. this._engine.setDepthWrite(false);
  72061. // Alpha
  72062. this._engine.setAlphaMode(this.alphaMode);
  72063. if (this.alphaConstants) {
  72064. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  72065. }
  72066. // Bind the output texture of the preivous post process as the input to this post process.
  72067. var source;
  72068. if (this._shareOutputWithPostProcess) {
  72069. source = this._shareOutputWithPostProcess.inputTexture;
  72070. }
  72071. else if (this._forcedOutputTexture) {
  72072. source = this._forcedOutputTexture;
  72073. }
  72074. else {
  72075. source = this.inputTexture;
  72076. }
  72077. this._effect._bindTexture("textureSampler", source);
  72078. // Parameters
  72079. this._effect.setVector2("scale", this._scaleRatio);
  72080. this.onApplyObservable.notifyObservers(this._effect);
  72081. return this._effect;
  72082. };
  72083. PostProcess.prototype._disposeTextures = function () {
  72084. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  72085. return;
  72086. }
  72087. if (this._textures.length > 0) {
  72088. for (var i = 0; i < this._textures.length; i++) {
  72089. this._engine._releaseTexture(this._textures.data[i]);
  72090. }
  72091. }
  72092. this._textures.dispose();
  72093. };
  72094. /**
  72095. * Disposes the post process.
  72096. * @param camera The camera to dispose the post process on.
  72097. */
  72098. PostProcess.prototype.dispose = function (camera) {
  72099. camera = camera || this._camera;
  72100. this._disposeTextures();
  72101. if (this._scene) {
  72102. var index_1 = this._scene.postProcesses.indexOf(this);
  72103. if (index_1 !== -1) {
  72104. this._scene.postProcesses.splice(index_1, 1);
  72105. }
  72106. }
  72107. else {
  72108. var index_2 = this._engine.postProcesses.indexOf(this);
  72109. if (index_2 !== -1) {
  72110. this._engine.postProcesses.splice(index_2, 1);
  72111. }
  72112. }
  72113. if (!camera) {
  72114. return;
  72115. }
  72116. camera.detachPostProcess(this);
  72117. var index = camera._postProcesses.indexOf(this);
  72118. if (index === 0 && camera._postProcesses.length > 0) {
  72119. var firstPostProcess = this._camera._getFirstPostProcess();
  72120. if (firstPostProcess) {
  72121. firstPostProcess.markTextureDirty();
  72122. }
  72123. }
  72124. this.onActivateObservable.clear();
  72125. this.onAfterRenderObservable.clear();
  72126. this.onApplyObservable.clear();
  72127. this.onBeforeRenderObservable.clear();
  72128. this.onSizeChangedObservable.clear();
  72129. };
  72130. return PostProcess;
  72131. }());
  72132. BABYLON.PostProcess = PostProcess;
  72133. })(BABYLON || (BABYLON = {}));
  72134. //# sourceMappingURL=babylon.postProcess.js.map
  72135. var BABYLON;
  72136. (function (BABYLON) {
  72137. var PassPostProcess = /** @class */ (function (_super) {
  72138. __extends(PassPostProcess, _super);
  72139. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72140. if (camera === void 0) { camera = null; }
  72141. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72142. if (blockCompilation === void 0) { blockCompilation = false; }
  72143. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  72144. }
  72145. return PassPostProcess;
  72146. }(BABYLON.PostProcess));
  72147. BABYLON.PassPostProcess = PassPostProcess;
  72148. })(BABYLON || (BABYLON = {}));
  72149. //# sourceMappingURL=babylon.passPostProcess.js.map
  72150. var __assign = (this && this.__assign) || function () {
  72151. __assign = Object.assign || function(t) {
  72152. for (var s, i = 1, n = arguments.length; i < n; i++) {
  72153. s = arguments[i];
  72154. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  72155. t[p] = s[p];
  72156. }
  72157. return t;
  72158. };
  72159. return __assign.apply(this, arguments);
  72160. };
  72161. var BABYLON;
  72162. (function (BABYLON) {
  72163. /**
  72164. * Default implementation IShadowGenerator.
  72165. * This is the main object responsible of generating shadows in the framework.
  72166. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  72167. */
  72168. var ShadowGenerator = /** @class */ (function () {
  72169. /**
  72170. * Creates a ShadowGenerator object.
  72171. * A ShadowGenerator is the required tool to use the shadows.
  72172. * Each light casting shadows needs to use its own ShadowGenerator.
  72173. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  72174. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  72175. * @param light The light object generating the shadows.
  72176. * @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.
  72177. */
  72178. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  72179. this._bias = 0.00005;
  72180. this._normalBias = 0;
  72181. this._blurBoxOffset = 1;
  72182. this._blurScale = 2;
  72183. this._blurKernel = 1;
  72184. this._useKernelBlur = false;
  72185. this._filter = ShadowGenerator.FILTER_NONE;
  72186. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  72187. this._contactHardeningLightSizeUVRatio = 0.1;
  72188. this._darkness = 0;
  72189. this._transparencyShadow = false;
  72190. /**
  72191. * Controls the extent to which the shadows fade out at the edge of the frustum
  72192. * Used only by directionals and spots
  72193. */
  72194. this.frustumEdgeFalloff = 0;
  72195. /**
  72196. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  72197. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  72198. * It might on the other hand introduce peter panning.
  72199. */
  72200. this.forceBackFacesOnly = false;
  72201. this._lightDirection = BABYLON.Vector3.Zero();
  72202. this._viewMatrix = BABYLON.Matrix.Zero();
  72203. this._projectionMatrix = BABYLON.Matrix.Zero();
  72204. this._transformMatrix = BABYLON.Matrix.Zero();
  72205. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  72206. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  72207. this._currentFaceIndex = 0;
  72208. this._currentFaceIndexCache = 0;
  72209. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  72210. this._mapSize = mapSize;
  72211. this._light = light;
  72212. this._scene = light.getScene();
  72213. light._shadowGenerator = this;
  72214. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  72215. if (!component) {
  72216. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  72217. this._scene._addComponent(component);
  72218. }
  72219. // Texture type fallback from float to int if not supported.
  72220. var caps = this._scene.getEngine().getCaps();
  72221. if (!useFullFloatFirst) {
  72222. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  72223. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72224. }
  72225. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  72226. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72227. }
  72228. else {
  72229. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72230. }
  72231. }
  72232. else {
  72233. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  72234. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72235. }
  72236. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  72237. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72238. }
  72239. else {
  72240. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72241. }
  72242. }
  72243. this._initializeGenerator();
  72244. this._applyFilterValues();
  72245. }
  72246. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  72247. /**
  72248. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  72249. */
  72250. get: function () {
  72251. return this._bias;
  72252. },
  72253. /**
  72254. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  72255. */
  72256. set: function (bias) {
  72257. this._bias = bias;
  72258. },
  72259. enumerable: true,
  72260. configurable: true
  72261. });
  72262. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  72263. /**
  72264. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  72265. */
  72266. get: function () {
  72267. return this._normalBias;
  72268. },
  72269. /**
  72270. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  72271. */
  72272. set: function (normalBias) {
  72273. this._normalBias = normalBias;
  72274. },
  72275. enumerable: true,
  72276. configurable: true
  72277. });
  72278. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  72279. /**
  72280. * Gets the blur box offset: offset applied during the blur pass.
  72281. * Only usefull if useKernelBlur = false
  72282. */
  72283. get: function () {
  72284. return this._blurBoxOffset;
  72285. },
  72286. /**
  72287. * Sets the blur box offset: offset applied during the blur pass.
  72288. * Only usefull if useKernelBlur = false
  72289. */
  72290. set: function (value) {
  72291. if (this._blurBoxOffset === value) {
  72292. return;
  72293. }
  72294. this._blurBoxOffset = value;
  72295. this._disposeBlurPostProcesses();
  72296. },
  72297. enumerable: true,
  72298. configurable: true
  72299. });
  72300. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  72301. /**
  72302. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  72303. * 2 means half of the size.
  72304. */
  72305. get: function () {
  72306. return this._blurScale;
  72307. },
  72308. /**
  72309. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  72310. * 2 means half of the size.
  72311. */
  72312. set: function (value) {
  72313. if (this._blurScale === value) {
  72314. return;
  72315. }
  72316. this._blurScale = value;
  72317. this._disposeBlurPostProcesses();
  72318. },
  72319. enumerable: true,
  72320. configurable: true
  72321. });
  72322. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  72323. /**
  72324. * Gets the blur kernel: kernel size of the blur pass.
  72325. * Only usefull if useKernelBlur = true
  72326. */
  72327. get: function () {
  72328. return this._blurKernel;
  72329. },
  72330. /**
  72331. * Sets the blur kernel: kernel size of the blur pass.
  72332. * Only usefull if useKernelBlur = true
  72333. */
  72334. set: function (value) {
  72335. if (this._blurKernel === value) {
  72336. return;
  72337. }
  72338. this._blurKernel = value;
  72339. this._disposeBlurPostProcesses();
  72340. },
  72341. enumerable: true,
  72342. configurable: true
  72343. });
  72344. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  72345. /**
  72346. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  72347. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72348. */
  72349. get: function () {
  72350. return this._useKernelBlur;
  72351. },
  72352. /**
  72353. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  72354. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72355. */
  72356. set: function (value) {
  72357. if (this._useKernelBlur === value) {
  72358. return;
  72359. }
  72360. this._useKernelBlur = value;
  72361. this._disposeBlurPostProcesses();
  72362. },
  72363. enumerable: true,
  72364. configurable: true
  72365. });
  72366. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  72367. /**
  72368. * Gets the depth scale used in ESM mode.
  72369. */
  72370. get: function () {
  72371. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  72372. },
  72373. /**
  72374. * Sets the depth scale used in ESM mode.
  72375. * This can override the scale stored on the light.
  72376. */
  72377. set: function (value) {
  72378. this._depthScale = value;
  72379. },
  72380. enumerable: true,
  72381. configurable: true
  72382. });
  72383. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  72384. /**
  72385. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  72386. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72387. */
  72388. get: function () {
  72389. return this._filter;
  72390. },
  72391. /**
  72392. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  72393. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72394. */
  72395. set: function (value) {
  72396. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  72397. if (this._light.needCube()) {
  72398. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72399. this.useExponentialShadowMap = true;
  72400. return;
  72401. }
  72402. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72403. this.useCloseExponentialShadowMap = true;
  72404. return;
  72405. }
  72406. // PCF on cubemap would also be expensive
  72407. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72408. this.usePoissonSampling = true;
  72409. return;
  72410. }
  72411. }
  72412. // Weblg1 fallback for PCF.
  72413. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72414. if (this._scene.getEngine().webGLVersion === 1) {
  72415. this.usePoissonSampling = true;
  72416. return;
  72417. }
  72418. }
  72419. if (this._filter === value) {
  72420. return;
  72421. }
  72422. this._filter = value;
  72423. this._disposeBlurPostProcesses();
  72424. this._applyFilterValues();
  72425. this._light._markMeshesAsLightDirty();
  72426. },
  72427. enumerable: true,
  72428. configurable: true
  72429. });
  72430. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  72431. /**
  72432. * Gets if the current filter is set to Poisson Sampling.
  72433. */
  72434. get: function () {
  72435. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  72436. },
  72437. /**
  72438. * Sets the current filter to Poisson Sampling.
  72439. */
  72440. set: function (value) {
  72441. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  72442. return;
  72443. }
  72444. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  72445. },
  72446. enumerable: true,
  72447. configurable: true
  72448. });
  72449. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  72450. /**
  72451. * Gets if the current filter is set to VSM.
  72452. * DEPRECATED. Should use useExponentialShadowMap instead.
  72453. */
  72454. get: function () {
  72455. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72456. return this.useExponentialShadowMap;
  72457. },
  72458. /**
  72459. * Sets the current filter is to VSM.
  72460. * DEPRECATED. Should use useExponentialShadowMap instead.
  72461. */
  72462. set: function (value) {
  72463. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72464. this.useExponentialShadowMap = value;
  72465. },
  72466. enumerable: true,
  72467. configurable: true
  72468. });
  72469. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  72470. /**
  72471. * Gets if the current filter is set to blurred VSM.
  72472. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72473. */
  72474. get: function () {
  72475. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72476. return this.useBlurExponentialShadowMap;
  72477. },
  72478. /**
  72479. * Sets the current filter is to blurred VSM.
  72480. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72481. */
  72482. set: function (value) {
  72483. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72484. this.useBlurExponentialShadowMap = value;
  72485. },
  72486. enumerable: true,
  72487. configurable: true
  72488. });
  72489. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  72490. /**
  72491. * Gets if the current filter is set to ESM.
  72492. */
  72493. get: function () {
  72494. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  72495. },
  72496. /**
  72497. * Sets the current filter is to ESM.
  72498. */
  72499. set: function (value) {
  72500. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  72501. return;
  72502. }
  72503. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72504. },
  72505. enumerable: true,
  72506. configurable: true
  72507. });
  72508. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  72509. /**
  72510. * Gets if the current filter is set to filtered ESM.
  72511. */
  72512. get: function () {
  72513. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  72514. },
  72515. /**
  72516. * Gets if the current filter is set to filtered ESM.
  72517. */
  72518. set: function (value) {
  72519. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72520. return;
  72521. }
  72522. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72523. },
  72524. enumerable: true,
  72525. configurable: true
  72526. });
  72527. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  72528. /**
  72529. * Gets if the current filter is set to "close ESM" (using the inverse of the
  72530. * exponential to prevent steep falloff artifacts).
  72531. */
  72532. get: function () {
  72533. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  72534. },
  72535. /**
  72536. * Sets the current filter to "close ESM" (using the inverse of the
  72537. * exponential to prevent steep falloff artifacts).
  72538. */
  72539. set: function (value) {
  72540. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  72541. return;
  72542. }
  72543. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72544. },
  72545. enumerable: true,
  72546. configurable: true
  72547. });
  72548. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  72549. /**
  72550. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  72551. * exponential to prevent steep falloff artifacts).
  72552. */
  72553. get: function () {
  72554. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  72555. },
  72556. /**
  72557. * Sets the current filter to filtered "close ESM" (using the inverse of the
  72558. * exponential to prevent steep falloff artifacts).
  72559. */
  72560. set: function (value) {
  72561. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72562. return;
  72563. }
  72564. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72565. },
  72566. enumerable: true,
  72567. configurable: true
  72568. });
  72569. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  72570. /**
  72571. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  72572. */
  72573. get: function () {
  72574. return this.filter === ShadowGenerator.FILTER_PCF;
  72575. },
  72576. /**
  72577. * Sets the current filter to "PCF" (percentage closer filtering).
  72578. */
  72579. set: function (value) {
  72580. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  72581. return;
  72582. }
  72583. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  72584. },
  72585. enumerable: true,
  72586. configurable: true
  72587. });
  72588. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  72589. /**
  72590. * Gets the PCF or PCSS Quality.
  72591. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72592. */
  72593. get: function () {
  72594. return this._filteringQuality;
  72595. },
  72596. /**
  72597. * Sets the PCF or PCSS Quality.
  72598. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72599. */
  72600. set: function (filteringQuality) {
  72601. this._filteringQuality = filteringQuality;
  72602. },
  72603. enumerable: true,
  72604. configurable: true
  72605. });
  72606. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  72607. /**
  72608. * Gets if the current filter is set to "PCSS" (contact hardening).
  72609. */
  72610. get: function () {
  72611. return this.filter === ShadowGenerator.FILTER_PCSS;
  72612. },
  72613. /**
  72614. * Sets the current filter to "PCSS" (contact hardening).
  72615. */
  72616. set: function (value) {
  72617. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  72618. return;
  72619. }
  72620. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  72621. },
  72622. enumerable: true,
  72623. configurable: true
  72624. });
  72625. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  72626. /**
  72627. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72628. * Using a ratio helps keeping shape stability independently of the map size.
  72629. *
  72630. * It does not account for the light projection as it was having too much
  72631. * instability during the light setup or during light position changes.
  72632. *
  72633. * Only valid if useContactHardeningShadow is true.
  72634. */
  72635. get: function () {
  72636. return this._contactHardeningLightSizeUVRatio;
  72637. },
  72638. /**
  72639. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72640. * Using a ratio helps keeping shape stability independently of the map size.
  72641. *
  72642. * It does not account for the light projection as it was having too much
  72643. * instability during the light setup or during light position changes.
  72644. *
  72645. * Only valid if useContactHardeningShadow is true.
  72646. */
  72647. set: function (contactHardeningLightSizeUVRatio) {
  72648. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  72649. },
  72650. enumerable: true,
  72651. configurable: true
  72652. });
  72653. /**
  72654. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  72655. * 0 means strongest and 1 would means no shadow.
  72656. * @returns the darkness.
  72657. */
  72658. ShadowGenerator.prototype.getDarkness = function () {
  72659. return this._darkness;
  72660. };
  72661. /**
  72662. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  72663. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  72664. * @returns the shadow generator allowing fluent coding.
  72665. */
  72666. ShadowGenerator.prototype.setDarkness = function (darkness) {
  72667. if (darkness >= 1.0)
  72668. this._darkness = 1.0;
  72669. else if (darkness <= 0.0)
  72670. this._darkness = 0.0;
  72671. else
  72672. this._darkness = darkness;
  72673. return this;
  72674. };
  72675. /**
  72676. * Sets the ability to have transparent shadow (boolean).
  72677. * @param transparent True if transparent else False
  72678. * @returns the shadow generator allowing fluent coding
  72679. */
  72680. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  72681. this._transparencyShadow = transparent;
  72682. return this;
  72683. };
  72684. /**
  72685. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  72686. * @returns The render target texture if present otherwise, null
  72687. */
  72688. ShadowGenerator.prototype.getShadowMap = function () {
  72689. return this._shadowMap;
  72690. };
  72691. /**
  72692. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  72693. * @returns The render target texture if the shadow map is present otherwise, null
  72694. */
  72695. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  72696. if (this._shadowMap2) {
  72697. return this._shadowMap2;
  72698. }
  72699. return this._shadowMap;
  72700. };
  72701. /**
  72702. * Helper function to add a mesh and its descendants to the list of shadow casters.
  72703. * @param mesh Mesh to add
  72704. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  72705. * @returns the Shadow Generator itself
  72706. */
  72707. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  72708. if (includeDescendants === void 0) { includeDescendants = true; }
  72709. var _a;
  72710. if (!this._shadowMap) {
  72711. return this;
  72712. }
  72713. if (!this._shadowMap.renderList) {
  72714. this._shadowMap.renderList = [];
  72715. }
  72716. this._shadowMap.renderList.push(mesh);
  72717. if (includeDescendants) {
  72718. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  72719. }
  72720. return this;
  72721. };
  72722. /**
  72723. * Helper function to remove a mesh and its descendants from the list of shadow casters
  72724. * @param mesh Mesh to remove
  72725. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  72726. * @returns the Shadow Generator itself
  72727. */
  72728. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  72729. if (includeDescendants === void 0) { includeDescendants = true; }
  72730. if (!this._shadowMap || !this._shadowMap.renderList) {
  72731. return this;
  72732. }
  72733. var index = this._shadowMap.renderList.indexOf(mesh);
  72734. if (index !== -1) {
  72735. this._shadowMap.renderList.splice(index, 1);
  72736. }
  72737. if (includeDescendants) {
  72738. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  72739. var child = _a[_i];
  72740. this.removeShadowCaster(child);
  72741. }
  72742. }
  72743. return this;
  72744. };
  72745. /**
  72746. * Returns the associated light object.
  72747. * @returns the light generating the shadow
  72748. */
  72749. ShadowGenerator.prototype.getLight = function () {
  72750. return this._light;
  72751. };
  72752. ShadowGenerator.prototype._initializeGenerator = function () {
  72753. this._light._markMeshesAsLightDirty();
  72754. this._initializeShadowMap();
  72755. };
  72756. ShadowGenerator.prototype._initializeShadowMap = function () {
  72757. var _this = this;
  72758. // Render target
  72759. var engine = this._scene.getEngine();
  72760. if (engine.webGLVersion > 1) {
  72761. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  72762. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  72763. }
  72764. else {
  72765. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  72766. }
  72767. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72768. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72769. this._shadowMap.anisotropicFilteringLevel = 1;
  72770. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72771. this._shadowMap.renderParticles = false;
  72772. this._shadowMap.ignoreCameraViewport = true;
  72773. // Record Face Index before render.
  72774. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  72775. _this._currentFaceIndex = faceIndex;
  72776. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72777. engine.setColorWrite(false);
  72778. }
  72779. });
  72780. // Custom render function.
  72781. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  72782. // Blur if required afer render.
  72783. this._shadowMap.onAfterUnbindObservable.add(function () {
  72784. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72785. engine.setColorWrite(true);
  72786. }
  72787. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  72788. return;
  72789. }
  72790. var shadowMap = _this.getShadowMapForRendering();
  72791. if (shadowMap) {
  72792. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  72793. }
  72794. });
  72795. // Clear according to the chosen filter.
  72796. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  72797. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  72798. this._shadowMap.onClearObservable.add(function (engine) {
  72799. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72800. engine.clear(clearOne, false, true, false);
  72801. }
  72802. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  72803. engine.clear(clearZero, true, true, false);
  72804. }
  72805. else {
  72806. engine.clear(clearOne, true, true, false);
  72807. }
  72808. });
  72809. };
  72810. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  72811. var _this = this;
  72812. var engine = this._scene.getEngine();
  72813. var targetSize = this._mapSize / this.blurScale;
  72814. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  72815. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  72816. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72817. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72818. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72819. }
  72820. if (this.useKernelBlur) {
  72821. 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);
  72822. this._kernelBlurXPostprocess.width = targetSize;
  72823. this._kernelBlurXPostprocess.height = targetSize;
  72824. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  72825. effect.setTexture("textureSampler", _this._shadowMap);
  72826. });
  72827. 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);
  72828. this._kernelBlurXPostprocess.autoClear = false;
  72829. this._kernelBlurYPostprocess.autoClear = false;
  72830. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72831. this._kernelBlurXPostprocess.packedFloat = true;
  72832. this._kernelBlurYPostprocess.packedFloat = true;
  72833. }
  72834. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  72835. }
  72836. else {
  72837. 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);
  72838. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  72839. effect.setFloat2("screenSize", targetSize, targetSize);
  72840. effect.setTexture("textureSampler", _this._shadowMap);
  72841. });
  72842. this._boxBlurPostprocess.autoClear = false;
  72843. this._blurPostProcesses = [this._boxBlurPostprocess];
  72844. }
  72845. };
  72846. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72847. var index;
  72848. var engine = this._scene.getEngine();
  72849. if (depthOnlySubMeshes.length) {
  72850. engine.setColorWrite(false);
  72851. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72852. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  72853. }
  72854. engine.setColorWrite(true);
  72855. }
  72856. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72857. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  72858. }
  72859. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72860. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  72861. }
  72862. if (this._transparencyShadow) {
  72863. for (index = 0; index < transparentSubMeshes.length; index++) {
  72864. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  72865. }
  72866. }
  72867. };
  72868. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  72869. var _this = this;
  72870. var mesh = subMesh.getRenderingMesh();
  72871. var scene = this._scene;
  72872. var engine = scene.getEngine();
  72873. var material = subMesh.getMaterial();
  72874. if (!material) {
  72875. return;
  72876. }
  72877. // Culling
  72878. engine.setState(material.backFaceCulling);
  72879. // Managing instances
  72880. var batch = mesh._getInstancesRenderList(subMesh._id);
  72881. if (batch.mustReturn) {
  72882. return;
  72883. }
  72884. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72885. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  72886. engine.enableEffect(this._effect);
  72887. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  72888. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  72889. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  72890. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  72891. this._effect.setVector3("lightData", this._cachedDirection);
  72892. }
  72893. else {
  72894. this._effect.setVector3("lightData", this._cachedPosition);
  72895. }
  72896. if (scene.activeCamera) {
  72897. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  72898. }
  72899. // Alpha test
  72900. if (material && material.needAlphaTesting()) {
  72901. var alphaTexture = material.getAlphaTestTexture();
  72902. if (alphaTexture) {
  72903. this._effect.setTexture("diffuseSampler", alphaTexture);
  72904. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  72905. }
  72906. }
  72907. // Bones
  72908. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72909. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  72910. }
  72911. // Morph targets
  72912. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  72913. if (this.forceBackFacesOnly) {
  72914. engine.setState(true, 0, false, true);
  72915. }
  72916. // Draw
  72917. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72918. if (this.forceBackFacesOnly) {
  72919. engine.setState(true, 0, false, false);
  72920. }
  72921. }
  72922. else {
  72923. // Need to reset refresh rate of the shadowMap
  72924. if (this._shadowMap) {
  72925. this._shadowMap.resetRefreshCounter();
  72926. }
  72927. }
  72928. };
  72929. ShadowGenerator.prototype._applyFilterValues = function () {
  72930. if (!this._shadowMap) {
  72931. return;
  72932. }
  72933. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  72934. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  72935. }
  72936. else {
  72937. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72938. }
  72939. };
  72940. /**
  72941. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72942. * @param onCompiled Callback triggered at the and of the effects compilation
  72943. * @param options Sets of optional options forcing the compilation with different modes
  72944. */
  72945. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  72946. var _this = this;
  72947. var localOptions = __assign({ useInstances: false }, options);
  72948. var shadowMap = this.getShadowMap();
  72949. if (!shadowMap) {
  72950. if (onCompiled) {
  72951. onCompiled(this);
  72952. }
  72953. return;
  72954. }
  72955. var renderList = shadowMap.renderList;
  72956. if (!renderList) {
  72957. if (onCompiled) {
  72958. onCompiled(this);
  72959. }
  72960. return;
  72961. }
  72962. var subMeshes = new Array();
  72963. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  72964. var mesh = renderList_1[_i];
  72965. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  72966. }
  72967. if (subMeshes.length === 0) {
  72968. if (onCompiled) {
  72969. onCompiled(this);
  72970. }
  72971. return;
  72972. }
  72973. var currentIndex = 0;
  72974. var checkReady = function () {
  72975. if (!_this._scene || !_this._scene.getEngine()) {
  72976. return;
  72977. }
  72978. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  72979. currentIndex++;
  72980. if (currentIndex >= subMeshes.length) {
  72981. if (onCompiled) {
  72982. onCompiled(_this);
  72983. }
  72984. return;
  72985. }
  72986. }
  72987. setTimeout(checkReady, 16);
  72988. };
  72989. checkReady();
  72990. };
  72991. /**
  72992. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72993. * @param options Sets of optional options forcing the compilation with different modes
  72994. * @returns A promise that resolves when the compilation completes
  72995. */
  72996. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  72997. var _this = this;
  72998. return new Promise(function (resolve) {
  72999. _this.forceCompilation(function () {
  73000. resolve();
  73001. }, options);
  73002. });
  73003. };
  73004. /**
  73005. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  73006. * @param subMesh The submesh we want to render in the shadow map
  73007. * @param useInstances Defines wether will draw in the map using instances
  73008. * @returns true if ready otherwise, false
  73009. */
  73010. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  73011. var defines = [];
  73012. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73013. defines.push("#define FLOAT");
  73014. }
  73015. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73016. defines.push("#define ESM");
  73017. }
  73018. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  73019. defines.push("#define DEPTHTEXTURE");
  73020. }
  73021. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73022. var mesh = subMesh.getMesh();
  73023. var material = subMesh.getMaterial();
  73024. // Normal bias.
  73025. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73026. attribs.push(BABYLON.VertexBuffer.NormalKind);
  73027. defines.push("#define NORMAL");
  73028. if (mesh.nonUniformScaling) {
  73029. defines.push("#define NONUNIFORMSCALING");
  73030. }
  73031. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  73032. defines.push("#define DIRECTIONINLIGHTDATA");
  73033. }
  73034. }
  73035. // Alpha test
  73036. if (material && material.needAlphaTesting()) {
  73037. var alphaTexture = material.getAlphaTestTexture();
  73038. if (alphaTexture) {
  73039. defines.push("#define ALPHATEST");
  73040. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73041. attribs.push(BABYLON.VertexBuffer.UVKind);
  73042. defines.push("#define UV1");
  73043. }
  73044. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73045. if (alphaTexture.coordinatesIndex === 1) {
  73046. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73047. defines.push("#define UV2");
  73048. }
  73049. }
  73050. }
  73051. }
  73052. // Bones
  73053. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73054. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73055. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73056. if (mesh.numBoneInfluencers > 4) {
  73057. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73058. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73059. }
  73060. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73061. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  73062. }
  73063. else {
  73064. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73065. }
  73066. // Morph targets
  73067. var manager = mesh.morphTargetManager;
  73068. var morphInfluencers = 0;
  73069. if (manager) {
  73070. if (manager.numInfluencers > 0) {
  73071. defines.push("#define MORPHTARGETS");
  73072. morphInfluencers = manager.numInfluencers;
  73073. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  73074. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  73075. }
  73076. }
  73077. // Instances
  73078. if (useInstances) {
  73079. defines.push("#define INSTANCES");
  73080. attribs.push("world0");
  73081. attribs.push("world1");
  73082. attribs.push("world2");
  73083. attribs.push("world3");
  73084. }
  73085. // Get correct effect
  73086. var join = defines.join("\n");
  73087. if (this._cachedDefines !== join) {
  73088. this._cachedDefines = join;
  73089. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  73090. }
  73091. if (!this._effect.isReady()) {
  73092. return false;
  73093. }
  73094. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  73095. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  73096. this._initializeBlurRTTAndPostProcesses();
  73097. }
  73098. }
  73099. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  73100. return false;
  73101. }
  73102. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  73103. return false;
  73104. }
  73105. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  73106. return false;
  73107. }
  73108. return true;
  73109. };
  73110. /**
  73111. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  73112. * @param defines Defines of the material we want to update
  73113. * @param lightIndex Index of the light in the enabled light list of the material
  73114. */
  73115. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  73116. var scene = this._scene;
  73117. var light = this._light;
  73118. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  73119. return;
  73120. }
  73121. defines["SHADOW" + lightIndex] = true;
  73122. if (this.useContactHardeningShadow) {
  73123. defines["SHADOWPCSS" + lightIndex] = true;
  73124. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  73125. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  73126. }
  73127. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  73128. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  73129. }
  73130. // else default to high.
  73131. }
  73132. if (this.usePercentageCloserFiltering) {
  73133. defines["SHADOWPCF" + lightIndex] = true;
  73134. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  73135. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  73136. }
  73137. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  73138. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  73139. }
  73140. // else default to high.
  73141. }
  73142. else if (this.usePoissonSampling) {
  73143. defines["SHADOWPOISSON" + lightIndex] = true;
  73144. }
  73145. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73146. defines["SHADOWESM" + lightIndex] = true;
  73147. }
  73148. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  73149. defines["SHADOWCLOSEESM" + lightIndex] = true;
  73150. }
  73151. if (light.needCube()) {
  73152. defines["SHADOWCUBE" + lightIndex] = true;
  73153. }
  73154. };
  73155. /**
  73156. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  73157. * defined in the generator but impacting the effect).
  73158. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  73159. * @param effect The effect we are binfing the information for
  73160. */
  73161. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  73162. var light = this._light;
  73163. var scene = this._scene;
  73164. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  73165. return;
  73166. }
  73167. var camera = scene.activeCamera;
  73168. if (!camera) {
  73169. return;
  73170. }
  73171. var shadowMap = this.getShadowMap();
  73172. if (!shadowMap) {
  73173. return;
  73174. }
  73175. if (!light.needCube()) {
  73176. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  73177. }
  73178. // Only PCF uses depth stencil texture.
  73179. if (this._filter === ShadowGenerator.FILTER_PCF) {
  73180. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73181. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  73182. }
  73183. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  73184. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73185. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  73186. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  73187. }
  73188. else {
  73189. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73190. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  73191. }
  73192. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  73193. };
  73194. /**
  73195. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  73196. * (eq to shadow prjection matrix * light transform matrix)
  73197. * @returns The transform matrix used to create the shadow map
  73198. */
  73199. ShadowGenerator.prototype.getTransformMatrix = function () {
  73200. var scene = this._scene;
  73201. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  73202. return this._transformMatrix;
  73203. }
  73204. this._currentRenderID = scene.getRenderId();
  73205. this._currentFaceIndexCache = this._currentFaceIndex;
  73206. var lightPosition = this._light.position;
  73207. if (this._light.computeTransformedInformation()) {
  73208. lightPosition = this._light.transformedPosition;
  73209. }
  73210. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  73211. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  73212. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  73213. }
  73214. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  73215. this._cachedPosition.copyFrom(lightPosition);
  73216. this._cachedDirection.copyFrom(this._lightDirection);
  73217. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  73218. var shadowMap = this.getShadowMap();
  73219. if (shadowMap) {
  73220. var renderList = shadowMap.renderList;
  73221. if (renderList) {
  73222. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  73223. }
  73224. }
  73225. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  73226. }
  73227. return this._transformMatrix;
  73228. };
  73229. /**
  73230. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  73231. * Cube and 2D textures for instance.
  73232. */
  73233. ShadowGenerator.prototype.recreateShadowMap = function () {
  73234. var shadowMap = this._shadowMap;
  73235. if (!shadowMap) {
  73236. return;
  73237. }
  73238. // Track render list.
  73239. var renderList = shadowMap.renderList;
  73240. // Clean up existing data.
  73241. this._disposeRTTandPostProcesses();
  73242. // Reinitializes.
  73243. this._initializeGenerator();
  73244. // Reaffect the filter to ensure a correct fallback if necessary.
  73245. this.filter = this.filter;
  73246. // Reaffect the filter.
  73247. this._applyFilterValues();
  73248. // Reaffect Render List.
  73249. this._shadowMap.renderList = renderList;
  73250. };
  73251. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  73252. if (this._shadowMap2) {
  73253. this._shadowMap2.dispose();
  73254. this._shadowMap2 = null;
  73255. }
  73256. if (this._boxBlurPostprocess) {
  73257. this._boxBlurPostprocess.dispose();
  73258. this._boxBlurPostprocess = null;
  73259. }
  73260. if (this._kernelBlurXPostprocess) {
  73261. this._kernelBlurXPostprocess.dispose();
  73262. this._kernelBlurXPostprocess = null;
  73263. }
  73264. if (this._kernelBlurYPostprocess) {
  73265. this._kernelBlurYPostprocess.dispose();
  73266. this._kernelBlurYPostprocess = null;
  73267. }
  73268. this._blurPostProcesses = [];
  73269. };
  73270. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  73271. if (this._shadowMap) {
  73272. this._shadowMap.dispose();
  73273. this._shadowMap = null;
  73274. }
  73275. this._disposeBlurPostProcesses();
  73276. };
  73277. /**
  73278. * Disposes the ShadowGenerator.
  73279. * Returns nothing.
  73280. */
  73281. ShadowGenerator.prototype.dispose = function () {
  73282. this._disposeRTTandPostProcesses();
  73283. if (this._light) {
  73284. this._light._shadowGenerator = null;
  73285. this._light._markMeshesAsLightDirty();
  73286. }
  73287. };
  73288. /**
  73289. * Serializes the shadow generator setup to a json object.
  73290. * @returns The serialized JSON object
  73291. */
  73292. ShadowGenerator.prototype.serialize = function () {
  73293. var serializationObject = {};
  73294. var shadowMap = this.getShadowMap();
  73295. if (!shadowMap) {
  73296. return serializationObject;
  73297. }
  73298. serializationObject.lightId = this._light.id;
  73299. serializationObject.mapSize = shadowMap.getRenderSize();
  73300. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  73301. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  73302. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73303. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73304. serializationObject.usePoissonSampling = this.usePoissonSampling;
  73305. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  73306. serializationObject.depthScale = this.depthScale;
  73307. serializationObject.darkness = this.getDarkness();
  73308. serializationObject.blurBoxOffset = this.blurBoxOffset;
  73309. serializationObject.blurKernel = this.blurKernel;
  73310. serializationObject.blurScale = this.blurScale;
  73311. serializationObject.useKernelBlur = this.useKernelBlur;
  73312. serializationObject.transparencyShadow = this._transparencyShadow;
  73313. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  73314. serializationObject.bias = this.bias;
  73315. serializationObject.normalBias = this.normalBias;
  73316. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  73317. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  73318. serializationObject.filteringQuality = this.filteringQuality;
  73319. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  73320. serializationObject.renderList = [];
  73321. if (shadowMap.renderList) {
  73322. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  73323. var mesh = shadowMap.renderList[meshIndex];
  73324. serializationObject.renderList.push(mesh.id);
  73325. }
  73326. }
  73327. return serializationObject;
  73328. };
  73329. /**
  73330. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  73331. * @param parsedShadowGenerator The JSON object to parse
  73332. * @param scene The scene to create the shadow map for
  73333. * @returns The parsed shadow generator
  73334. */
  73335. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  73336. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  73337. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  73338. var shadowMap = shadowGenerator.getShadowMap();
  73339. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  73340. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  73341. meshes.forEach(function (mesh) {
  73342. if (!shadowMap) {
  73343. return;
  73344. }
  73345. if (!shadowMap.renderList) {
  73346. shadowMap.renderList = [];
  73347. }
  73348. shadowMap.renderList.push(mesh);
  73349. });
  73350. }
  73351. if (parsedShadowGenerator.usePoissonSampling) {
  73352. shadowGenerator.usePoissonSampling = true;
  73353. }
  73354. else if (parsedShadowGenerator.useExponentialShadowMap) {
  73355. shadowGenerator.useExponentialShadowMap = true;
  73356. }
  73357. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  73358. shadowGenerator.useBlurExponentialShadowMap = true;
  73359. }
  73360. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  73361. shadowGenerator.useCloseExponentialShadowMap = true;
  73362. }
  73363. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  73364. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  73365. }
  73366. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  73367. shadowGenerator.usePercentageCloserFiltering = true;
  73368. }
  73369. else if (parsedShadowGenerator.useContactHardeningShadow) {
  73370. shadowGenerator.useContactHardeningShadow = true;
  73371. }
  73372. if (parsedShadowGenerator.filteringQuality) {
  73373. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  73374. }
  73375. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  73376. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  73377. }
  73378. // Backward compat
  73379. else if (parsedShadowGenerator.useVarianceShadowMap) {
  73380. shadowGenerator.useExponentialShadowMap = true;
  73381. }
  73382. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  73383. shadowGenerator.useBlurExponentialShadowMap = true;
  73384. }
  73385. if (parsedShadowGenerator.depthScale) {
  73386. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  73387. }
  73388. if (parsedShadowGenerator.blurScale) {
  73389. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  73390. }
  73391. if (parsedShadowGenerator.blurBoxOffset) {
  73392. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  73393. }
  73394. if (parsedShadowGenerator.useKernelBlur) {
  73395. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  73396. }
  73397. if (parsedShadowGenerator.blurKernel) {
  73398. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  73399. }
  73400. if (parsedShadowGenerator.bias !== undefined) {
  73401. shadowGenerator.bias = parsedShadowGenerator.bias;
  73402. }
  73403. if (parsedShadowGenerator.normalBias !== undefined) {
  73404. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  73405. }
  73406. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  73407. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  73408. }
  73409. if (parsedShadowGenerator.darkness) {
  73410. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  73411. }
  73412. if (parsedShadowGenerator.transparencyShadow) {
  73413. shadowGenerator.setTransparencyShadow(true);
  73414. }
  73415. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  73416. return shadowGenerator;
  73417. };
  73418. /**
  73419. * Shadow generator mode None: no filtering applied.
  73420. */
  73421. ShadowGenerator.FILTER_NONE = 0;
  73422. /**
  73423. * Shadow generator mode ESM: Exponential Shadow Mapping.
  73424. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73425. */
  73426. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  73427. /**
  73428. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  73429. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  73430. */
  73431. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  73432. /**
  73433. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  73434. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73435. */
  73436. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  73437. /**
  73438. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  73439. * edge artifacts on steep falloff.
  73440. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73441. */
  73442. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  73443. /**
  73444. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  73445. * edge artifacts on steep falloff.
  73446. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73447. */
  73448. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  73449. /**
  73450. * Shadow generator mode PCF: Percentage Closer Filtering
  73451. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73452. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  73453. */
  73454. ShadowGenerator.FILTER_PCF = 6;
  73455. /**
  73456. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  73457. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73458. * Contact Hardening
  73459. */
  73460. ShadowGenerator.FILTER_PCSS = 7;
  73461. /**
  73462. * Reserved for PCF and PCSS
  73463. * Highest Quality.
  73464. *
  73465. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  73466. *
  73467. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  73468. */
  73469. ShadowGenerator.QUALITY_HIGH = 0;
  73470. /**
  73471. * Reserved for PCF and PCSS
  73472. * Good tradeoff for quality/perf cross devices
  73473. *
  73474. * Execute PCF on a 3*3 kernel.
  73475. *
  73476. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  73477. */
  73478. ShadowGenerator.QUALITY_MEDIUM = 1;
  73479. /**
  73480. * Reserved for PCF and PCSS
  73481. * The lowest quality but the fastest.
  73482. *
  73483. * Execute PCF on a 1*1 kernel.
  73484. *
  73485. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  73486. */
  73487. ShadowGenerator.QUALITY_LOW = 2;
  73488. return ShadowGenerator;
  73489. }());
  73490. BABYLON.ShadowGenerator = ShadowGenerator;
  73491. })(BABYLON || (BABYLON = {}));
  73492. //# sourceMappingURL=babylon.shadowGenerator.js.map
  73493. var BABYLON;
  73494. (function (BABYLON) {
  73495. // Adds the parser to the scene parsers.
  73496. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  73497. // Shadows
  73498. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  73499. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  73500. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  73501. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  73502. // SG would be available on their associated lights
  73503. }
  73504. }
  73505. });
  73506. /**
  73507. * Defines the shadow generator component responsible to manage any shadow generators
  73508. * in a given scene.
  73509. */
  73510. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  73511. /**
  73512. * Creates a new instance of the component for the given scene
  73513. * @param scene Defines the scene to register the component in
  73514. */
  73515. function ShadowGeneratorSceneComponent(scene) {
  73516. /**
  73517. * The component name helpfull to identify the component in the list of scene components.
  73518. */
  73519. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  73520. this.scene = scene;
  73521. }
  73522. /**
  73523. * Registers the component in a given scene
  73524. */
  73525. ShadowGeneratorSceneComponent.prototype.register = function () {
  73526. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  73527. };
  73528. /**
  73529. * Rebuilds the elements related to this component in case of
  73530. * context lost for instance.
  73531. */
  73532. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  73533. // Nothing To Do Here.
  73534. };
  73535. /**
  73536. * Serializes the component data to the specified json object
  73537. * @param serializationObject The object to serialize to
  73538. */
  73539. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  73540. // Shadows
  73541. serializationObject.shadowGenerators = [];
  73542. var lights = this.scene.lights;
  73543. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  73544. var light = lights_1[_i];
  73545. var shadowGenerator = light.getShadowGenerator();
  73546. if (shadowGenerator) {
  73547. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73548. }
  73549. }
  73550. };
  73551. /**
  73552. * Adds all the element from the container to the scene
  73553. * @param container the container holding the elements
  73554. */
  73555. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  73556. // Nothing To Do Here. (directly attached to a light)
  73557. };
  73558. /**
  73559. * Removes all the elements in the container from the scene
  73560. * @param container contains the elements to remove
  73561. */
  73562. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  73563. // Nothing To Do Here. (directly attached to a light)
  73564. };
  73565. /**
  73566. * Rebuilds the elements related to this component in case of
  73567. * context lost for instance.
  73568. */
  73569. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  73570. // Nothing To Do Here.
  73571. };
  73572. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  73573. // Shadows
  73574. var scene = this.scene;
  73575. if (this.scene.shadowsEnabled) {
  73576. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  73577. var light = scene.lights[lightIndex];
  73578. var shadowGenerator = light.getShadowGenerator();
  73579. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  73580. var shadowMap = (shadowGenerator.getShadowMap());
  73581. if (scene.textures.indexOf(shadowMap) !== -1) {
  73582. renderTargets.push(shadowMap);
  73583. }
  73584. }
  73585. }
  73586. }
  73587. };
  73588. return ShadowGeneratorSceneComponent;
  73589. }());
  73590. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  73591. })(BABYLON || (BABYLON = {}));
  73592. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  73593. var BABYLON;
  73594. (function (BABYLON) {
  73595. var DefaultLoadingScreen = /** @class */ (function () {
  73596. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  73597. if (_loadingText === void 0) { _loadingText = ""; }
  73598. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  73599. var _this = this;
  73600. this._renderingCanvas = _renderingCanvas;
  73601. this._loadingText = _loadingText;
  73602. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  73603. // Resize
  73604. this._resizeLoadingUI = function () {
  73605. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  73606. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  73607. if (!_this._loadingDiv) {
  73608. return;
  73609. }
  73610. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  73611. _this._loadingDiv.style.left = canvasRect.left + "px";
  73612. _this._loadingDiv.style.top = canvasRect.top + "px";
  73613. _this._loadingDiv.style.width = canvasRect.width + "px";
  73614. _this._loadingDiv.style.height = canvasRect.height + "px";
  73615. };
  73616. }
  73617. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  73618. if (this._loadingDiv) {
  73619. // Do not add a loading screen if there is already one
  73620. return;
  73621. }
  73622. this._loadingDiv = document.createElement("div");
  73623. this._loadingDiv.id = "babylonjsLoadingDiv";
  73624. this._loadingDiv.style.opacity = "0";
  73625. this._loadingDiv.style.transition = "opacity 1.5s ease";
  73626. this._loadingDiv.style.pointerEvents = "none";
  73627. // Loading text
  73628. this._loadingTextDiv = document.createElement("div");
  73629. this._loadingTextDiv.style.position = "absolute";
  73630. this._loadingTextDiv.style.left = "0";
  73631. this._loadingTextDiv.style.top = "50%";
  73632. this._loadingTextDiv.style.marginTop = "80px";
  73633. this._loadingTextDiv.style.width = "100%";
  73634. this._loadingTextDiv.style.height = "20px";
  73635. this._loadingTextDiv.style.fontFamily = "Arial";
  73636. this._loadingTextDiv.style.fontSize = "14px";
  73637. this._loadingTextDiv.style.color = "white";
  73638. this._loadingTextDiv.style.textAlign = "center";
  73639. this._loadingTextDiv.innerHTML = "Loading";
  73640. this._loadingDiv.appendChild(this._loadingTextDiv);
  73641. //set the predefined text
  73642. this._loadingTextDiv.innerHTML = this._loadingText;
  73643. // Generating keyframes
  73644. var style = document.createElement('style');
  73645. style.type = 'text/css';
  73646. 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 }";
  73647. style.innerHTML = keyFrames;
  73648. document.getElementsByTagName('head')[0].appendChild(style);
  73649. // Loading img
  73650. var imgBack = new Image();
  73651. 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";
  73652. imgBack.style.position = "absolute";
  73653. imgBack.style.left = "50%";
  73654. imgBack.style.top = "50%";
  73655. imgBack.style.marginLeft = "-60px";
  73656. imgBack.style.marginTop = "-60px";
  73657. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  73658. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  73659. imgBack.style.transformOrigin = "50% 50%";
  73660. imgBack.style.webkitTransformOrigin = "50% 50%";
  73661. this._loadingDiv.appendChild(imgBack);
  73662. this._resizeLoadingUI();
  73663. window.addEventListener("resize", this._resizeLoadingUI);
  73664. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73665. document.body.appendChild(this._loadingDiv);
  73666. this._loadingDiv.style.opacity = "1";
  73667. };
  73668. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  73669. var _this = this;
  73670. if (!this._loadingDiv) {
  73671. return;
  73672. }
  73673. var onTransitionEnd = function () {
  73674. if (!_this._loadingDiv) {
  73675. return;
  73676. }
  73677. document.body.removeChild(_this._loadingDiv);
  73678. window.removeEventListener("resize", _this._resizeLoadingUI);
  73679. _this._loadingDiv = null;
  73680. };
  73681. this._loadingDiv.style.opacity = "0";
  73682. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  73683. };
  73684. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  73685. set: function (text) {
  73686. this._loadingText = text;
  73687. if (this._loadingTextDiv) {
  73688. this._loadingTextDiv.innerHTML = this._loadingText;
  73689. }
  73690. },
  73691. enumerable: true,
  73692. configurable: true
  73693. });
  73694. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  73695. get: function () {
  73696. return this._loadingDivBackgroundColor;
  73697. },
  73698. set: function (color) {
  73699. this._loadingDivBackgroundColor = color;
  73700. if (!this._loadingDiv) {
  73701. return;
  73702. }
  73703. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73704. },
  73705. enumerable: true,
  73706. configurable: true
  73707. });
  73708. return DefaultLoadingScreen;
  73709. }());
  73710. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  73711. })(BABYLON || (BABYLON = {}));
  73712. //# sourceMappingURL=babylon.loadingScreen.js.map
  73713. var BABYLON;
  73714. (function (BABYLON) {
  73715. var SceneLoaderProgressEvent = /** @class */ (function () {
  73716. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  73717. this.lengthComputable = lengthComputable;
  73718. this.loaded = loaded;
  73719. this.total = total;
  73720. }
  73721. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  73722. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  73723. };
  73724. return SceneLoaderProgressEvent;
  73725. }());
  73726. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  73727. var SceneLoader = /** @class */ (function () {
  73728. function SceneLoader() {
  73729. }
  73730. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  73731. get: function () {
  73732. return 0;
  73733. },
  73734. enumerable: true,
  73735. configurable: true
  73736. });
  73737. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  73738. get: function () {
  73739. return 1;
  73740. },
  73741. enumerable: true,
  73742. configurable: true
  73743. });
  73744. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  73745. get: function () {
  73746. return 2;
  73747. },
  73748. enumerable: true,
  73749. configurable: true
  73750. });
  73751. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  73752. get: function () {
  73753. return 3;
  73754. },
  73755. enumerable: true,
  73756. configurable: true
  73757. });
  73758. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  73759. get: function () {
  73760. return SceneLoader._ForceFullSceneLoadingForIncremental;
  73761. },
  73762. set: function (value) {
  73763. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  73764. },
  73765. enumerable: true,
  73766. configurable: true
  73767. });
  73768. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  73769. get: function () {
  73770. return SceneLoader._ShowLoadingScreen;
  73771. },
  73772. set: function (value) {
  73773. SceneLoader._ShowLoadingScreen = value;
  73774. },
  73775. enumerable: true,
  73776. configurable: true
  73777. });
  73778. Object.defineProperty(SceneLoader, "loggingLevel", {
  73779. get: function () {
  73780. return SceneLoader._loggingLevel;
  73781. },
  73782. set: function (value) {
  73783. SceneLoader._loggingLevel = value;
  73784. },
  73785. enumerable: true,
  73786. configurable: true
  73787. });
  73788. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  73789. get: function () {
  73790. return SceneLoader._CleanBoneMatrixWeights;
  73791. },
  73792. set: function (value) {
  73793. SceneLoader._CleanBoneMatrixWeights = value;
  73794. },
  73795. enumerable: true,
  73796. configurable: true
  73797. });
  73798. SceneLoader._getDefaultPlugin = function () {
  73799. return SceneLoader._registeredPlugins[".babylon"];
  73800. };
  73801. SceneLoader._getPluginForExtension = function (extension) {
  73802. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  73803. if (registeredPlugin) {
  73804. return registeredPlugin;
  73805. }
  73806. 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");
  73807. return SceneLoader._getDefaultPlugin();
  73808. };
  73809. SceneLoader._getPluginForDirectLoad = function (data) {
  73810. for (var extension in SceneLoader._registeredPlugins) {
  73811. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  73812. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  73813. return SceneLoader._registeredPlugins[extension];
  73814. }
  73815. }
  73816. return SceneLoader._getDefaultPlugin();
  73817. };
  73818. SceneLoader._getPluginForFilename = function (sceneFilename) {
  73819. var queryStringPosition = sceneFilename.indexOf("?");
  73820. if (queryStringPosition !== -1) {
  73821. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  73822. }
  73823. var dotPosition = sceneFilename.lastIndexOf(".");
  73824. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  73825. return SceneLoader._getPluginForExtension(extension);
  73826. };
  73827. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  73828. SceneLoader._getDirectLoad = function (sceneFilename) {
  73829. if (sceneFilename.substr(0, 5) === "data:") {
  73830. return sceneFilename.substr(5);
  73831. }
  73832. return null;
  73833. };
  73834. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  73835. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  73836. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  73837. var plugin;
  73838. if (registeredPlugin.plugin.createPlugin) {
  73839. plugin = registeredPlugin.plugin.createPlugin();
  73840. }
  73841. else {
  73842. plugin = registeredPlugin.plugin;
  73843. }
  73844. var useArrayBuffer = registeredPlugin.isBinary;
  73845. var database;
  73846. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  73847. var dataCallback = function (data, responseURL) {
  73848. if (scene.isDisposed) {
  73849. onError("Scene has been disposed");
  73850. return;
  73851. }
  73852. scene.database = database;
  73853. onSuccess(plugin, data, responseURL);
  73854. };
  73855. var request = null;
  73856. var pluginDisposed = false;
  73857. var onDisposeObservable = plugin.onDisposeObservable;
  73858. if (onDisposeObservable) {
  73859. onDisposeObservable.add(function () {
  73860. pluginDisposed = true;
  73861. if (request) {
  73862. request.abort();
  73863. request = null;
  73864. }
  73865. onDispose();
  73866. });
  73867. }
  73868. var manifestChecked = function () {
  73869. if (pluginDisposed) {
  73870. return;
  73871. }
  73872. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  73873. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  73874. } : undefined, database, useArrayBuffer, function (request, exception) {
  73875. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  73876. });
  73877. };
  73878. if (directLoad) {
  73879. dataCallback(directLoad);
  73880. return plugin;
  73881. }
  73882. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  73883. var engine = scene.getEngine();
  73884. var canUseOfflineSupport = engine.enableOfflineSupport;
  73885. if (canUseOfflineSupport) {
  73886. // Also check for exceptions
  73887. var exceptionFound = false;
  73888. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  73889. var regex = _a[_i];
  73890. if (regex.test(fileInfo.url)) {
  73891. exceptionFound = true;
  73892. break;
  73893. }
  73894. }
  73895. canUseOfflineSupport = !exceptionFound;
  73896. }
  73897. if (canUseOfflineSupport) {
  73898. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  73899. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  73900. }
  73901. else {
  73902. manifestChecked();
  73903. }
  73904. }
  73905. // Loading file from disk via input file or drag'n'drop
  73906. else {
  73907. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  73908. if (file) {
  73909. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  73910. }
  73911. else {
  73912. onError("Unable to find file named " + fileInfo.name);
  73913. }
  73914. }
  73915. return plugin;
  73916. };
  73917. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  73918. var url;
  73919. var name;
  73920. if (!sceneFilename) {
  73921. url = rootUrl;
  73922. name = BABYLON.Tools.GetFilename(rootUrl);
  73923. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  73924. }
  73925. else {
  73926. if (sceneFilename.substr(0, 1) === "/") {
  73927. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  73928. return null;
  73929. }
  73930. url = rootUrl + sceneFilename;
  73931. name = sceneFilename;
  73932. }
  73933. ;
  73934. return {
  73935. url: url,
  73936. rootUrl: rootUrl,
  73937. name: name
  73938. };
  73939. };
  73940. // Public functions
  73941. SceneLoader.GetPluginForExtension = function (extension) {
  73942. return SceneLoader._getPluginForExtension(extension).plugin;
  73943. };
  73944. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  73945. return !!SceneLoader._registeredPlugins[extension];
  73946. };
  73947. SceneLoader.RegisterPlugin = function (plugin) {
  73948. if (typeof plugin.extensions === "string") {
  73949. var extension = plugin.extensions;
  73950. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73951. plugin: plugin,
  73952. isBinary: false
  73953. };
  73954. }
  73955. else {
  73956. var extensions = plugin.extensions;
  73957. Object.keys(extensions).forEach(function (extension) {
  73958. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73959. plugin: plugin,
  73960. isBinary: extensions[extension].isBinary
  73961. };
  73962. });
  73963. }
  73964. };
  73965. /**
  73966. * Import meshes into a scene
  73967. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  73968. * @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)
  73969. * @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)
  73970. * @param scene the instance of BABYLON.Scene to append to
  73971. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  73972. * @param onProgress a callback with a progress event for each file being loaded
  73973. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73974. * @param pluginExtension the extension used to determine the plugin
  73975. * @returns The loaded plugin
  73976. */
  73977. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73978. if (sceneFilename === void 0) { sceneFilename = ""; }
  73979. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73980. if (onSuccess === void 0) { onSuccess = null; }
  73981. if (onProgress === void 0) { onProgress = null; }
  73982. if (onError === void 0) { onError = null; }
  73983. if (pluginExtension === void 0) { pluginExtension = null; }
  73984. if (!scene) {
  73985. BABYLON.Tools.Error("No scene available to import mesh to");
  73986. return null;
  73987. }
  73988. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73989. if (!fileInfo) {
  73990. return null;
  73991. }
  73992. var loadingToken = {};
  73993. scene._addPendingData(loadingToken);
  73994. var disposeHandler = function () {
  73995. scene._removePendingData(loadingToken);
  73996. };
  73997. var errorHandler = function (message, exception) {
  73998. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  73999. if (onError) {
  74000. onError(scene, errorMessage, exception);
  74001. }
  74002. else {
  74003. BABYLON.Tools.Error(errorMessage);
  74004. // should the exception be thrown?
  74005. }
  74006. disposeHandler();
  74007. };
  74008. var progressHandler = onProgress ? function (event) {
  74009. try {
  74010. onProgress(event);
  74011. }
  74012. catch (e) {
  74013. errorHandler("Error in onProgress callback", e);
  74014. }
  74015. } : undefined;
  74016. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  74017. scene.importedMeshesFiles.push(fileInfo.url);
  74018. if (onSuccess) {
  74019. try {
  74020. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  74021. }
  74022. catch (e) {
  74023. errorHandler("Error in onSuccess callback", e);
  74024. }
  74025. }
  74026. scene._removePendingData(loadingToken);
  74027. };
  74028. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74029. if (plugin.rewriteRootURL) {
  74030. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  74031. }
  74032. if (plugin.importMesh) {
  74033. var syncedPlugin = plugin;
  74034. var meshes = new Array();
  74035. var particleSystems = new Array();
  74036. var skeletons = new Array();
  74037. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  74038. return;
  74039. }
  74040. scene.loadingPluginName = plugin.name;
  74041. successHandler(meshes, particleSystems, skeletons, []);
  74042. }
  74043. else {
  74044. var asyncedPlugin = plugin;
  74045. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  74046. scene.loadingPluginName = plugin.name;
  74047. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  74048. }).catch(function (error) {
  74049. errorHandler(error.message, error);
  74050. });
  74051. }
  74052. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74053. };
  74054. /**
  74055. * Import meshes into a scene
  74056. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  74057. * @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)
  74058. * @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)
  74059. * @param scene the instance of BABYLON.Scene to append to
  74060. * @param onProgress a callback with a progress event for each file being loaded
  74061. * @param pluginExtension the extension used to determine the plugin
  74062. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  74063. */
  74064. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74065. if (sceneFilename === void 0) { sceneFilename = ""; }
  74066. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74067. if (onProgress === void 0) { onProgress = null; }
  74068. if (pluginExtension === void 0) { pluginExtension = null; }
  74069. return new Promise(function (resolve, reject) {
  74070. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  74071. resolve({
  74072. meshes: meshes,
  74073. particleSystems: particleSystems,
  74074. skeletons: skeletons,
  74075. animationGroups: animationGroups
  74076. });
  74077. }, onProgress, function (scene, message, exception) {
  74078. reject(exception || new Error(message));
  74079. }, pluginExtension);
  74080. });
  74081. };
  74082. /**
  74083. * Load a scene
  74084. * @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)
  74085. * @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)
  74086. * @param engine is the instance of BABYLON.Engine to use to create the scene
  74087. * @param onSuccess a callback with the scene when import succeeds
  74088. * @param onProgress a callback with a progress event for each file being loaded
  74089. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74090. * @param pluginExtension the extension used to determine the plugin
  74091. * @returns The loaded plugin
  74092. */
  74093. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  74094. if (onSuccess === void 0) { onSuccess = null; }
  74095. if (onProgress === void 0) { onProgress = null; }
  74096. if (onError === void 0) { onError = null; }
  74097. if (pluginExtension === void 0) { pluginExtension = null; }
  74098. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  74099. };
  74100. /**
  74101. * Load a scene
  74102. * @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)
  74103. * @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)
  74104. * @param engine is the instance of BABYLON.Engine to use to create the scene
  74105. * @param onProgress a callback with a progress event for each file being loaded
  74106. * @param pluginExtension the extension used to determine the plugin
  74107. * @returns The loaded scene
  74108. */
  74109. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  74110. if (onProgress === void 0) { onProgress = null; }
  74111. if (pluginExtension === void 0) { pluginExtension = null; }
  74112. return new Promise(function (resolve, reject) {
  74113. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  74114. resolve(scene);
  74115. }, onProgress, function (scene, message, exception) {
  74116. reject(exception || new Error(message));
  74117. }, pluginExtension);
  74118. });
  74119. };
  74120. /**
  74121. * Append a scene
  74122. * @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)
  74123. * @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)
  74124. * @param scene is the instance of BABYLON.Scene to append to
  74125. * @param onSuccess a callback with the scene when import succeeds
  74126. * @param onProgress a callback with a progress event for each file being loaded
  74127. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74128. * @param pluginExtension the extension used to determine the plugin
  74129. * @returns The loaded plugin
  74130. */
  74131. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74132. if (sceneFilename === void 0) { sceneFilename = ""; }
  74133. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74134. if (onSuccess === void 0) { onSuccess = null; }
  74135. if (onProgress === void 0) { onProgress = null; }
  74136. if (onError === void 0) { onError = null; }
  74137. if (pluginExtension === void 0) { pluginExtension = null; }
  74138. if (!scene) {
  74139. BABYLON.Tools.Error("No scene available to append to");
  74140. return null;
  74141. }
  74142. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74143. if (!fileInfo) {
  74144. return null;
  74145. }
  74146. if (SceneLoader.ShowLoadingScreen) {
  74147. scene.getEngine().displayLoadingUI();
  74148. }
  74149. var loadingToken = {};
  74150. scene._addPendingData(loadingToken);
  74151. var disposeHandler = function () {
  74152. scene._removePendingData(loadingToken);
  74153. scene.getEngine().hideLoadingUI();
  74154. };
  74155. var errorHandler = function (message, exception) {
  74156. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  74157. if (onError) {
  74158. onError(scene, errorMessage, exception);
  74159. }
  74160. else {
  74161. BABYLON.Tools.Error(errorMessage);
  74162. // should the exception be thrown?
  74163. }
  74164. disposeHandler();
  74165. };
  74166. var progressHandler = onProgress ? function (event) {
  74167. try {
  74168. onProgress(event);
  74169. }
  74170. catch (e) {
  74171. errorHandler("Error in onProgress callback", e);
  74172. }
  74173. } : undefined;
  74174. var successHandler = function () {
  74175. if (onSuccess) {
  74176. try {
  74177. onSuccess(scene);
  74178. }
  74179. catch (e) {
  74180. errorHandler("Error in onSuccess callback", e);
  74181. }
  74182. }
  74183. scene._removePendingData(loadingToken);
  74184. };
  74185. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74186. if (plugin.load) {
  74187. var syncedPlugin = plugin;
  74188. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  74189. return;
  74190. }
  74191. scene.loadingPluginName = plugin.name;
  74192. successHandler();
  74193. }
  74194. else {
  74195. var asyncedPlugin = plugin;
  74196. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  74197. scene.loadingPluginName = plugin.name;
  74198. successHandler();
  74199. }).catch(function (error) {
  74200. errorHandler(error.message, error);
  74201. });
  74202. }
  74203. if (SceneLoader.ShowLoadingScreen) {
  74204. scene.executeWhenReady(function () {
  74205. scene.getEngine().hideLoadingUI();
  74206. });
  74207. }
  74208. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74209. };
  74210. /**
  74211. * Append a scene
  74212. * @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)
  74213. * @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)
  74214. * @param scene is the instance of BABYLON.Scene to append to
  74215. * @param onProgress a callback with a progress event for each file being loaded
  74216. * @param pluginExtension the extension used to determine the plugin
  74217. * @returns The given scene
  74218. */
  74219. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74220. if (sceneFilename === void 0) { sceneFilename = ""; }
  74221. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74222. if (onProgress === void 0) { onProgress = null; }
  74223. if (pluginExtension === void 0) { pluginExtension = null; }
  74224. return new Promise(function (resolve, reject) {
  74225. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  74226. resolve(scene);
  74227. }, onProgress, function (scene, message, exception) {
  74228. reject(exception || new Error(message));
  74229. }, pluginExtension);
  74230. });
  74231. };
  74232. /**
  74233. * Load a scene into an asset container
  74234. * @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)
  74235. * @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)
  74236. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  74237. * @param onSuccess a callback with the scene when import succeeds
  74238. * @param onProgress a callback with a progress event for each file being loaded
  74239. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74240. * @param pluginExtension the extension used to determine the plugin
  74241. * @returns The loaded plugin
  74242. */
  74243. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74244. if (sceneFilename === void 0) { sceneFilename = ""; }
  74245. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74246. if (onSuccess === void 0) { onSuccess = null; }
  74247. if (onProgress === void 0) { onProgress = null; }
  74248. if (onError === void 0) { onError = null; }
  74249. if (pluginExtension === void 0) { pluginExtension = null; }
  74250. if (!scene) {
  74251. BABYLON.Tools.Error("No scene available to load asset container to");
  74252. return null;
  74253. }
  74254. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74255. if (!fileInfo) {
  74256. return null;
  74257. }
  74258. var loadingToken = {};
  74259. scene._addPendingData(loadingToken);
  74260. var disposeHandler = function () {
  74261. scene._removePendingData(loadingToken);
  74262. };
  74263. var errorHandler = function (message, exception) {
  74264. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  74265. if (onError) {
  74266. onError(scene, errorMessage, exception);
  74267. }
  74268. else {
  74269. BABYLON.Tools.Error(errorMessage);
  74270. // should the exception be thrown?
  74271. }
  74272. disposeHandler();
  74273. };
  74274. var progressHandler = onProgress ? function (event) {
  74275. try {
  74276. onProgress(event);
  74277. }
  74278. catch (e) {
  74279. errorHandler("Error in onProgress callback", e);
  74280. }
  74281. } : undefined;
  74282. var successHandler = function (assets) {
  74283. if (onSuccess) {
  74284. try {
  74285. onSuccess(assets);
  74286. }
  74287. catch (e) {
  74288. errorHandler("Error in onSuccess callback", e);
  74289. }
  74290. }
  74291. scene._removePendingData(loadingToken);
  74292. };
  74293. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74294. if (plugin.loadAssetContainer) {
  74295. var syncedPlugin = plugin;
  74296. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  74297. if (!assetContainer) {
  74298. return;
  74299. }
  74300. scene.loadingPluginName = plugin.name;
  74301. successHandler(assetContainer);
  74302. }
  74303. else if (plugin.loadAssetContainerAsync) {
  74304. var asyncedPlugin = plugin;
  74305. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  74306. scene.loadingPluginName = plugin.name;
  74307. successHandler(assetContainer);
  74308. }).catch(function (error) {
  74309. errorHandler(error.message, error);
  74310. });
  74311. }
  74312. else {
  74313. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  74314. }
  74315. if (SceneLoader.ShowLoadingScreen) {
  74316. scene.executeWhenReady(function () {
  74317. scene.getEngine().hideLoadingUI();
  74318. });
  74319. }
  74320. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74321. };
  74322. /**
  74323. * Load a scene into an asset container
  74324. * @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)
  74325. * @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)
  74326. * @param scene is the instance of BABYLON.Scene to append to
  74327. * @param onProgress a callback with a progress event for each file being loaded
  74328. * @param pluginExtension the extension used to determine the plugin
  74329. * @returns The loaded asset container
  74330. */
  74331. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74332. if (sceneFilename === void 0) { sceneFilename = ""; }
  74333. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74334. if (onProgress === void 0) { onProgress = null; }
  74335. if (pluginExtension === void 0) { pluginExtension = null; }
  74336. return new Promise(function (resolve, reject) {
  74337. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  74338. resolve(assetContainer);
  74339. }, onProgress, function (scene, message, exception) {
  74340. reject(exception || new Error(message));
  74341. }, pluginExtension);
  74342. });
  74343. };
  74344. // Flags
  74345. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  74346. SceneLoader._ShowLoadingScreen = true;
  74347. SceneLoader._CleanBoneMatrixWeights = false;
  74348. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  74349. // Members
  74350. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  74351. SceneLoader._registeredPlugins = {};
  74352. return SceneLoader;
  74353. }());
  74354. BABYLON.SceneLoader = SceneLoader;
  74355. ;
  74356. })(BABYLON || (BABYLON = {}));
  74357. //# sourceMappingURL=babylon.sceneLoader.js.map
  74358. var BABYLON;
  74359. (function (BABYLON) {
  74360. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  74361. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74362. var parsedMaterial = parsedData.materials[index];
  74363. if (parsedMaterial.id === id) {
  74364. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74365. }
  74366. }
  74367. return null;
  74368. };
  74369. var isDescendantOf = function (mesh, names, hierarchyIds) {
  74370. for (var i in names) {
  74371. if (mesh.name === names[i]) {
  74372. hierarchyIds.push(mesh.id);
  74373. return true;
  74374. }
  74375. }
  74376. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  74377. hierarchyIds.push(mesh.id);
  74378. return true;
  74379. }
  74380. return false;
  74381. };
  74382. var logOperation = function (operation, producer) {
  74383. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  74384. };
  74385. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  74386. if (addToScene === void 0) { addToScene = false; }
  74387. var container = new BABYLON.AssetContainer(scene);
  74388. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74389. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74390. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74391. // and avoid problems with multiple concurrent .babylon loads.
  74392. var log = "importScene has failed JSON parse";
  74393. try {
  74394. var parsedData = JSON.parse(data);
  74395. log = "";
  74396. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74397. var index;
  74398. var cache;
  74399. // Lights
  74400. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  74401. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  74402. var parsedLight = parsedData.lights[index];
  74403. var light = BABYLON.Light.Parse(parsedLight, scene);
  74404. if (light) {
  74405. container.lights.push(light);
  74406. log += (index === 0 ? "\n\tLights:" : "");
  74407. log += "\n\t\t" + light.toString(fullDetails);
  74408. }
  74409. }
  74410. }
  74411. // Animations
  74412. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  74413. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  74414. var parsedAnimation = parsedData.animations[index];
  74415. var animation = BABYLON.Animation.Parse(parsedAnimation);
  74416. scene.animations.push(animation);
  74417. container.animations.push(animation);
  74418. log += (index === 0 ? "\n\tAnimations:" : "");
  74419. log += "\n\t\t" + animation.toString(fullDetails);
  74420. }
  74421. }
  74422. // Materials
  74423. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  74424. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74425. var parsedMaterial = parsedData.materials[index];
  74426. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74427. container.materials.push(mat);
  74428. log += (index === 0 ? "\n\tMaterials:" : "");
  74429. log += "\n\t\t" + mat.toString(fullDetails);
  74430. }
  74431. }
  74432. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74433. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  74434. var parsedMultiMaterial = parsedData.multiMaterials[index];
  74435. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74436. container.multiMaterials.push(mmat);
  74437. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  74438. log += "\n\t\t" + mmat.toString(fullDetails);
  74439. }
  74440. }
  74441. // Morph targets
  74442. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74443. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74444. var managerData = _a[_i];
  74445. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  74446. }
  74447. }
  74448. // Skeletons
  74449. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74450. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  74451. var parsedSkeleton = parsedData.skeletons[index];
  74452. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74453. container.skeletons.push(skeleton);
  74454. log += (index === 0 ? "\n\tSkeletons:" : "");
  74455. log += "\n\t\t" + skeleton.toString(fullDetails);
  74456. }
  74457. }
  74458. // Geometries
  74459. var geometries = parsedData.geometries;
  74460. if (geometries !== undefined && geometries !== null) {
  74461. var addedGeometry = new Array();
  74462. // Boxes
  74463. var boxes = geometries.boxes;
  74464. if (boxes !== undefined && boxes !== null) {
  74465. for (index = 0, cache = boxes.length; index < cache; index++) {
  74466. var parsedBox = boxes[index];
  74467. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  74468. }
  74469. }
  74470. // Spheres
  74471. var spheres = geometries.spheres;
  74472. if (spheres !== undefined && spheres !== null) {
  74473. for (index = 0, cache = spheres.length; index < cache; index++) {
  74474. var parsedSphere = spheres[index];
  74475. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  74476. }
  74477. }
  74478. // Cylinders
  74479. var cylinders = geometries.cylinders;
  74480. if (cylinders !== undefined && cylinders !== null) {
  74481. for (index = 0, cache = cylinders.length; index < cache; index++) {
  74482. var parsedCylinder = cylinders[index];
  74483. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  74484. }
  74485. }
  74486. // Toruses
  74487. var toruses = geometries.toruses;
  74488. if (toruses !== undefined && toruses !== null) {
  74489. for (index = 0, cache = toruses.length; index < cache; index++) {
  74490. var parsedTorus = toruses[index];
  74491. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  74492. }
  74493. }
  74494. // Grounds
  74495. var grounds = geometries.grounds;
  74496. if (grounds !== undefined && grounds !== null) {
  74497. for (index = 0, cache = grounds.length; index < cache; index++) {
  74498. var parsedGround = grounds[index];
  74499. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  74500. }
  74501. }
  74502. // Planes
  74503. var planes = geometries.planes;
  74504. if (planes !== undefined && planes !== null) {
  74505. for (index = 0, cache = planes.length; index < cache; index++) {
  74506. var parsedPlane = planes[index];
  74507. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  74508. }
  74509. }
  74510. // TorusKnots
  74511. var torusKnots = geometries.torusKnots;
  74512. if (torusKnots !== undefined && torusKnots !== null) {
  74513. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  74514. var parsedTorusKnot = torusKnots[index];
  74515. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  74516. }
  74517. }
  74518. // VertexData
  74519. var vertexData = geometries.vertexData;
  74520. if (vertexData !== undefined && vertexData !== null) {
  74521. for (index = 0, cache = vertexData.length; index < cache; index++) {
  74522. var parsedVertexData = vertexData[index];
  74523. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  74524. }
  74525. }
  74526. addedGeometry.forEach(function (g) {
  74527. if (g) {
  74528. container.geometries.push(g);
  74529. }
  74530. });
  74531. }
  74532. // Transform nodes
  74533. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  74534. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  74535. var parsedTransformNode = parsedData.transformNodes[index];
  74536. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  74537. container.transformNodes.push(node);
  74538. }
  74539. }
  74540. // Meshes
  74541. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74542. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74543. var parsedMesh = parsedData.meshes[index];
  74544. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74545. container.meshes.push(mesh);
  74546. log += (index === 0 ? "\n\tMeshes:" : "");
  74547. log += "\n\t\t" + mesh.toString(fullDetails);
  74548. }
  74549. }
  74550. // Cameras
  74551. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  74552. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  74553. var parsedCamera = parsedData.cameras[index];
  74554. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  74555. container.cameras.push(camera);
  74556. log += (index === 0 ? "\n\tCameras:" : "");
  74557. log += "\n\t\t" + camera.toString(fullDetails);
  74558. }
  74559. }
  74560. // Animation Groups
  74561. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  74562. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  74563. var parsedAnimationGroup = parsedData.animationGroups[index];
  74564. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  74565. container.animationGroups.push(animationGroup);
  74566. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  74567. log += "\n\t\t" + animationGroup.toString(fullDetails);
  74568. }
  74569. }
  74570. // Browsing all the graph to connect the dots
  74571. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  74572. var camera = scene.cameras[index];
  74573. if (camera._waitingParentId) {
  74574. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  74575. camera._waitingParentId = null;
  74576. }
  74577. }
  74578. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74579. var light_1 = scene.lights[index];
  74580. if (light_1 && light_1._waitingParentId) {
  74581. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  74582. light_1._waitingParentId = null;
  74583. }
  74584. }
  74585. // Connect parents & children and parse actions
  74586. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  74587. var transformNode = scene.transformNodes[index];
  74588. if (transformNode._waitingParentId) {
  74589. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  74590. transformNode._waitingParentId = null;
  74591. }
  74592. }
  74593. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74594. var mesh = scene.meshes[index];
  74595. if (mesh._waitingParentId) {
  74596. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  74597. mesh._waitingParentId = null;
  74598. }
  74599. }
  74600. // freeze world matrix application
  74601. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74602. var currentMesh = scene.meshes[index];
  74603. if (currentMesh._waitingFreezeWorldMatrix) {
  74604. currentMesh.freezeWorldMatrix();
  74605. currentMesh._waitingFreezeWorldMatrix = null;
  74606. }
  74607. else {
  74608. currentMesh.computeWorldMatrix(true);
  74609. }
  74610. }
  74611. // Lights exclusions / inclusions
  74612. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74613. var light_2 = scene.lights[index];
  74614. // Excluded check
  74615. if (light_2._excludedMeshesIds.length > 0) {
  74616. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  74617. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  74618. if (excludedMesh) {
  74619. light_2.excludedMeshes.push(excludedMesh);
  74620. }
  74621. }
  74622. light_2._excludedMeshesIds = [];
  74623. }
  74624. // Included check
  74625. if (light_2._includedOnlyMeshesIds.length > 0) {
  74626. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  74627. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  74628. if (includedOnlyMesh) {
  74629. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  74630. }
  74631. }
  74632. light_2._includedOnlyMeshesIds = [];
  74633. }
  74634. }
  74635. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  74636. // Actions (scene) Done last as it can access other objects.
  74637. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74638. var mesh = scene.meshes[index];
  74639. if (mesh._waitingActions) {
  74640. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  74641. mesh._waitingActions = null;
  74642. }
  74643. }
  74644. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  74645. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  74646. }
  74647. if (!addToScene) {
  74648. container.removeAllFromScene();
  74649. }
  74650. }
  74651. catch (err) {
  74652. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  74653. if (onError) {
  74654. onError(msg, err);
  74655. }
  74656. else {
  74657. BABYLON.Tools.Log(msg);
  74658. throw err;
  74659. }
  74660. }
  74661. finally {
  74662. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74663. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74664. }
  74665. }
  74666. return container;
  74667. };
  74668. BABYLON.SceneLoader.RegisterPlugin({
  74669. name: "babylon.js",
  74670. extensions: ".babylon",
  74671. canDirectLoad: function (data) {
  74672. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  74673. return true;
  74674. }
  74675. return false;
  74676. },
  74677. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  74678. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74679. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74680. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74681. // and avoid problems with multiple concurrent .babylon loads.
  74682. var log = "importMesh has failed JSON parse";
  74683. try {
  74684. var parsedData = JSON.parse(data);
  74685. log = "";
  74686. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74687. if (!meshesNames) {
  74688. meshesNames = null;
  74689. }
  74690. else if (!Array.isArray(meshesNames)) {
  74691. meshesNames = [meshesNames];
  74692. }
  74693. var hierarchyIds = new Array();
  74694. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74695. var loadedSkeletonsIds = [];
  74696. var loadedMaterialsIds = [];
  74697. var index;
  74698. var cache;
  74699. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74700. var parsedMesh = parsedData.meshes[index];
  74701. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  74702. if (meshesNames !== null) {
  74703. // Remove found mesh name from list.
  74704. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  74705. }
  74706. //Geometry?
  74707. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  74708. //does the file contain geometries?
  74709. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  74710. //find the correct geometry and add it to the scene
  74711. var found = false;
  74712. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  74713. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  74714. return;
  74715. }
  74716. else {
  74717. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  74718. if (parsedGeometryData.id === parsedMesh.geometryId) {
  74719. switch (geometryType) {
  74720. case "boxes":
  74721. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  74722. break;
  74723. case "spheres":
  74724. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  74725. break;
  74726. case "cylinders":
  74727. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  74728. break;
  74729. case "toruses":
  74730. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  74731. break;
  74732. case "grounds":
  74733. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  74734. break;
  74735. case "planes":
  74736. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  74737. break;
  74738. case "torusKnots":
  74739. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  74740. break;
  74741. case "vertexData":
  74742. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  74743. break;
  74744. }
  74745. found = true;
  74746. }
  74747. });
  74748. }
  74749. });
  74750. if (found === false) {
  74751. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  74752. }
  74753. }
  74754. }
  74755. // Material ?
  74756. if (parsedMesh.materialId) {
  74757. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  74758. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74759. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  74760. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  74761. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  74762. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  74763. var subMatId = parsedMultiMaterial.materials[matIndex];
  74764. loadedMaterialsIds.push(subMatId);
  74765. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  74766. if (mat) {
  74767. log += "\n\tMaterial " + mat.toString(fullDetails);
  74768. }
  74769. }
  74770. loadedMaterialsIds.push(parsedMultiMaterial.id);
  74771. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74772. if (mmat) {
  74773. materialFound = true;
  74774. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  74775. }
  74776. break;
  74777. }
  74778. }
  74779. }
  74780. if (materialFound === false) {
  74781. loadedMaterialsIds.push(parsedMesh.materialId);
  74782. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  74783. if (!mat) {
  74784. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  74785. }
  74786. else {
  74787. log += "\n\tMaterial " + mat.toString(fullDetails);
  74788. }
  74789. }
  74790. }
  74791. // Skeleton ?
  74792. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74793. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  74794. if (skeletonAlreadyLoaded === false) {
  74795. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  74796. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  74797. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  74798. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74799. skeletons.push(skeleton);
  74800. loadedSkeletonsIds.push(parsedSkeleton.id);
  74801. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  74802. }
  74803. }
  74804. }
  74805. }
  74806. // Morph targets ?
  74807. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74808. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74809. var managerData = _a[_i];
  74810. BABYLON.MorphTargetManager.Parse(managerData, scene);
  74811. }
  74812. }
  74813. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74814. meshes.push(mesh);
  74815. log += "\n\tMesh " + mesh.toString(fullDetails);
  74816. }
  74817. }
  74818. // Connecting parents
  74819. var currentMesh;
  74820. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74821. currentMesh = scene.meshes[index];
  74822. if (currentMesh._waitingParentId) {
  74823. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  74824. currentMesh._waitingParentId = null;
  74825. }
  74826. }
  74827. // freeze and compute world matrix application
  74828. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74829. currentMesh = scene.meshes[index];
  74830. if (currentMesh._waitingFreezeWorldMatrix) {
  74831. currentMesh.freezeWorldMatrix();
  74832. currentMesh._waitingFreezeWorldMatrix = null;
  74833. }
  74834. else {
  74835. currentMesh.computeWorldMatrix(true);
  74836. }
  74837. }
  74838. }
  74839. // Particles
  74840. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  74841. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  74842. if (parser) {
  74843. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  74844. var parsedParticleSystem = parsedData.particleSystems[index];
  74845. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  74846. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  74847. }
  74848. }
  74849. }
  74850. }
  74851. return true;
  74852. }
  74853. catch (err) {
  74854. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  74855. if (onError) {
  74856. onError(msg, err);
  74857. }
  74858. else {
  74859. BABYLON.Tools.Log(msg);
  74860. throw err;
  74861. }
  74862. }
  74863. finally {
  74864. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74865. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74866. }
  74867. }
  74868. return false;
  74869. },
  74870. load: function (scene, data, rootUrl, onError) {
  74871. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74872. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74873. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74874. // and avoid problems with multiple concurrent .babylon loads.
  74875. var log = "importScene has failed JSON parse";
  74876. try {
  74877. var parsedData = JSON.parse(data);
  74878. log = "";
  74879. // Scene
  74880. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  74881. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  74882. }
  74883. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  74884. scene.autoClear = parsedData.autoClear;
  74885. }
  74886. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  74887. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  74888. }
  74889. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  74890. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  74891. }
  74892. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  74893. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  74894. }
  74895. // Fog
  74896. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  74897. scene.fogMode = parsedData.fogMode;
  74898. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  74899. scene.fogStart = parsedData.fogStart;
  74900. scene.fogEnd = parsedData.fogEnd;
  74901. scene.fogDensity = parsedData.fogDensity;
  74902. log += "\tFog mode for scene: ";
  74903. switch (scene.fogMode) {
  74904. // getters not compiling, so using hardcoded
  74905. case 1:
  74906. log += "exp\n";
  74907. break;
  74908. case 2:
  74909. log += "exp2\n";
  74910. break;
  74911. case 3:
  74912. log += "linear\n";
  74913. break;
  74914. }
  74915. }
  74916. //Physics
  74917. if (parsedData.physicsEnabled) {
  74918. var physicsPlugin;
  74919. if (parsedData.physicsEngine === "cannon") {
  74920. physicsPlugin = new BABYLON.CannonJSPlugin();
  74921. }
  74922. else if (parsedData.physicsEngine === "oimo") {
  74923. physicsPlugin = new BABYLON.OimoJSPlugin();
  74924. }
  74925. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  74926. //else - default engine, which is currently oimo
  74927. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  74928. scene.enablePhysics(physicsGravity, physicsPlugin);
  74929. }
  74930. // Metadata
  74931. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  74932. scene.metadata = parsedData.metadata;
  74933. }
  74934. //collisions, if defined. otherwise, default is true
  74935. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  74936. scene.collisionsEnabled = parsedData.collisionsEnabled;
  74937. }
  74938. scene.workerCollisions = !!parsedData.workerCollisions;
  74939. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  74940. if (!container) {
  74941. return false;
  74942. }
  74943. if (parsedData.autoAnimate) {
  74944. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  74945. }
  74946. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  74947. scene.setActiveCameraByID(parsedData.activeCameraID);
  74948. }
  74949. // Environment texture
  74950. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  74951. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  74952. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  74953. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  74954. if (parsedData.environmentTextureRotationY) {
  74955. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  74956. }
  74957. scene.environmentTexture = hdrTexture;
  74958. }
  74959. else {
  74960. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  74961. if (parsedData.environmentTextureRotationY) {
  74962. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  74963. }
  74964. scene.environmentTexture = cubeTexture;
  74965. }
  74966. if (parsedData.createDefaultSkybox === true) {
  74967. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  74968. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  74969. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  74970. }
  74971. }
  74972. // Finish
  74973. return true;
  74974. }
  74975. catch (err) {
  74976. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  74977. if (onError) {
  74978. onError(msg, err);
  74979. }
  74980. else {
  74981. BABYLON.Tools.Log(msg);
  74982. throw err;
  74983. }
  74984. }
  74985. finally {
  74986. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74987. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74988. }
  74989. }
  74990. return false;
  74991. },
  74992. loadAssetContainer: function (scene, data, rootUrl, onError) {
  74993. var container = loadAssetContainer(scene, data, rootUrl, onError);
  74994. return container;
  74995. }
  74996. });
  74997. })(BABYLON || (BABYLON = {}));
  74998. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  74999. var BABYLON;
  75000. (function (BABYLON) {
  75001. var FilesInput = /** @class */ (function () {
  75002. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  75003. this.onProcessFileCallback = function () { return true; };
  75004. this._engine = engine;
  75005. this._currentScene = scene;
  75006. this._sceneLoadedCallback = sceneLoadedCallback;
  75007. this._progressCallback = progressCallback;
  75008. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  75009. this._textureLoadingCallback = textureLoadingCallback;
  75010. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  75011. this._onReloadCallback = onReloadCallback;
  75012. this._errorCallback = errorCallback;
  75013. }
  75014. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  75015. var _this = this;
  75016. if (elementToMonitor) {
  75017. this._elementToMonitor = elementToMonitor;
  75018. this._dragEnterHandler = function (e) { _this.drag(e); };
  75019. this._dragOverHandler = function (e) { _this.drag(e); };
  75020. this._dropHandler = function (e) { _this.drop(e); };
  75021. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  75022. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  75023. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  75024. }
  75025. };
  75026. FilesInput.prototype.dispose = function () {
  75027. if (!this._elementToMonitor) {
  75028. return;
  75029. }
  75030. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  75031. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  75032. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  75033. };
  75034. FilesInput.prototype.renderFunction = function () {
  75035. if (this._additionalRenderLoopLogicCallback) {
  75036. this._additionalRenderLoopLogicCallback();
  75037. }
  75038. if (this._currentScene) {
  75039. if (this._textureLoadingCallback) {
  75040. var remaining = this._currentScene.getWaitingItemsCount();
  75041. if (remaining > 0) {
  75042. this._textureLoadingCallback(remaining);
  75043. }
  75044. }
  75045. this._currentScene.render();
  75046. }
  75047. };
  75048. FilesInput.prototype.drag = function (e) {
  75049. e.stopPropagation();
  75050. e.preventDefault();
  75051. };
  75052. FilesInput.prototype.drop = function (eventDrop) {
  75053. eventDrop.stopPropagation();
  75054. eventDrop.preventDefault();
  75055. this.loadFiles(eventDrop);
  75056. };
  75057. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  75058. var _this = this;
  75059. var reader = folder.createReader();
  75060. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  75061. reader.readEntries(function (entries) {
  75062. remaining.count += entries.length;
  75063. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  75064. var entry = entries_1[_i];
  75065. if (entry.isFile) {
  75066. entry.file(function (file) {
  75067. file.correctName = relativePath + file.name;
  75068. files.push(file);
  75069. if (--remaining.count === 0) {
  75070. callback();
  75071. }
  75072. });
  75073. }
  75074. else if (entry.isDirectory) {
  75075. _this._traverseFolder(entry, files, remaining, callback);
  75076. }
  75077. }
  75078. if (--remaining.count) {
  75079. callback();
  75080. }
  75081. });
  75082. };
  75083. FilesInput.prototype._processFiles = function (files) {
  75084. for (var i = 0; i < files.length; i++) {
  75085. var name = files[i].correctName.toLowerCase();
  75086. var extension = name.split('.').pop();
  75087. if (!this.onProcessFileCallback(files[i], name, extension)) {
  75088. continue;
  75089. }
  75090. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  75091. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  75092. this._sceneFileToLoad = files[i];
  75093. }
  75094. FilesInput.FilesToLoad[name] = files[i];
  75095. }
  75096. };
  75097. FilesInput.prototype.loadFiles = function (event) {
  75098. var _this = this;
  75099. // Handling data transfer via drag'n'drop
  75100. if (event && event.dataTransfer && event.dataTransfer.files) {
  75101. this._filesToLoad = event.dataTransfer.files;
  75102. }
  75103. // Handling files from input files
  75104. if (event && event.target && event.target.files) {
  75105. this._filesToLoad = event.target.files;
  75106. }
  75107. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  75108. return;
  75109. }
  75110. if (this._startingProcessingFilesCallback) {
  75111. this._startingProcessingFilesCallback(this._filesToLoad);
  75112. }
  75113. if (this._filesToLoad && this._filesToLoad.length > 0) {
  75114. var files_1 = new Array();
  75115. var folders = [];
  75116. var items = event.dataTransfer ? event.dataTransfer.items : null;
  75117. for (var i = 0; i < this._filesToLoad.length; i++) {
  75118. var fileToLoad = this._filesToLoad[i];
  75119. var name_1 = fileToLoad.name.toLowerCase();
  75120. var entry = void 0;
  75121. fileToLoad.correctName = name_1;
  75122. if (items) {
  75123. var item = items[i];
  75124. if (item.getAsEntry) {
  75125. entry = item.getAsEntry();
  75126. }
  75127. else if (item.webkitGetAsEntry) {
  75128. entry = item.webkitGetAsEntry();
  75129. }
  75130. }
  75131. if (!entry) {
  75132. files_1.push(fileToLoad);
  75133. }
  75134. else {
  75135. if (entry.isDirectory) {
  75136. folders.push(entry);
  75137. }
  75138. else {
  75139. files_1.push(fileToLoad);
  75140. }
  75141. }
  75142. }
  75143. if (folders.length === 0) {
  75144. this._processFiles(files_1);
  75145. this._processReload();
  75146. }
  75147. else {
  75148. var remaining = { count: folders.length };
  75149. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  75150. var folder = folders_1[_i];
  75151. this._traverseFolder(folder, files_1, remaining, function () {
  75152. _this._processFiles(files_1);
  75153. if (remaining.count === 0) {
  75154. _this._processReload();
  75155. }
  75156. });
  75157. }
  75158. }
  75159. }
  75160. };
  75161. FilesInput.prototype._processReload = function () {
  75162. if (this._onReloadCallback) {
  75163. this._onReloadCallback(this._sceneFileToLoad);
  75164. }
  75165. else {
  75166. this.reload();
  75167. }
  75168. };
  75169. FilesInput.prototype.reload = function () {
  75170. var _this = this;
  75171. // If a scene file has been provided
  75172. if (this._sceneFileToLoad) {
  75173. if (this._currentScene) {
  75174. if (BABYLON.Tools.errorsCount > 0) {
  75175. BABYLON.Tools.ClearLogCache();
  75176. }
  75177. this._engine.stopRenderLoop();
  75178. }
  75179. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  75180. if (_this._progressCallback) {
  75181. _this._progressCallback(progress);
  75182. }
  75183. }).then(function (scene) {
  75184. if (_this._currentScene) {
  75185. _this._currentScene.dispose();
  75186. }
  75187. _this._currentScene = scene;
  75188. if (_this._sceneLoadedCallback) {
  75189. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  75190. }
  75191. // Wait for textures and shaders to be ready
  75192. _this._currentScene.executeWhenReady(function () {
  75193. _this._engine.runRenderLoop(function () {
  75194. _this.renderFunction();
  75195. });
  75196. });
  75197. }).catch(function (error) {
  75198. if (_this._errorCallback) {
  75199. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  75200. }
  75201. });
  75202. }
  75203. else {
  75204. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  75205. }
  75206. };
  75207. FilesInput.FilesToLoad = {};
  75208. return FilesInput;
  75209. }());
  75210. BABYLON.FilesInput = FilesInput;
  75211. })(BABYLON || (BABYLON = {}));
  75212. //# sourceMappingURL=babylon.filesInput.js.map
  75213. var BABYLON;
  75214. (function (BABYLON) {
  75215. var Tags = /** @class */ (function () {
  75216. function Tags() {
  75217. }
  75218. Tags.EnableFor = function (obj) {
  75219. obj._tags = obj._tags || {};
  75220. obj.hasTags = function () {
  75221. return Tags.HasTags(obj);
  75222. };
  75223. obj.addTags = function (tagsString) {
  75224. return Tags.AddTagsTo(obj, tagsString);
  75225. };
  75226. obj.removeTags = function (tagsString) {
  75227. return Tags.RemoveTagsFrom(obj, tagsString);
  75228. };
  75229. obj.matchesTagsQuery = function (tagsQuery) {
  75230. return Tags.MatchesQuery(obj, tagsQuery);
  75231. };
  75232. };
  75233. Tags.DisableFor = function (obj) {
  75234. delete obj._tags;
  75235. delete obj.hasTags;
  75236. delete obj.addTags;
  75237. delete obj.removeTags;
  75238. delete obj.matchesTagsQuery;
  75239. };
  75240. Tags.HasTags = function (obj) {
  75241. if (!obj._tags) {
  75242. return false;
  75243. }
  75244. return !BABYLON.Tools.IsEmpty(obj._tags);
  75245. };
  75246. Tags.GetTags = function (obj, asString) {
  75247. if (asString === void 0) { asString = true; }
  75248. if (!obj._tags) {
  75249. return null;
  75250. }
  75251. if (asString) {
  75252. var tagsArray = [];
  75253. for (var tag in obj._tags) {
  75254. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  75255. tagsArray.push(tag);
  75256. }
  75257. }
  75258. return tagsArray.join(" ");
  75259. }
  75260. else {
  75261. return obj._tags;
  75262. }
  75263. };
  75264. // the tags 'true' and 'false' are reserved and cannot be used as tags
  75265. // a tag cannot start with '||', '&&', and '!'
  75266. // it cannot contain whitespaces
  75267. Tags.AddTagsTo = function (obj, tagsString) {
  75268. if (!tagsString) {
  75269. return;
  75270. }
  75271. if (typeof tagsString !== "string") {
  75272. return;
  75273. }
  75274. var tags = tagsString.split(" ");
  75275. tags.forEach(function (tag, index, array) {
  75276. Tags._AddTagTo(obj, tag);
  75277. });
  75278. };
  75279. Tags._AddTagTo = function (obj, tag) {
  75280. tag = tag.trim();
  75281. if (tag === "" || tag === "true" || tag === "false") {
  75282. return;
  75283. }
  75284. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  75285. return;
  75286. }
  75287. Tags.EnableFor(obj);
  75288. obj._tags[tag] = true;
  75289. };
  75290. Tags.RemoveTagsFrom = function (obj, tagsString) {
  75291. if (!Tags.HasTags(obj)) {
  75292. return;
  75293. }
  75294. var tags = tagsString.split(" ");
  75295. for (var t in tags) {
  75296. Tags._RemoveTagFrom(obj, tags[t]);
  75297. }
  75298. };
  75299. Tags._RemoveTagFrom = function (obj, tag) {
  75300. delete obj._tags[tag];
  75301. };
  75302. Tags.MatchesQuery = function (obj, tagsQuery) {
  75303. if (tagsQuery === undefined) {
  75304. return true;
  75305. }
  75306. if (tagsQuery === "") {
  75307. return Tags.HasTags(obj);
  75308. }
  75309. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  75310. };
  75311. return Tags;
  75312. }());
  75313. BABYLON.Tags = Tags;
  75314. })(BABYLON || (BABYLON = {}));
  75315. //# sourceMappingURL=babylon.tags.js.map
  75316. var BABYLON;
  75317. (function (BABYLON) {
  75318. /**
  75319. * Class used to evalaute queries containing `and` and `or` operators
  75320. */
  75321. var AndOrNotEvaluator = /** @class */ (function () {
  75322. function AndOrNotEvaluator() {
  75323. }
  75324. /**
  75325. * Evaluate a query
  75326. * @param query defines the query to evaluate
  75327. * @param evaluateCallback defines the callback used to filter result
  75328. * @returns true if the query matches
  75329. */
  75330. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  75331. if (!query.match(/\([^\(\)]*\)/g)) {
  75332. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  75333. }
  75334. else {
  75335. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  75336. // remove parenthesis
  75337. r = r.slice(1, r.length - 1);
  75338. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  75339. });
  75340. }
  75341. if (query === "true") {
  75342. return true;
  75343. }
  75344. if (query === "false") {
  75345. return false;
  75346. }
  75347. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  75348. };
  75349. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  75350. evaluateCallback = evaluateCallback || (function (r) {
  75351. return r === "true" ? true : false;
  75352. });
  75353. var result;
  75354. var or = parenthesisContent.split("||");
  75355. for (var i in or) {
  75356. if (or.hasOwnProperty(i)) {
  75357. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  75358. var and = ori.split("&&");
  75359. if (and.length > 1) {
  75360. for (var j = 0; j < and.length; ++j) {
  75361. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  75362. if (andj !== "true" && andj !== "false") {
  75363. if (andj[0] === "!") {
  75364. result = !evaluateCallback(andj.substring(1));
  75365. }
  75366. else {
  75367. result = evaluateCallback(andj);
  75368. }
  75369. }
  75370. else {
  75371. result = andj === "true" ? true : false;
  75372. }
  75373. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  75374. ori = "false";
  75375. break;
  75376. }
  75377. }
  75378. }
  75379. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  75380. result = true;
  75381. break;
  75382. }
  75383. // result equals false (or undefined)
  75384. if (ori !== "true" && ori !== "false") {
  75385. if (ori[0] === "!") {
  75386. result = !evaluateCallback(ori.substring(1));
  75387. }
  75388. else {
  75389. result = evaluateCallback(ori);
  75390. }
  75391. }
  75392. else {
  75393. result = ori === "true" ? true : false;
  75394. }
  75395. }
  75396. }
  75397. // the whole parenthesis scope is replaced by 'true' or 'false'
  75398. return result ? "true" : "false";
  75399. };
  75400. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  75401. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  75402. // remove whitespaces
  75403. r = r.replace(/[\s]/g, function () { return ""; });
  75404. return r.length % 2 ? "!" : "";
  75405. });
  75406. booleanString = booleanString.trim();
  75407. if (booleanString === "!true") {
  75408. booleanString = "false";
  75409. }
  75410. else if (booleanString === "!false") {
  75411. booleanString = "true";
  75412. }
  75413. return booleanString;
  75414. };
  75415. return AndOrNotEvaluator;
  75416. }());
  75417. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  75418. })(BABYLON || (BABYLON = {}));
  75419. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  75420. var BABYLON;
  75421. (function (BABYLON) {
  75422. /**
  75423. * Class used to enable access to IndexedDB
  75424. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  75425. */
  75426. var Database = /** @class */ (function () {
  75427. /**
  75428. * Creates a new Database
  75429. * @param urlToScene defines the url to load the scene
  75430. * @param callbackManifestChecked defines the callback to use when manifest is checked
  75431. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  75432. */
  75433. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  75434. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  75435. var _this = this;
  75436. // Handling various flavors of prefixed version of IndexedDB
  75437. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  75438. this.callbackManifestChecked = callbackManifestChecked;
  75439. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  75440. this.db = null;
  75441. this._enableSceneOffline = false;
  75442. this._enableTexturesOffline = false;
  75443. this.manifestVersionFound = 0;
  75444. this.mustUpdateRessources = false;
  75445. this.hasReachedQuota = false;
  75446. if (!Database.IDBStorageEnabled) {
  75447. this.callbackManifestChecked(true);
  75448. }
  75449. else {
  75450. if (disableManifestCheck) {
  75451. this._enableSceneOffline = true;
  75452. this._enableTexturesOffline = true;
  75453. this.manifestVersionFound = 1;
  75454. BABYLON.Tools.SetImmediate(function () {
  75455. _this.callbackManifestChecked(true);
  75456. });
  75457. }
  75458. else {
  75459. this._checkManifestFile();
  75460. }
  75461. }
  75462. }
  75463. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  75464. /**
  75465. * Gets a boolean indicating if scene must be saved in the database
  75466. */
  75467. get: function () {
  75468. return this._enableSceneOffline;
  75469. },
  75470. enumerable: true,
  75471. configurable: true
  75472. });
  75473. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  75474. /**
  75475. * Gets a boolean indicating if textures must be saved in the database
  75476. */
  75477. get: function () {
  75478. return this._enableTexturesOffline;
  75479. },
  75480. enumerable: true,
  75481. configurable: true
  75482. });
  75483. Database.prototype._checkManifestFile = function () {
  75484. var _this = this;
  75485. var noManifestFile = function () {
  75486. _this._enableSceneOffline = false;
  75487. _this._enableTexturesOffline = false;
  75488. _this.callbackManifestChecked(false);
  75489. };
  75490. var timeStampUsed = false;
  75491. var manifestURL = this.currentSceneUrl + ".manifest";
  75492. var xhr = new XMLHttpRequest();
  75493. if (navigator.onLine) {
  75494. // Adding a timestamp to by-pass browsers' cache
  75495. timeStampUsed = true;
  75496. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  75497. }
  75498. xhr.open("GET", manifestURL, true);
  75499. xhr.addEventListener("load", function () {
  75500. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  75501. try {
  75502. var manifestFile = JSON.parse(xhr.response);
  75503. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  75504. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  75505. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  75506. _this.manifestVersionFound = manifestFile.version;
  75507. }
  75508. if (_this.callbackManifestChecked) {
  75509. _this.callbackManifestChecked(true);
  75510. }
  75511. }
  75512. catch (ex) {
  75513. noManifestFile();
  75514. }
  75515. }
  75516. else {
  75517. noManifestFile();
  75518. }
  75519. }, false);
  75520. xhr.addEventListener("error", function (event) {
  75521. if (timeStampUsed) {
  75522. timeStampUsed = false;
  75523. // Let's retry without the timeStamp
  75524. // It could fail when coupled with HTML5 Offline API
  75525. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  75526. xhr.open("GET", retryManifestURL, true);
  75527. xhr.send();
  75528. }
  75529. else {
  75530. noManifestFile();
  75531. }
  75532. }, false);
  75533. try {
  75534. xhr.send();
  75535. }
  75536. catch (ex) {
  75537. BABYLON.Tools.Error("Error on XHR send request.");
  75538. this.callbackManifestChecked(false);
  75539. }
  75540. };
  75541. /**
  75542. * Open the database and make it available
  75543. * @param successCallback defines the callback to call on success
  75544. * @param errorCallback defines the callback to call on error
  75545. */
  75546. Database.prototype.openAsync = function (successCallback, errorCallback) {
  75547. var _this = this;
  75548. var handleError = function () {
  75549. _this.isSupported = false;
  75550. if (errorCallback)
  75551. errorCallback();
  75552. };
  75553. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  75554. // Your browser doesn't support IndexedDB
  75555. this.isSupported = false;
  75556. if (errorCallback)
  75557. errorCallback();
  75558. }
  75559. else {
  75560. // If the DB hasn't been opened or created yet
  75561. if (!this.db) {
  75562. this.hasReachedQuota = false;
  75563. this.isSupported = true;
  75564. var request = this.idbFactory.open("babylonjs", 1);
  75565. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  75566. request.onerror = function (event) {
  75567. handleError();
  75568. };
  75569. // executes when a version change transaction cannot complete due to other active transactions
  75570. request.onblocked = function (event) {
  75571. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  75572. handleError();
  75573. };
  75574. // DB has been opened successfully
  75575. request.onsuccess = function (event) {
  75576. _this.db = request.result;
  75577. successCallback();
  75578. };
  75579. // Initialization of the DB. Creating Scenes & Textures stores
  75580. request.onupgradeneeded = function (event) {
  75581. _this.db = (event.target).result;
  75582. if (_this.db) {
  75583. try {
  75584. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  75585. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  75586. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  75587. }
  75588. catch (ex) {
  75589. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  75590. handleError();
  75591. }
  75592. }
  75593. };
  75594. }
  75595. // DB has already been created and opened
  75596. else {
  75597. if (successCallback)
  75598. successCallback();
  75599. }
  75600. }
  75601. };
  75602. /**
  75603. * Loads an image from the database
  75604. * @param url defines the url to load from
  75605. * @param image defines the target DOM image
  75606. */
  75607. Database.prototype.loadImageFromDB = function (url, image) {
  75608. var _this = this;
  75609. var completeURL = Database._ReturnFullUrlLocation(url);
  75610. var saveAndLoadImage = function () {
  75611. if (!_this.hasReachedQuota && _this.db !== null) {
  75612. // the texture is not yet in the DB, let's try to save it
  75613. _this._saveImageIntoDBAsync(completeURL, image);
  75614. }
  75615. // If the texture is not in the DB and we've reached the DB quota limit
  75616. // let's load it directly from the web
  75617. else {
  75618. image.src = url;
  75619. }
  75620. };
  75621. if (!this.mustUpdateRessources) {
  75622. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  75623. }
  75624. // First time we're download the images or update requested in the manifest file by a version change
  75625. else {
  75626. saveAndLoadImage();
  75627. }
  75628. };
  75629. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  75630. if (this.isSupported && this.db !== null) {
  75631. var texture;
  75632. var transaction = this.db.transaction(["textures"]);
  75633. transaction.onabort = function (event) {
  75634. image.src = url;
  75635. };
  75636. transaction.oncomplete = function (event) {
  75637. var blobTextureURL;
  75638. if (texture) {
  75639. var URL = window.URL || window.webkitURL;
  75640. blobTextureURL = URL.createObjectURL(texture.data);
  75641. image.onerror = function () {
  75642. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  75643. image.src = url;
  75644. };
  75645. image.src = blobTextureURL;
  75646. }
  75647. else {
  75648. notInDBCallback();
  75649. }
  75650. };
  75651. var getRequest = transaction.objectStore("textures").get(url);
  75652. getRequest.onsuccess = function (event) {
  75653. texture = (event.target).result;
  75654. };
  75655. getRequest.onerror = function (event) {
  75656. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  75657. image.src = url;
  75658. };
  75659. }
  75660. else {
  75661. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75662. image.src = url;
  75663. }
  75664. };
  75665. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  75666. var _this = this;
  75667. if (this.isSupported) {
  75668. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  75669. var generateBlobUrl = function () {
  75670. var blobTextureURL;
  75671. if (blob) {
  75672. var URL = window.URL || window.webkitURL;
  75673. try {
  75674. blobTextureURL = URL.createObjectURL(blob);
  75675. }
  75676. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  75677. catch (ex) {
  75678. blobTextureURL = URL.createObjectURL(blob);
  75679. }
  75680. }
  75681. if (blobTextureURL) {
  75682. image.src = blobTextureURL;
  75683. }
  75684. };
  75685. if (Database.IsUASupportingBlobStorage) { // Create XHR
  75686. var xhr = new XMLHttpRequest(), blob;
  75687. xhr.open("GET", url, true);
  75688. xhr.responseType = "blob";
  75689. xhr.addEventListener("load", function () {
  75690. if (xhr.status === 200 && _this.db) {
  75691. // Blob as response (XHR2)
  75692. blob = xhr.response;
  75693. var transaction = _this.db.transaction(["textures"], "readwrite");
  75694. // the transaction could abort because of a QuotaExceededError error
  75695. transaction.onabort = function (event) {
  75696. try {
  75697. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75698. var srcElement = (event.srcElement || event.target);
  75699. var error = srcElement.error;
  75700. if (error && error.name === "QuotaExceededError") {
  75701. _this.hasReachedQuota = true;
  75702. }
  75703. }
  75704. catch (ex) { }
  75705. generateBlobUrl();
  75706. };
  75707. transaction.oncomplete = function (event) {
  75708. generateBlobUrl();
  75709. };
  75710. var newTexture = { textureUrl: url, data: blob };
  75711. try {
  75712. // Put the blob into the dabase
  75713. var addRequest = transaction.objectStore("textures").put(newTexture);
  75714. addRequest.onsuccess = function (event) {
  75715. };
  75716. addRequest.onerror = function (event) {
  75717. generateBlobUrl();
  75718. };
  75719. }
  75720. catch (ex) {
  75721. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  75722. if (ex.code === 25) {
  75723. Database.IsUASupportingBlobStorage = false;
  75724. }
  75725. image.src = url;
  75726. }
  75727. }
  75728. else {
  75729. image.src = url;
  75730. }
  75731. }, false);
  75732. xhr.addEventListener("error", function (event) {
  75733. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  75734. image.src = url;
  75735. }, false);
  75736. xhr.send();
  75737. }
  75738. else {
  75739. image.src = url;
  75740. }
  75741. }
  75742. else {
  75743. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75744. image.src = url;
  75745. }
  75746. };
  75747. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  75748. var _this = this;
  75749. var updateVersion = function () {
  75750. // the version is not yet in the DB or we need to update it
  75751. _this._saveVersionIntoDBAsync(url, versionLoaded);
  75752. };
  75753. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  75754. };
  75755. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  75756. var _this = this;
  75757. if (this.isSupported && this.db) {
  75758. var version;
  75759. try {
  75760. var transaction = this.db.transaction(["versions"]);
  75761. transaction.oncomplete = function (event) {
  75762. if (version) {
  75763. // If the version in the JSON file is different from the version in DB
  75764. if (_this.manifestVersionFound !== version.data) {
  75765. _this.mustUpdateRessources = true;
  75766. updateInDBCallback();
  75767. }
  75768. else {
  75769. callback(version.data);
  75770. }
  75771. }
  75772. // version was not found in DB
  75773. else {
  75774. _this.mustUpdateRessources = true;
  75775. updateInDBCallback();
  75776. }
  75777. };
  75778. transaction.onabort = function (event) {
  75779. callback(-1);
  75780. };
  75781. var getRequest = transaction.objectStore("versions").get(url);
  75782. getRequest.onsuccess = function (event) {
  75783. version = (event.target).result;
  75784. };
  75785. getRequest.onerror = function (event) {
  75786. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  75787. callback(-1);
  75788. };
  75789. }
  75790. catch (ex) {
  75791. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  75792. callback(-1);
  75793. }
  75794. }
  75795. else {
  75796. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75797. callback(-1);
  75798. }
  75799. };
  75800. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  75801. var _this = this;
  75802. if (this.isSupported && !this.hasReachedQuota && this.db) {
  75803. try {
  75804. // Open a transaction to the database
  75805. var transaction = this.db.transaction(["versions"], "readwrite");
  75806. // the transaction could abort because of a QuotaExceededError error
  75807. transaction.onabort = function (event) {
  75808. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75809. var error = event.srcElement['error'];
  75810. if (error && error.name === "QuotaExceededError") {
  75811. _this.hasReachedQuota = true;
  75812. }
  75813. }
  75814. catch (ex) { }
  75815. callback(-1);
  75816. };
  75817. transaction.oncomplete = function (event) {
  75818. callback(_this.manifestVersionFound);
  75819. };
  75820. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  75821. // Put the scene into the database
  75822. var addRequest = transaction.objectStore("versions").put(newVersion);
  75823. addRequest.onsuccess = function (event) {
  75824. };
  75825. addRequest.onerror = function (event) {
  75826. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  75827. };
  75828. }
  75829. catch (ex) {
  75830. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  75831. callback(-1);
  75832. }
  75833. }
  75834. else {
  75835. callback(-1);
  75836. }
  75837. };
  75838. /**
  75839. * Loads a file from database
  75840. * @param url defines the URL to load from
  75841. * @param sceneLoaded defines a callback to call on success
  75842. * @param progressCallBack defines a callback to call when progress changed
  75843. * @param errorCallback defines a callback to call on error
  75844. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  75845. */
  75846. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  75847. var _this = this;
  75848. var completeUrl = Database._ReturnFullUrlLocation(url);
  75849. var saveAndLoadFile = function () {
  75850. // the scene is not yet in the DB, let's try to save it
  75851. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75852. };
  75853. this._checkVersionFromDB(completeUrl, function (version) {
  75854. if (version !== -1) {
  75855. if (!_this.mustUpdateRessources) {
  75856. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  75857. }
  75858. else {
  75859. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75860. }
  75861. }
  75862. else {
  75863. if (errorCallback) {
  75864. errorCallback();
  75865. }
  75866. }
  75867. });
  75868. };
  75869. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  75870. if (this.isSupported && this.db) {
  75871. var targetStore;
  75872. if (url.indexOf(".babylon") !== -1) {
  75873. targetStore = "scenes";
  75874. }
  75875. else {
  75876. targetStore = "textures";
  75877. }
  75878. var file;
  75879. var transaction = this.db.transaction([targetStore]);
  75880. transaction.oncomplete = function (event) {
  75881. if (file) {
  75882. callback(file.data);
  75883. }
  75884. // file was not found in DB
  75885. else {
  75886. notInDBCallback();
  75887. }
  75888. };
  75889. transaction.onabort = function (event) {
  75890. notInDBCallback();
  75891. };
  75892. var getRequest = transaction.objectStore(targetStore).get(url);
  75893. getRequest.onsuccess = function (event) {
  75894. file = (event.target).result;
  75895. };
  75896. getRequest.onerror = function (event) {
  75897. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  75898. notInDBCallback();
  75899. };
  75900. }
  75901. else {
  75902. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75903. callback();
  75904. }
  75905. };
  75906. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  75907. var _this = this;
  75908. if (this.isSupported) {
  75909. var targetStore;
  75910. if (url.indexOf(".babylon") !== -1) {
  75911. targetStore = "scenes";
  75912. }
  75913. else {
  75914. targetStore = "textures";
  75915. }
  75916. // Create XHR
  75917. var xhr = new XMLHttpRequest();
  75918. var fileData;
  75919. xhr.open("GET", url + "?" + Date.now(), true);
  75920. if (useArrayBuffer) {
  75921. xhr.responseType = "arraybuffer";
  75922. }
  75923. if (progressCallback) {
  75924. xhr.onprogress = progressCallback;
  75925. }
  75926. xhr.addEventListener("load", function () {
  75927. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  75928. // Blob as response (XHR2)
  75929. //fileData = xhr.responseText;
  75930. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  75931. if (!_this.hasReachedQuota && _this.db) {
  75932. // Open a transaction to the database
  75933. var transaction = _this.db.transaction([targetStore], "readwrite");
  75934. // the transaction could abort because of a QuotaExceededError error
  75935. transaction.onabort = function (event) {
  75936. try {
  75937. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75938. var error = event.srcElement['error'];
  75939. if (error && error.name === "QuotaExceededError") {
  75940. _this.hasReachedQuota = true;
  75941. }
  75942. }
  75943. catch (ex) { }
  75944. callback(fileData);
  75945. };
  75946. transaction.oncomplete = function (event) {
  75947. callback(fileData);
  75948. };
  75949. var newFile;
  75950. if (targetStore === "scenes") {
  75951. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  75952. }
  75953. else {
  75954. newFile = { textureUrl: url, data: fileData };
  75955. }
  75956. try {
  75957. // Put the scene into the database
  75958. var addRequest = transaction.objectStore(targetStore).put(newFile);
  75959. addRequest.onsuccess = function (event) {
  75960. };
  75961. addRequest.onerror = function (event) {
  75962. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  75963. };
  75964. }
  75965. catch (ex) {
  75966. callback(fileData);
  75967. }
  75968. }
  75969. else {
  75970. callback(fileData);
  75971. }
  75972. }
  75973. else {
  75974. if (xhr.status >= 400 && errorCallback) {
  75975. errorCallback(xhr);
  75976. }
  75977. else {
  75978. callback();
  75979. }
  75980. }
  75981. }, false);
  75982. xhr.addEventListener("error", function (event) {
  75983. BABYLON.Tools.Error("error on XHR request.");
  75984. callback();
  75985. }, false);
  75986. xhr.send();
  75987. }
  75988. else {
  75989. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75990. callback();
  75991. }
  75992. };
  75993. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  75994. Database.IsUASupportingBlobStorage = true;
  75995. /** Gets a boolean indicating if Database storate is enabled */
  75996. Database.IDBStorageEnabled = true;
  75997. Database._ParseURL = function (url) {
  75998. var a = document.createElement('a');
  75999. a.href = url;
  76000. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  76001. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  76002. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  76003. return absLocation;
  76004. };
  76005. Database._ReturnFullUrlLocation = function (url) {
  76006. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  76007. return (Database._ParseURL(window.location.href) + url);
  76008. }
  76009. else {
  76010. return url;
  76011. }
  76012. };
  76013. return Database;
  76014. }());
  76015. BABYLON.Database = Database;
  76016. })(BABYLON || (BABYLON = {}));
  76017. //# sourceMappingURL=babylon.database.js.map
  76018. var BABYLON;
  76019. (function (BABYLON) {
  76020. var FresnelParameters = /** @class */ (function () {
  76021. function FresnelParameters() {
  76022. this._isEnabled = true;
  76023. this.leftColor = BABYLON.Color3.White();
  76024. this.rightColor = BABYLON.Color3.Black();
  76025. this.bias = 0;
  76026. this.power = 1;
  76027. }
  76028. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  76029. get: function () {
  76030. return this._isEnabled;
  76031. },
  76032. set: function (value) {
  76033. if (this._isEnabled === value) {
  76034. return;
  76035. }
  76036. this._isEnabled = value;
  76037. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  76038. },
  76039. enumerable: true,
  76040. configurable: true
  76041. });
  76042. FresnelParameters.prototype.clone = function () {
  76043. var newFresnelParameters = new FresnelParameters();
  76044. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  76045. return newFresnelParameters;
  76046. };
  76047. FresnelParameters.prototype.serialize = function () {
  76048. var serializationObject = {};
  76049. serializationObject.isEnabled = this.isEnabled;
  76050. serializationObject.leftColor = this.leftColor.asArray();
  76051. serializationObject.rightColor = this.rightColor.asArray();
  76052. serializationObject.bias = this.bias;
  76053. serializationObject.power = this.power;
  76054. return serializationObject;
  76055. };
  76056. FresnelParameters.Parse = function (parsedFresnelParameters) {
  76057. var fresnelParameters = new FresnelParameters();
  76058. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  76059. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  76060. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  76061. fresnelParameters.bias = parsedFresnelParameters.bias;
  76062. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  76063. return fresnelParameters;
  76064. };
  76065. return FresnelParameters;
  76066. }());
  76067. BABYLON.FresnelParameters = FresnelParameters;
  76068. })(BABYLON || (BABYLON = {}));
  76069. //# sourceMappingURL=babylon.fresnelParameters.js.map
  76070. var BABYLON;
  76071. (function (BABYLON) {
  76072. var MultiMaterial = /** @class */ (function (_super) {
  76073. __extends(MultiMaterial, _super);
  76074. function MultiMaterial(name, scene) {
  76075. var _this = _super.call(this, name, scene, true) || this;
  76076. scene.multiMaterials.push(_this);
  76077. _this.subMaterials = new Array();
  76078. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  76079. return _this;
  76080. }
  76081. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  76082. get: function () {
  76083. return this._subMaterials;
  76084. },
  76085. set: function (value) {
  76086. this._subMaterials = value;
  76087. this._hookArray(value);
  76088. },
  76089. enumerable: true,
  76090. configurable: true
  76091. });
  76092. MultiMaterial.prototype._hookArray = function (array) {
  76093. var _this = this;
  76094. var oldPush = array.push;
  76095. array.push = function () {
  76096. var items = [];
  76097. for (var _i = 0; _i < arguments.length; _i++) {
  76098. items[_i] = arguments[_i];
  76099. }
  76100. var result = oldPush.apply(array, items);
  76101. _this._markAllSubMeshesAsTexturesDirty();
  76102. return result;
  76103. };
  76104. var oldSplice = array.splice;
  76105. array.splice = function (index, deleteCount) {
  76106. var deleted = oldSplice.apply(array, [index, deleteCount]);
  76107. _this._markAllSubMeshesAsTexturesDirty();
  76108. return deleted;
  76109. };
  76110. };
  76111. // Properties
  76112. MultiMaterial.prototype.getSubMaterial = function (index) {
  76113. if (index < 0 || index >= this.subMaterials.length) {
  76114. return this.getScene().defaultMaterial;
  76115. }
  76116. return this.subMaterials[index];
  76117. };
  76118. MultiMaterial.prototype.getActiveTextures = function () {
  76119. var _a;
  76120. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  76121. if (subMaterial) {
  76122. return subMaterial.getActiveTextures();
  76123. }
  76124. else {
  76125. return [];
  76126. }
  76127. }));
  76128. };
  76129. // Methods
  76130. MultiMaterial.prototype.getClassName = function () {
  76131. return "MultiMaterial";
  76132. };
  76133. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  76134. for (var index = 0; index < this.subMaterials.length; index++) {
  76135. var subMaterial = this.subMaterials[index];
  76136. if (subMaterial) {
  76137. if (subMaterial.storeEffectOnSubMeshes) {
  76138. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  76139. return false;
  76140. }
  76141. continue;
  76142. }
  76143. if (!subMaterial.isReady(mesh)) {
  76144. return false;
  76145. }
  76146. }
  76147. }
  76148. return true;
  76149. };
  76150. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  76151. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  76152. for (var index = 0; index < this.subMaterials.length; index++) {
  76153. var subMaterial = null;
  76154. var current = this.subMaterials[index];
  76155. if (cloneChildren && current) {
  76156. subMaterial = current.clone(name + "-" + current.name);
  76157. }
  76158. else {
  76159. subMaterial = this.subMaterials[index];
  76160. }
  76161. newMultiMaterial.subMaterials.push(subMaterial);
  76162. }
  76163. return newMultiMaterial;
  76164. };
  76165. MultiMaterial.prototype.serialize = function () {
  76166. var serializationObject = {};
  76167. serializationObject.name = this.name;
  76168. serializationObject.id = this.id;
  76169. if (BABYLON.Tags) {
  76170. serializationObject.tags = BABYLON.Tags.GetTags(this);
  76171. }
  76172. serializationObject.materials = [];
  76173. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  76174. var subMat = this.subMaterials[matIndex];
  76175. if (subMat) {
  76176. serializationObject.materials.push(subMat.id);
  76177. }
  76178. else {
  76179. serializationObject.materials.push(null);
  76180. }
  76181. }
  76182. return serializationObject;
  76183. };
  76184. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  76185. var scene = this.getScene();
  76186. if (!scene) {
  76187. return;
  76188. }
  76189. var index = scene.multiMaterials.indexOf(this);
  76190. if (index >= 0) {
  76191. scene.multiMaterials.splice(index, 1);
  76192. }
  76193. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  76194. };
  76195. return MultiMaterial;
  76196. }(BABYLON.Material));
  76197. BABYLON.MultiMaterial = MultiMaterial;
  76198. })(BABYLON || (BABYLON = {}));
  76199. //# sourceMappingURL=babylon.multiMaterial.js.map
  76200. var BABYLON;
  76201. (function (BABYLON) {
  76202. /**
  76203. * Manage the touch inputs to control the movement of a free camera.
  76204. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76205. */
  76206. var FreeCameraTouchInput = /** @class */ (function () {
  76207. function FreeCameraTouchInput() {
  76208. /**
  76209. * Defines the touch sensibility for rotation.
  76210. * The higher the faster.
  76211. */
  76212. this.touchAngularSensibility = 200000.0;
  76213. /**
  76214. * Defines the touch sensibility for move.
  76215. * The higher the faster.
  76216. */
  76217. this.touchMoveSensibility = 250.0;
  76218. this._offsetX = null;
  76219. this._offsetY = null;
  76220. this._pointerPressed = new Array();
  76221. }
  76222. /**
  76223. * Attach the input controls to a specific dom element to get the input from.
  76224. * @param element Defines the element the controls should be listened from
  76225. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76226. */
  76227. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  76228. var _this = this;
  76229. var previousPosition = null;
  76230. if (this._pointerInput === undefined) {
  76231. this._onLostFocus = function (evt) {
  76232. _this._offsetX = null;
  76233. _this._offsetY = null;
  76234. };
  76235. this._pointerInput = function (p, s) {
  76236. var evt = p.event;
  76237. if (evt.pointerType === "mouse") {
  76238. return;
  76239. }
  76240. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  76241. if (!noPreventDefault) {
  76242. evt.preventDefault();
  76243. }
  76244. _this._pointerPressed.push(evt.pointerId);
  76245. if (_this._pointerPressed.length !== 1) {
  76246. return;
  76247. }
  76248. previousPosition = {
  76249. x: evt.clientX,
  76250. y: evt.clientY
  76251. };
  76252. }
  76253. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  76254. if (!noPreventDefault) {
  76255. evt.preventDefault();
  76256. }
  76257. var index = _this._pointerPressed.indexOf(evt.pointerId);
  76258. if (index === -1) {
  76259. return;
  76260. }
  76261. _this._pointerPressed.splice(index, 1);
  76262. if (index != 0) {
  76263. return;
  76264. }
  76265. previousPosition = null;
  76266. _this._offsetX = null;
  76267. _this._offsetY = null;
  76268. }
  76269. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  76270. if (!noPreventDefault) {
  76271. evt.preventDefault();
  76272. }
  76273. if (!previousPosition) {
  76274. return;
  76275. }
  76276. var index = _this._pointerPressed.indexOf(evt.pointerId);
  76277. if (index != 0) {
  76278. return;
  76279. }
  76280. _this._offsetX = evt.clientX - previousPosition.x;
  76281. _this._offsetY = -(evt.clientY - previousPosition.y);
  76282. }
  76283. };
  76284. }
  76285. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  76286. if (this._onLostFocus) {
  76287. element.addEventListener("blur", this._onLostFocus);
  76288. }
  76289. };
  76290. /**
  76291. * Detach the current controls from the specified dom element.
  76292. * @param element Defines the element to stop listening the inputs from
  76293. */
  76294. FreeCameraTouchInput.prototype.detachControl = function (element) {
  76295. if (this._pointerInput && element) {
  76296. if (this._observer) {
  76297. this.camera.getScene().onPointerObservable.remove(this._observer);
  76298. this._observer = null;
  76299. }
  76300. if (this._onLostFocus) {
  76301. element.removeEventListener("blur", this._onLostFocus);
  76302. this._onLostFocus = null;
  76303. }
  76304. this._pointerPressed = [];
  76305. this._offsetX = null;
  76306. this._offsetY = null;
  76307. }
  76308. };
  76309. /**
  76310. * Update the current camera state depending on the inputs that have been used this frame.
  76311. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76312. */
  76313. FreeCameraTouchInput.prototype.checkInputs = function () {
  76314. if (this._offsetX && this._offsetY) {
  76315. var camera = this.camera;
  76316. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  76317. if (this._pointerPressed.length > 1) {
  76318. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  76319. }
  76320. else {
  76321. var speed = camera._computeLocalCameraSpeed();
  76322. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  76323. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  76324. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  76325. }
  76326. }
  76327. };
  76328. /**
  76329. * Gets the class name of the current intput.
  76330. * @returns the class name
  76331. */
  76332. FreeCameraTouchInput.prototype.getClassName = function () {
  76333. return "FreeCameraTouchInput";
  76334. };
  76335. /**
  76336. * Get the friendly name associated with the input class.
  76337. * @returns the input friendly name
  76338. */
  76339. FreeCameraTouchInput.prototype.getSimpleName = function () {
  76340. return "touch";
  76341. };
  76342. __decorate([
  76343. BABYLON.serialize()
  76344. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  76345. __decorate([
  76346. BABYLON.serialize()
  76347. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  76348. return FreeCameraTouchInput;
  76349. }());
  76350. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  76351. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  76352. })(BABYLON || (BABYLON = {}));
  76353. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  76354. var BABYLON;
  76355. (function (BABYLON) {
  76356. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  76357. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  76358. });
  76359. /**
  76360. * This represents a FPS type of camera controlled by touch.
  76361. * This is like a universal camera minus the Gamepad controls.
  76362. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76363. */
  76364. var TouchCamera = /** @class */ (function (_super) {
  76365. __extends(TouchCamera, _super);
  76366. /**
  76367. * Instantiates a new touch camera.
  76368. * This represents a FPS type of camera controlled by touch.
  76369. * This is like a universal camera minus the Gamepad controls.
  76370. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76371. * @param name Define the name of the camera in the scene
  76372. * @param position Define the start position of the camera in the scene
  76373. * @param scene Define the scene the camera belongs to
  76374. */
  76375. function TouchCamera(name, position, scene) {
  76376. var _this = _super.call(this, name, position, scene) || this;
  76377. _this.inputs.addTouch();
  76378. _this._setupInputs();
  76379. return _this;
  76380. }
  76381. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  76382. /**
  76383. * Defines the touch sensibility for rotation.
  76384. * The higher the faster.
  76385. */
  76386. get: function () {
  76387. var touch = this.inputs.attached["touch"];
  76388. if (touch)
  76389. return touch.touchAngularSensibility;
  76390. return 0;
  76391. },
  76392. set: function (value) {
  76393. var touch = this.inputs.attached["touch"];
  76394. if (touch)
  76395. touch.touchAngularSensibility = value;
  76396. },
  76397. enumerable: true,
  76398. configurable: true
  76399. });
  76400. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  76401. /**
  76402. * Defines the touch sensibility for move.
  76403. * The higher the faster.
  76404. */
  76405. get: function () {
  76406. var touch = this.inputs.attached["touch"];
  76407. if (touch)
  76408. return touch.touchMoveSensibility;
  76409. return 0;
  76410. },
  76411. set: function (value) {
  76412. var touch = this.inputs.attached["touch"];
  76413. if (touch)
  76414. touch.touchMoveSensibility = value;
  76415. },
  76416. enumerable: true,
  76417. configurable: true
  76418. });
  76419. /**
  76420. * Gets the current object class name.
  76421. * @return the class name
  76422. */
  76423. TouchCamera.prototype.getClassName = function () {
  76424. return "TouchCamera";
  76425. };
  76426. /** @hidden */
  76427. TouchCamera.prototype._setupInputs = function () {
  76428. var mouse = this.inputs.attached["mouse"];
  76429. if (mouse) {
  76430. mouse.touchEnabled = false;
  76431. }
  76432. };
  76433. return TouchCamera;
  76434. }(BABYLON.FreeCamera));
  76435. BABYLON.TouchCamera = TouchCamera;
  76436. })(BABYLON || (BABYLON = {}));
  76437. //# sourceMappingURL=babylon.touchCamera.js.map
  76438. var BABYLON;
  76439. (function (BABYLON) {
  76440. var ProceduralTexture = /** @class */ (function (_super) {
  76441. __extends(ProceduralTexture, _super);
  76442. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  76443. if (fallbackTexture === void 0) { fallbackTexture = null; }
  76444. if (generateMipMaps === void 0) { generateMipMaps = true; }
  76445. if (isCube === void 0) { isCube = false; }
  76446. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  76447. _this.isCube = isCube;
  76448. _this.isEnabled = true;
  76449. _this._currentRefreshId = -1;
  76450. _this._refreshRate = 1;
  76451. /**
  76452. * Event raised when the texture is generated
  76453. */
  76454. _this.onGeneratedObservable = new BABYLON.Observable();
  76455. _this._vertexBuffers = {};
  76456. _this._uniforms = new Array();
  76457. _this._samplers = new Array();
  76458. /** @hidden */
  76459. _this._textures = {};
  76460. _this._floats = {};
  76461. _this._ints = {};
  76462. _this._floatsArrays = {};
  76463. _this._colors3 = {};
  76464. _this._colors4 = {};
  76465. _this._vectors2 = {};
  76466. _this._vectors3 = {};
  76467. _this._matrices = {};
  76468. _this._fallbackTextureUsed = false;
  76469. _this._cachedDefines = "";
  76470. _this._contentUpdateId = -1;
  76471. scene = _this.getScene();
  76472. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  76473. if (!component) {
  76474. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  76475. scene._addComponent(component);
  76476. }
  76477. scene.proceduralTextures.push(_this);
  76478. _this._engine = scene.getEngine();
  76479. _this.name = name;
  76480. _this.isRenderTarget = true;
  76481. _this._size = size;
  76482. _this._generateMipMaps = generateMipMaps;
  76483. _this.setFragment(fragment);
  76484. _this._fallbackTexture = fallbackTexture;
  76485. if (isCube) {
  76486. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  76487. _this.setFloat("face", 0);
  76488. }
  76489. else {
  76490. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  76491. }
  76492. // VBO
  76493. var vertices = [];
  76494. vertices.push(1, 1);
  76495. vertices.push(-1, 1);
  76496. vertices.push(-1, -1);
  76497. vertices.push(1, -1);
  76498. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76499. _this._createIndexBuffer();
  76500. return _this;
  76501. }
  76502. /**
  76503. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  76504. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  76505. */
  76506. ProceduralTexture.prototype.getContent = function () {
  76507. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  76508. return this._contentData;
  76509. }
  76510. this._contentData = this.readPixels(0, 0, this._contentData);
  76511. this._contentUpdateId = this._currentRefreshId;
  76512. return this._contentData;
  76513. };
  76514. ProceduralTexture.prototype._createIndexBuffer = function () {
  76515. var engine = this._engine;
  76516. // Indices
  76517. var indices = [];
  76518. indices.push(0);
  76519. indices.push(1);
  76520. indices.push(2);
  76521. indices.push(0);
  76522. indices.push(2);
  76523. indices.push(3);
  76524. this._indexBuffer = engine.createIndexBuffer(indices);
  76525. };
  76526. /** @hidden */
  76527. ProceduralTexture.prototype._rebuild = function () {
  76528. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76529. if (vb) {
  76530. vb._rebuild();
  76531. }
  76532. this._createIndexBuffer();
  76533. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  76534. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  76535. }
  76536. };
  76537. ProceduralTexture.prototype.reset = function () {
  76538. if (this._effect === undefined) {
  76539. return;
  76540. }
  76541. var engine = this._engine;
  76542. engine._releaseEffect(this._effect);
  76543. };
  76544. ProceduralTexture.prototype._getDefines = function () {
  76545. return "";
  76546. };
  76547. ProceduralTexture.prototype.isReady = function () {
  76548. var _this = this;
  76549. var engine = this._engine;
  76550. var shaders;
  76551. if (!this._fragment) {
  76552. return false;
  76553. }
  76554. if (this._fallbackTextureUsed) {
  76555. return true;
  76556. }
  76557. var defines = this._getDefines();
  76558. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  76559. return true;
  76560. }
  76561. if (this._fragment.fragmentElement !== undefined) {
  76562. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  76563. }
  76564. else {
  76565. shaders = { vertex: "procedural", fragment: this._fragment };
  76566. }
  76567. this._cachedDefines = defines;
  76568. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  76569. _this.releaseInternalTexture();
  76570. if (_this._fallbackTexture) {
  76571. _this._texture = _this._fallbackTexture._texture;
  76572. if (_this._texture) {
  76573. _this._texture.incrementReferences();
  76574. }
  76575. }
  76576. _this._fallbackTextureUsed = true;
  76577. });
  76578. return this._effect.isReady();
  76579. };
  76580. ProceduralTexture.prototype.resetRefreshCounter = function () {
  76581. this._currentRefreshId = -1;
  76582. };
  76583. ProceduralTexture.prototype.setFragment = function (fragment) {
  76584. this._fragment = fragment;
  76585. };
  76586. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  76587. get: function () {
  76588. return this._refreshRate;
  76589. },
  76590. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  76591. set: function (value) {
  76592. this._refreshRate = value;
  76593. this.resetRefreshCounter();
  76594. },
  76595. enumerable: true,
  76596. configurable: true
  76597. });
  76598. /** @hidden */
  76599. ProceduralTexture.prototype._shouldRender = function () {
  76600. if (!this.isEnabled || !this.isReady() || !this._texture) {
  76601. if (this._texture) {
  76602. this._texture.isReady = false;
  76603. }
  76604. return false;
  76605. }
  76606. if (this._fallbackTextureUsed) {
  76607. return false;
  76608. }
  76609. if (this._currentRefreshId === -1) { // At least render once
  76610. this._currentRefreshId = 1;
  76611. return true;
  76612. }
  76613. if (this.refreshRate === this._currentRefreshId) {
  76614. this._currentRefreshId = 1;
  76615. return true;
  76616. }
  76617. this._currentRefreshId++;
  76618. return false;
  76619. };
  76620. ProceduralTexture.prototype.getRenderSize = function () {
  76621. return this._size;
  76622. };
  76623. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  76624. if (this._fallbackTextureUsed) {
  76625. return;
  76626. }
  76627. this.releaseInternalTexture();
  76628. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  76629. // Update properties
  76630. this._size = size;
  76631. this._generateMipMaps = generateMipMaps;
  76632. };
  76633. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  76634. if (this._uniforms.indexOf(uniformName) === -1) {
  76635. this._uniforms.push(uniformName);
  76636. }
  76637. };
  76638. ProceduralTexture.prototype.setTexture = function (name, texture) {
  76639. if (this._samplers.indexOf(name) === -1) {
  76640. this._samplers.push(name);
  76641. }
  76642. this._textures[name] = texture;
  76643. return this;
  76644. };
  76645. ProceduralTexture.prototype.setFloat = function (name, value) {
  76646. this._checkUniform(name);
  76647. this._floats[name] = value;
  76648. return this;
  76649. };
  76650. /**
  76651. * Set the value of an uniform to an integer value
  76652. * @param name defines the name of the uniform
  76653. * @param value defines the value to set
  76654. * @returns the current procedural texture
  76655. */
  76656. ProceduralTexture.prototype.setInt = function (name, value) {
  76657. this._checkUniform(name);
  76658. this._ints[name] = value;
  76659. return this;
  76660. };
  76661. ProceduralTexture.prototype.setFloats = function (name, value) {
  76662. this._checkUniform(name);
  76663. this._floatsArrays[name] = value;
  76664. return this;
  76665. };
  76666. ProceduralTexture.prototype.setColor3 = function (name, value) {
  76667. this._checkUniform(name);
  76668. this._colors3[name] = value;
  76669. return this;
  76670. };
  76671. ProceduralTexture.prototype.setColor4 = function (name, value) {
  76672. this._checkUniform(name);
  76673. this._colors4[name] = value;
  76674. return this;
  76675. };
  76676. ProceduralTexture.prototype.setVector2 = function (name, value) {
  76677. this._checkUniform(name);
  76678. this._vectors2[name] = value;
  76679. return this;
  76680. };
  76681. ProceduralTexture.prototype.setVector3 = function (name, value) {
  76682. this._checkUniform(name);
  76683. this._vectors3[name] = value;
  76684. return this;
  76685. };
  76686. ProceduralTexture.prototype.setMatrix = function (name, value) {
  76687. this._checkUniform(name);
  76688. this._matrices[name] = value;
  76689. return this;
  76690. };
  76691. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76692. var scene = this.getScene();
  76693. if (!scene) {
  76694. return;
  76695. }
  76696. var engine = this._engine;
  76697. // Render
  76698. engine.enableEffect(this._effect);
  76699. engine.setState(false);
  76700. // Texture
  76701. for (var name in this._textures) {
  76702. this._effect.setTexture(name, this._textures[name]);
  76703. }
  76704. // Float
  76705. for (name in this._ints) {
  76706. this._effect.setInt(name, this._ints[name]);
  76707. }
  76708. // Float
  76709. for (name in this._floats) {
  76710. this._effect.setFloat(name, this._floats[name]);
  76711. }
  76712. // Floats
  76713. for (name in this._floatsArrays) {
  76714. this._effect.setArray(name, this._floatsArrays[name]);
  76715. }
  76716. // Color3
  76717. for (name in this._colors3) {
  76718. this._effect.setColor3(name, this._colors3[name]);
  76719. }
  76720. // Color4
  76721. for (name in this._colors4) {
  76722. var color = this._colors4[name];
  76723. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  76724. }
  76725. // Vector2
  76726. for (name in this._vectors2) {
  76727. this._effect.setVector2(name, this._vectors2[name]);
  76728. }
  76729. // Vector3
  76730. for (name in this._vectors3) {
  76731. this._effect.setVector3(name, this._vectors3[name]);
  76732. }
  76733. // Matrix
  76734. for (name in this._matrices) {
  76735. this._effect.setMatrix(name, this._matrices[name]);
  76736. }
  76737. if (!this._texture) {
  76738. return;
  76739. }
  76740. if (this.isCube) {
  76741. for (var face = 0; face < 6; face++) {
  76742. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  76743. // VBOs
  76744. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76745. this._effect.setFloat("face", face);
  76746. // Clear
  76747. engine.clear(scene.clearColor, true, true, true);
  76748. // Draw order
  76749. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76750. // Mipmaps
  76751. if (face === 5) {
  76752. engine.generateMipMapsForCubemap(this._texture);
  76753. }
  76754. }
  76755. }
  76756. else {
  76757. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  76758. // VBOs
  76759. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76760. // Clear
  76761. engine.clear(scene.clearColor, true, true, true);
  76762. // Draw order
  76763. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76764. }
  76765. // Unbind
  76766. engine.unBindFramebuffer(this._texture, this.isCube);
  76767. if (this.onGenerated) {
  76768. this.onGenerated();
  76769. }
  76770. this.onGeneratedObservable.notifyObservers(this);
  76771. };
  76772. ProceduralTexture.prototype.clone = function () {
  76773. var textureSize = this.getSize();
  76774. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  76775. // Base texture
  76776. newTexture.hasAlpha = this.hasAlpha;
  76777. newTexture.level = this.level;
  76778. // RenderTarget Texture
  76779. newTexture.coordinatesMode = this.coordinatesMode;
  76780. return newTexture;
  76781. };
  76782. ProceduralTexture.prototype.dispose = function () {
  76783. var scene = this.getScene();
  76784. if (!scene) {
  76785. return;
  76786. }
  76787. var index = scene.proceduralTextures.indexOf(this);
  76788. if (index >= 0) {
  76789. scene.proceduralTextures.splice(index, 1);
  76790. }
  76791. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76792. if (vertexBuffer) {
  76793. vertexBuffer.dispose();
  76794. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76795. }
  76796. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  76797. this._indexBuffer = null;
  76798. }
  76799. _super.prototype.dispose.call(this);
  76800. };
  76801. __decorate([
  76802. BABYLON.serialize()
  76803. ], ProceduralTexture.prototype, "_size", void 0);
  76804. __decorate([
  76805. BABYLON.serialize()
  76806. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  76807. __decorate([
  76808. BABYLON.serialize()
  76809. ], ProceduralTexture.prototype, "isEnabled", void 0);
  76810. __decorate([
  76811. BABYLON.serialize()
  76812. ], ProceduralTexture.prototype, "refreshRate", null);
  76813. return ProceduralTexture;
  76814. }(BABYLON.Texture));
  76815. BABYLON.ProceduralTexture = ProceduralTexture;
  76816. })(BABYLON || (BABYLON = {}));
  76817. //# sourceMappingURL=babylon.proceduralTexture.js.map
  76818. var BABYLON;
  76819. (function (BABYLON) {
  76820. /**
  76821. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  76822. * in a given scene.
  76823. */
  76824. var ProceduralTextureSceneComponent = /** @class */ (function () {
  76825. /**
  76826. * Creates a new instance of the component for the given scene
  76827. * @param scene Defines the scene to register the component in
  76828. */
  76829. function ProceduralTextureSceneComponent(scene) {
  76830. /**
  76831. * The component name helpfull to identify the component in the list of scene components.
  76832. */
  76833. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  76834. this.scene = scene;
  76835. this.scene.proceduralTextures = new Array();
  76836. scene.layers = new Array();
  76837. }
  76838. /**
  76839. * Registers the component in a given scene
  76840. */
  76841. ProceduralTextureSceneComponent.prototype.register = function () {
  76842. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  76843. };
  76844. /**
  76845. * Rebuilds the elements related to this component in case of
  76846. * context lost for instance.
  76847. */
  76848. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  76849. // Nothing to do here.
  76850. };
  76851. /**
  76852. * Disposes the component and the associated ressources.
  76853. */
  76854. ProceduralTextureSceneComponent.prototype.dispose = function () {
  76855. // Nothing to do here.
  76856. };
  76857. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  76858. if (this.scene.proceduralTexturesEnabled) {
  76859. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76860. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  76861. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  76862. if (proceduralTexture._shouldRender()) {
  76863. proceduralTexture.render();
  76864. }
  76865. }
  76866. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76867. }
  76868. };
  76869. return ProceduralTextureSceneComponent;
  76870. }());
  76871. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  76872. })(BABYLON || (BABYLON = {}));
  76873. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  76874. var BABYLON;
  76875. (function (BABYLON) {
  76876. var CustomProceduralTexture = /** @class */ (function (_super) {
  76877. __extends(CustomProceduralTexture, _super);
  76878. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  76879. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  76880. _this._animate = true;
  76881. _this._time = 0;
  76882. _this._texturePath = texturePath;
  76883. //Try to load json
  76884. _this.loadJson(texturePath);
  76885. _this.refreshRate = 1;
  76886. return _this;
  76887. }
  76888. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  76889. var _this = this;
  76890. var noConfigFile = function () {
  76891. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  76892. try {
  76893. _this.setFragment(_this._texturePath);
  76894. }
  76895. catch (ex) {
  76896. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  76897. }
  76898. };
  76899. var configFileUrl = jsonUrl + "/config.json";
  76900. var xhr = new XMLHttpRequest();
  76901. xhr.open("GET", configFileUrl, true);
  76902. xhr.addEventListener("load", function () {
  76903. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  76904. try {
  76905. _this._config = JSON.parse(xhr.response);
  76906. _this.updateShaderUniforms();
  76907. _this.updateTextures();
  76908. _this.setFragment(_this._texturePath + "/custom");
  76909. _this._animate = _this._config.animate;
  76910. _this.refreshRate = _this._config.refreshrate;
  76911. }
  76912. catch (ex) {
  76913. noConfigFile();
  76914. }
  76915. }
  76916. else {
  76917. noConfigFile();
  76918. }
  76919. }, false);
  76920. xhr.addEventListener("error", function () {
  76921. noConfigFile();
  76922. }, false);
  76923. try {
  76924. xhr.send();
  76925. }
  76926. catch (ex) {
  76927. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  76928. }
  76929. };
  76930. CustomProceduralTexture.prototype.isReady = function () {
  76931. if (!_super.prototype.isReady.call(this)) {
  76932. return false;
  76933. }
  76934. for (var name in this._textures) {
  76935. var texture = this._textures[name];
  76936. if (!texture.isReady()) {
  76937. return false;
  76938. }
  76939. }
  76940. return true;
  76941. };
  76942. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76943. var scene = this.getScene();
  76944. if (this._animate && scene) {
  76945. this._time += scene.getAnimationRatio() * 0.03;
  76946. this.updateShaderUniforms();
  76947. }
  76948. _super.prototype.render.call(this, useCameraPostProcess);
  76949. };
  76950. CustomProceduralTexture.prototype.updateTextures = function () {
  76951. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  76952. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  76953. }
  76954. };
  76955. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  76956. if (this._config) {
  76957. for (var j = 0; j < this._config.uniforms.length; j++) {
  76958. var uniform = this._config.uniforms[j];
  76959. switch (uniform.type) {
  76960. case "float":
  76961. this.setFloat(uniform.name, uniform.value);
  76962. break;
  76963. case "color3":
  76964. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  76965. break;
  76966. case "color4":
  76967. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  76968. break;
  76969. case "vector2":
  76970. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  76971. break;
  76972. case "vector3":
  76973. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  76974. break;
  76975. }
  76976. }
  76977. }
  76978. this.setFloat("time", this._time);
  76979. };
  76980. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  76981. get: function () {
  76982. return this._animate;
  76983. },
  76984. set: function (value) {
  76985. this._animate = value;
  76986. },
  76987. enumerable: true,
  76988. configurable: true
  76989. });
  76990. return CustomProceduralTexture;
  76991. }(BABYLON.ProceduralTexture));
  76992. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  76993. })(BABYLON || (BABYLON = {}));
  76994. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  76995. var BABYLON;
  76996. (function (BABYLON) {
  76997. /**
  76998. * Manage the gamepad inputs to control a free camera.
  76999. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77000. */
  77001. var FreeCameraGamepadInput = /** @class */ (function () {
  77002. function FreeCameraGamepadInput() {
  77003. /**
  77004. * Defines the gamepad rotation sensiblity.
  77005. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  77006. */
  77007. this.gamepadAngularSensibility = 200;
  77008. /**
  77009. * Defines the gamepad move sensiblity.
  77010. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  77011. */
  77012. this.gamepadMoveSensibility = 40;
  77013. this._cameraTransform = BABYLON.Matrix.Identity();
  77014. this._deltaTransform = BABYLON.Vector3.Zero();
  77015. this._vector3 = BABYLON.Vector3.Zero();
  77016. this._vector2 = BABYLON.Vector2.Zero();
  77017. }
  77018. /**
  77019. * Attach the input controls to a specific dom element to get the input from.
  77020. * @param element Defines the element the controls should be listened from
  77021. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77022. */
  77023. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  77024. var _this = this;
  77025. var manager = this.camera.getScene().gamepadManager;
  77026. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77027. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77028. // prioritize XBOX gamepads.
  77029. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  77030. _this.gamepad = gamepad;
  77031. }
  77032. }
  77033. });
  77034. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77035. if (_this.gamepad === gamepad) {
  77036. _this.gamepad = null;
  77037. }
  77038. });
  77039. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  77040. };
  77041. /**
  77042. * Detach the current controls from the specified dom element.
  77043. * @param element Defines the element to stop listening the inputs from
  77044. */
  77045. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  77046. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77047. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77048. this.gamepad = null;
  77049. };
  77050. /**
  77051. * Update the current camera state depending on the inputs that have been used this frame.
  77052. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77053. */
  77054. FreeCameraGamepadInput.prototype.checkInputs = function () {
  77055. if (this.gamepad && this.gamepad.leftStick) {
  77056. var camera = this.camera;
  77057. var LSValues = this.gamepad.leftStick;
  77058. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  77059. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  77060. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  77061. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  77062. var RSValues = this.gamepad.rightStick;
  77063. if (RSValues) {
  77064. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  77065. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  77066. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  77067. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  77068. }
  77069. else {
  77070. RSValues = { x: 0, y: 0 };
  77071. }
  77072. if (!camera.rotationQuaternion) {
  77073. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  77074. }
  77075. else {
  77076. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  77077. }
  77078. var speed = camera._computeLocalCameraSpeed() * 50.0;
  77079. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  77080. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  77081. camera.cameraDirection.addInPlace(this._deltaTransform);
  77082. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  77083. camera.cameraRotation.addInPlace(this._vector2);
  77084. }
  77085. };
  77086. /**
  77087. * Gets the class name of the current intput.
  77088. * @returns the class name
  77089. */
  77090. FreeCameraGamepadInput.prototype.getClassName = function () {
  77091. return "FreeCameraGamepadInput";
  77092. };
  77093. /**
  77094. * Get the friendly name associated with the input class.
  77095. * @returns the input friendly name
  77096. */
  77097. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  77098. return "gamepad";
  77099. };
  77100. __decorate([
  77101. BABYLON.serialize()
  77102. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  77103. __decorate([
  77104. BABYLON.serialize()
  77105. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  77106. return FreeCameraGamepadInput;
  77107. }());
  77108. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  77109. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  77110. })(BABYLON || (BABYLON = {}));
  77111. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  77112. var BABYLON;
  77113. (function (BABYLON) {
  77114. /**
  77115. * Manage the gamepad inputs to control an arc rotate camera.
  77116. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77117. */
  77118. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  77119. function ArcRotateCameraGamepadInput() {
  77120. /**
  77121. * Defines the gamepad rotation sensiblity.
  77122. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  77123. */
  77124. this.gamepadRotationSensibility = 80;
  77125. /**
  77126. * Defines the gamepad move sensiblity.
  77127. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  77128. */
  77129. this.gamepadMoveSensibility = 40;
  77130. }
  77131. /**
  77132. * Attach the input controls to a specific dom element to get the input from.
  77133. * @param element Defines the element the controls should be listened from
  77134. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77135. */
  77136. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  77137. var _this = this;
  77138. var manager = this.camera.getScene().gamepadManager;
  77139. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77140. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77141. // prioritize XBOX gamepads.
  77142. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  77143. _this.gamepad = gamepad;
  77144. }
  77145. }
  77146. });
  77147. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77148. if (_this.gamepad === gamepad) {
  77149. _this.gamepad = null;
  77150. }
  77151. });
  77152. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  77153. };
  77154. /**
  77155. * Detach the current controls from the specified dom element.
  77156. * @param element Defines the element to stop listening the inputs from
  77157. */
  77158. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  77159. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77160. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77161. this.gamepad = null;
  77162. };
  77163. /**
  77164. * Update the current camera state depending on the inputs that have been used this frame.
  77165. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77166. */
  77167. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  77168. if (this.gamepad) {
  77169. var camera = this.camera;
  77170. var RSValues = this.gamepad.rightStick;
  77171. if (RSValues) {
  77172. if (RSValues.x != 0) {
  77173. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  77174. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  77175. camera.inertialAlphaOffset += normalizedRX;
  77176. }
  77177. }
  77178. if (RSValues.y != 0) {
  77179. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  77180. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  77181. camera.inertialBetaOffset += normalizedRY;
  77182. }
  77183. }
  77184. }
  77185. var LSValues = this.gamepad.leftStick;
  77186. if (LSValues && LSValues.y != 0) {
  77187. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  77188. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  77189. this.camera.inertialRadiusOffset -= normalizedLY;
  77190. }
  77191. }
  77192. }
  77193. };
  77194. /**
  77195. * Gets the class name of the current intput.
  77196. * @returns the class name
  77197. */
  77198. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  77199. return "ArcRotateCameraGamepadInput";
  77200. };
  77201. /**
  77202. * Get the friendly name associated with the input class.
  77203. * @returns the input friendly name
  77204. */
  77205. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  77206. return "gamepad";
  77207. };
  77208. __decorate([
  77209. BABYLON.serialize()
  77210. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  77211. __decorate([
  77212. BABYLON.serialize()
  77213. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  77214. return ArcRotateCameraGamepadInput;
  77215. }());
  77216. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  77217. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  77218. })(BABYLON || (BABYLON = {}));
  77219. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  77220. var BABYLON;
  77221. (function (BABYLON) {
  77222. /**
  77223. * Manager for handling gamepads
  77224. */
  77225. var GamepadManager = /** @class */ (function () {
  77226. /**
  77227. * Initializes the gamepad manager
  77228. * @param _scene BabylonJS scene
  77229. */
  77230. function GamepadManager(_scene) {
  77231. var _this = this;
  77232. this._scene = _scene;
  77233. this._babylonGamepads = [];
  77234. this._oneGamepadConnected = false;
  77235. /** @hidden */
  77236. this._isMonitoring = false;
  77237. /**
  77238. * observable to be triggered when the gamepad controller has been disconnected
  77239. */
  77240. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  77241. if (!BABYLON.Tools.IsWindowObjectExist()) {
  77242. this._gamepadEventSupported = false;
  77243. }
  77244. else {
  77245. this._gamepadEventSupported = 'GamepadEvent' in window;
  77246. this._gamepadSupport = (navigator.getGamepads ||
  77247. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  77248. }
  77249. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  77250. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  77251. for (var i in _this._babylonGamepads) {
  77252. var gamepad = _this._babylonGamepads[i];
  77253. if (gamepad && gamepad._isConnected) {
  77254. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  77255. }
  77256. }
  77257. });
  77258. this._onGamepadConnectedEvent = function (evt) {
  77259. var gamepad = evt.gamepad;
  77260. if (gamepad.index in _this._babylonGamepads) {
  77261. if (_this._babylonGamepads[gamepad.index].isConnected) {
  77262. return;
  77263. }
  77264. }
  77265. var newGamepad;
  77266. if (_this._babylonGamepads[gamepad.index]) {
  77267. newGamepad = _this._babylonGamepads[gamepad.index];
  77268. newGamepad.browserGamepad = gamepad;
  77269. newGamepad._isConnected = true;
  77270. }
  77271. else {
  77272. newGamepad = _this._addNewGamepad(gamepad);
  77273. }
  77274. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77275. _this._startMonitoringGamepads();
  77276. };
  77277. this._onGamepadDisconnectedEvent = function (evt) {
  77278. var gamepad = evt.gamepad;
  77279. // Remove the gamepad from the list of gamepads to monitor.
  77280. for (var i in _this._babylonGamepads) {
  77281. if (_this._babylonGamepads[i].index === gamepad.index) {
  77282. var disconnectedGamepad = _this._babylonGamepads[i];
  77283. disconnectedGamepad._isConnected = false;
  77284. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  77285. break;
  77286. }
  77287. }
  77288. };
  77289. if (this._gamepadSupport) {
  77290. //first add already-connected gamepads
  77291. this._updateGamepadObjects();
  77292. if (this._babylonGamepads.length) {
  77293. this._startMonitoringGamepads();
  77294. }
  77295. // Checking if the gamepad connected event is supported (like in Firefox)
  77296. if (this._gamepadEventSupported) {
  77297. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  77298. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  77299. }
  77300. else {
  77301. this._startMonitoringGamepads();
  77302. }
  77303. }
  77304. }
  77305. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  77306. /**
  77307. * The gamepads in the game pad manager
  77308. */
  77309. get: function () {
  77310. return this._babylonGamepads;
  77311. },
  77312. enumerable: true,
  77313. configurable: true
  77314. });
  77315. /**
  77316. * Get the gamepad controllers based on type
  77317. * @param type The type of gamepad controller
  77318. * @returns Nullable gamepad
  77319. */
  77320. GamepadManager.prototype.getGamepadByType = function (type) {
  77321. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  77322. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  77323. var gamepad = _a[_i];
  77324. if (gamepad && gamepad.type === type) {
  77325. return gamepad;
  77326. }
  77327. }
  77328. return null;
  77329. };
  77330. /**
  77331. * Disposes the gamepad manager
  77332. */
  77333. GamepadManager.prototype.dispose = function () {
  77334. if (this._gamepadEventSupported) {
  77335. if (this._onGamepadConnectedEvent) {
  77336. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  77337. }
  77338. if (this._onGamepadDisconnectedEvent) {
  77339. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  77340. }
  77341. this._onGamepadConnectedEvent = null;
  77342. this._onGamepadDisconnectedEvent = null;
  77343. }
  77344. this._babylonGamepads.forEach(function (gamepad) {
  77345. gamepad.dispose();
  77346. });
  77347. this.onGamepadConnectedObservable.clear();
  77348. this.onGamepadDisconnectedObservable.clear();
  77349. this._oneGamepadConnected = false;
  77350. this._stopMonitoringGamepads();
  77351. this._babylonGamepads = [];
  77352. };
  77353. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  77354. if (!this._oneGamepadConnected) {
  77355. this._oneGamepadConnected = true;
  77356. }
  77357. var newGamepad;
  77358. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  77359. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  77360. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  77361. }
  77362. // if pose is supported, use the (WebVR) pose enabled controller
  77363. else if (gamepad.pose) {
  77364. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  77365. }
  77366. else {
  77367. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  77368. }
  77369. this._babylonGamepads[newGamepad.index] = newGamepad;
  77370. return newGamepad;
  77371. };
  77372. GamepadManager.prototype._startMonitoringGamepads = function () {
  77373. if (!this._isMonitoring) {
  77374. this._isMonitoring = true;
  77375. //back-comp
  77376. if (!this._scene) {
  77377. this._checkGamepadsStatus();
  77378. }
  77379. }
  77380. };
  77381. GamepadManager.prototype._stopMonitoringGamepads = function () {
  77382. this._isMonitoring = false;
  77383. };
  77384. /** @hidden */
  77385. GamepadManager.prototype._checkGamepadsStatus = function () {
  77386. var _this = this;
  77387. // Hack to be compatible Chrome
  77388. this._updateGamepadObjects();
  77389. for (var i in this._babylonGamepads) {
  77390. var gamepad = this._babylonGamepads[i];
  77391. if (!gamepad || !gamepad.isConnected) {
  77392. continue;
  77393. }
  77394. gamepad.update();
  77395. }
  77396. if (this._isMonitoring && !this._scene) {
  77397. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  77398. }
  77399. };
  77400. // This function is called only on Chrome, which does not properly support
  77401. // connection/disconnection events and forces you to recopy again the gamepad object
  77402. GamepadManager.prototype._updateGamepadObjects = function () {
  77403. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  77404. for (var i = 0; i < gamepads.length; i++) {
  77405. var gamepad = gamepads[i];
  77406. if (gamepad) {
  77407. if (!this._babylonGamepads[gamepad.index]) {
  77408. var newGamepad = this._addNewGamepad(gamepad);
  77409. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77410. }
  77411. else {
  77412. // Forced to copy again this object for Chrome for unknown reason
  77413. this._babylonGamepads[i].browserGamepad = gamepad;
  77414. if (!this._babylonGamepads[i].isConnected) {
  77415. this._babylonGamepads[i]._isConnected = true;
  77416. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  77417. }
  77418. }
  77419. }
  77420. }
  77421. };
  77422. return GamepadManager;
  77423. }());
  77424. BABYLON.GamepadManager = GamepadManager;
  77425. })(BABYLON || (BABYLON = {}));
  77426. //# sourceMappingURL=babylon.gamepadManager.js.map
  77427. var BABYLON;
  77428. (function (BABYLON) {
  77429. /**
  77430. * Represents a gamepad control stick position
  77431. */
  77432. var StickValues = /** @class */ (function () {
  77433. /**
  77434. * Initializes the gamepad x and y control stick values
  77435. * @param x The x component of the gamepad control stick value
  77436. * @param y The y component of the gamepad control stick value
  77437. */
  77438. function StickValues(
  77439. /**
  77440. * The x component of the control stick
  77441. */
  77442. x,
  77443. /**
  77444. * The y component of the control stick
  77445. */
  77446. y) {
  77447. this.x = x;
  77448. this.y = y;
  77449. }
  77450. return StickValues;
  77451. }());
  77452. BABYLON.StickValues = StickValues;
  77453. /**
  77454. * Represents a gamepad
  77455. */
  77456. var Gamepad = /** @class */ (function () {
  77457. /**
  77458. * Initializes the gamepad
  77459. * @param id The id of the gamepad
  77460. * @param index The index of the gamepad
  77461. * @param browserGamepad The browser gamepad
  77462. * @param leftStickX The x component of the left joystick
  77463. * @param leftStickY The y component of the left joystick
  77464. * @param rightStickX The x component of the right joystick
  77465. * @param rightStickY The y component of the right joystick
  77466. */
  77467. function Gamepad(
  77468. /**
  77469. * The id of the gamepad
  77470. */
  77471. id,
  77472. /**
  77473. * The index of the gamepad
  77474. */
  77475. index,
  77476. /**
  77477. * The browser gamepad
  77478. */
  77479. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  77480. if (leftStickX === void 0) { leftStickX = 0; }
  77481. if (leftStickY === void 0) { leftStickY = 1; }
  77482. if (rightStickX === void 0) { rightStickX = 2; }
  77483. if (rightStickY === void 0) { rightStickY = 3; }
  77484. this.id = id;
  77485. this.index = index;
  77486. this.browserGamepad = browserGamepad;
  77487. this._leftStick = { x: 0, y: 0 };
  77488. this._rightStick = { x: 0, y: 0 };
  77489. /** @hidden */
  77490. this._isConnected = true;
  77491. /**
  77492. * Specifies whether the left control stick should be Y-inverted
  77493. */
  77494. this._invertLeftStickY = false;
  77495. this.type = Gamepad.GAMEPAD;
  77496. this._leftStickAxisX = leftStickX;
  77497. this._leftStickAxisY = leftStickY;
  77498. this._rightStickAxisX = rightStickX;
  77499. this._rightStickAxisY = rightStickY;
  77500. if (this.browserGamepad.axes.length >= 2) {
  77501. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77502. }
  77503. if (this.browserGamepad.axes.length >= 4) {
  77504. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77505. }
  77506. }
  77507. Object.defineProperty(Gamepad.prototype, "isConnected", {
  77508. /**
  77509. * Specifies if the gamepad has been connected
  77510. */
  77511. get: function () {
  77512. return this._isConnected;
  77513. },
  77514. enumerable: true,
  77515. configurable: true
  77516. });
  77517. /**
  77518. * Callback triggered when the left joystick has changed
  77519. * @param callback
  77520. */
  77521. Gamepad.prototype.onleftstickchanged = function (callback) {
  77522. this._onleftstickchanged = callback;
  77523. };
  77524. /**
  77525. * Callback triggered when the right joystick has changed
  77526. * @param callback
  77527. */
  77528. Gamepad.prototype.onrightstickchanged = function (callback) {
  77529. this._onrightstickchanged = callback;
  77530. };
  77531. Object.defineProperty(Gamepad.prototype, "leftStick", {
  77532. /**
  77533. * Gets the left joystick
  77534. */
  77535. get: function () {
  77536. return this._leftStick;
  77537. },
  77538. /**
  77539. * Sets the left joystick values
  77540. */
  77541. set: function (newValues) {
  77542. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  77543. this._onleftstickchanged(newValues);
  77544. }
  77545. this._leftStick = newValues;
  77546. },
  77547. enumerable: true,
  77548. configurable: true
  77549. });
  77550. Object.defineProperty(Gamepad.prototype, "rightStick", {
  77551. /**
  77552. * Gets the right joystick
  77553. */
  77554. get: function () {
  77555. return this._rightStick;
  77556. },
  77557. /**
  77558. * Sets the right joystick value
  77559. */
  77560. set: function (newValues) {
  77561. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  77562. this._onrightstickchanged(newValues);
  77563. }
  77564. this._rightStick = newValues;
  77565. },
  77566. enumerable: true,
  77567. configurable: true
  77568. });
  77569. /**
  77570. * Updates the gamepad joystick positions
  77571. */
  77572. Gamepad.prototype.update = function () {
  77573. if (this._leftStick) {
  77574. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77575. if (this._invertLeftStickY) {
  77576. this.leftStick.y *= -1;
  77577. }
  77578. }
  77579. if (this._rightStick) {
  77580. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77581. }
  77582. };
  77583. /**
  77584. * Disposes the gamepad
  77585. */
  77586. Gamepad.prototype.dispose = function () {
  77587. };
  77588. /**
  77589. * Represents a gamepad controller
  77590. */
  77591. Gamepad.GAMEPAD = 0;
  77592. /**
  77593. * Represents a generic controller
  77594. */
  77595. Gamepad.GENERIC = 1;
  77596. /**
  77597. * Represents an XBox controller
  77598. */
  77599. Gamepad.XBOX = 2;
  77600. /**
  77601. * Represents a pose-enabled controller
  77602. */
  77603. Gamepad.POSE_ENABLED = 3;
  77604. return Gamepad;
  77605. }());
  77606. BABYLON.Gamepad = Gamepad;
  77607. /**
  77608. * Represents a generic gamepad
  77609. */
  77610. var GenericPad = /** @class */ (function (_super) {
  77611. __extends(GenericPad, _super);
  77612. /**
  77613. * Initializes the generic gamepad
  77614. * @param id The id of the generic gamepad
  77615. * @param index The index of the generic gamepad
  77616. * @param browserGamepad The browser gamepad
  77617. */
  77618. function GenericPad(id, index, browserGamepad) {
  77619. var _this = _super.call(this, id, index, browserGamepad) || this;
  77620. /**
  77621. * Observable triggered when a button has been pressed
  77622. */
  77623. _this.onButtonDownObservable = new BABYLON.Observable();
  77624. /**
  77625. * Observable triggered when a button has been released
  77626. */
  77627. _this.onButtonUpObservable = new BABYLON.Observable();
  77628. _this.type = Gamepad.GENERIC;
  77629. _this._buttons = new Array(browserGamepad.buttons.length);
  77630. return _this;
  77631. }
  77632. /**
  77633. * Callback triggered when a button has been pressed
  77634. * @param callback Called when a button has been pressed
  77635. */
  77636. GenericPad.prototype.onbuttondown = function (callback) {
  77637. this._onbuttondown = callback;
  77638. };
  77639. /**
  77640. * Callback triggered when a button has been released
  77641. * @param callback Called when a button has been released
  77642. */
  77643. GenericPad.prototype.onbuttonup = function (callback) {
  77644. this._onbuttonup = callback;
  77645. };
  77646. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  77647. if (newValue !== currentValue) {
  77648. if (newValue === 1) {
  77649. if (this._onbuttondown) {
  77650. this._onbuttondown(buttonIndex);
  77651. }
  77652. this.onButtonDownObservable.notifyObservers(buttonIndex);
  77653. }
  77654. if (newValue === 0) {
  77655. if (this._onbuttonup) {
  77656. this._onbuttonup(buttonIndex);
  77657. }
  77658. this.onButtonUpObservable.notifyObservers(buttonIndex);
  77659. }
  77660. }
  77661. return newValue;
  77662. };
  77663. /**
  77664. * Updates the generic gamepad
  77665. */
  77666. GenericPad.prototype.update = function () {
  77667. _super.prototype.update.call(this);
  77668. for (var index = 0; index < this._buttons.length; index++) {
  77669. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  77670. }
  77671. };
  77672. /**
  77673. * Disposes the generic gamepad
  77674. */
  77675. GenericPad.prototype.dispose = function () {
  77676. _super.prototype.dispose.call(this);
  77677. this.onButtonDownObservable.clear();
  77678. this.onButtonUpObservable.clear();
  77679. };
  77680. return GenericPad;
  77681. }(Gamepad));
  77682. BABYLON.GenericPad = GenericPad;
  77683. })(BABYLON || (BABYLON = {}));
  77684. //# sourceMappingURL=babylon.gamepad.js.map
  77685. var BABYLON;
  77686. (function (BABYLON) {
  77687. /**
  77688. * Defines supported buttons for XBox360 compatible gamepads
  77689. */
  77690. var Xbox360Button;
  77691. (function (Xbox360Button) {
  77692. /** A */
  77693. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  77694. /** B */
  77695. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  77696. /** X */
  77697. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  77698. /** Y */
  77699. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  77700. /** Start */
  77701. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  77702. /** Back */
  77703. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  77704. /** Left button */
  77705. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  77706. /** Right button */
  77707. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  77708. /** Left stick */
  77709. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  77710. /** Right stick */
  77711. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  77712. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  77713. /** Defines values for XBox360 DPad */
  77714. var Xbox360Dpad;
  77715. (function (Xbox360Dpad) {
  77716. /** Up */
  77717. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  77718. /** Down */
  77719. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  77720. /** Left */
  77721. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  77722. /** Right */
  77723. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  77724. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  77725. /**
  77726. * Defines a XBox360 gamepad
  77727. */
  77728. var Xbox360Pad = /** @class */ (function (_super) {
  77729. __extends(Xbox360Pad, _super);
  77730. /**
  77731. * Creates a new XBox360 gamepad object
  77732. * @param id defines the id of this gamepad
  77733. * @param index defines its index
  77734. * @param gamepad defines the internal HTML gamepad object
  77735. * @param xboxOne defines if it is a XBox One gamepad
  77736. */
  77737. function Xbox360Pad(id, index, gamepad, xboxOne) {
  77738. if (xboxOne === void 0) { xboxOne = false; }
  77739. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  77740. _this._leftTrigger = 0;
  77741. _this._rightTrigger = 0;
  77742. /** Observable raised when a button is pressed */
  77743. _this.onButtonDownObservable = new BABYLON.Observable();
  77744. /** Observable raised when a button is released */
  77745. _this.onButtonUpObservable = new BABYLON.Observable();
  77746. /** Observable raised when a pad is pressed */
  77747. _this.onPadDownObservable = new BABYLON.Observable();
  77748. /** Observable raised when a pad is released */
  77749. _this.onPadUpObservable = new BABYLON.Observable();
  77750. _this._buttonA = 0;
  77751. _this._buttonB = 0;
  77752. _this._buttonX = 0;
  77753. _this._buttonY = 0;
  77754. _this._buttonBack = 0;
  77755. _this._buttonStart = 0;
  77756. _this._buttonLB = 0;
  77757. _this._buttonRB = 0;
  77758. _this._buttonLeftStick = 0;
  77759. _this._buttonRightStick = 0;
  77760. _this._dPadUp = 0;
  77761. _this._dPadDown = 0;
  77762. _this._dPadLeft = 0;
  77763. _this._dPadRight = 0;
  77764. _this._isXboxOnePad = false;
  77765. _this.type = BABYLON.Gamepad.XBOX;
  77766. _this._isXboxOnePad = xboxOne;
  77767. return _this;
  77768. }
  77769. /**
  77770. * Defines the callback to call when left trigger is pressed
  77771. * @param callback defines the callback to use
  77772. */
  77773. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  77774. this._onlefttriggerchanged = callback;
  77775. };
  77776. /**
  77777. * Defines the callback to call when right trigger is pressed
  77778. * @param callback defines the callback to use
  77779. */
  77780. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  77781. this._onrighttriggerchanged = callback;
  77782. };
  77783. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  77784. /**
  77785. * Gets the left trigger value
  77786. */
  77787. get: function () {
  77788. return this._leftTrigger;
  77789. },
  77790. /**
  77791. * Sets the left trigger value
  77792. */
  77793. set: function (newValue) {
  77794. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  77795. this._onlefttriggerchanged(newValue);
  77796. }
  77797. this._leftTrigger = newValue;
  77798. },
  77799. enumerable: true,
  77800. configurable: true
  77801. });
  77802. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  77803. /**
  77804. * Gets the right trigger value
  77805. */
  77806. get: function () {
  77807. return this._rightTrigger;
  77808. },
  77809. /**
  77810. * Sets the right trigger value
  77811. */
  77812. set: function (newValue) {
  77813. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  77814. this._onrighttriggerchanged(newValue);
  77815. }
  77816. this._rightTrigger = newValue;
  77817. },
  77818. enumerable: true,
  77819. configurable: true
  77820. });
  77821. /**
  77822. * Defines the callback to call when a button is pressed
  77823. * @param callback defines the callback to use
  77824. */
  77825. Xbox360Pad.prototype.onbuttondown = function (callback) {
  77826. this._onbuttondown = callback;
  77827. };
  77828. /**
  77829. * Defines the callback to call when a button is released
  77830. * @param callback defines the callback to use
  77831. */
  77832. Xbox360Pad.prototype.onbuttonup = function (callback) {
  77833. this._onbuttonup = callback;
  77834. };
  77835. /**
  77836. * Defines the callback to call when a pad is pressed
  77837. * @param callback defines the callback to use
  77838. */
  77839. Xbox360Pad.prototype.ondpaddown = function (callback) {
  77840. this._ondpaddown = callback;
  77841. };
  77842. /**
  77843. * Defines the callback to call when a pad is released
  77844. * @param callback defines the callback to use
  77845. */
  77846. Xbox360Pad.prototype.ondpadup = function (callback) {
  77847. this._ondpadup = callback;
  77848. };
  77849. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  77850. if (newValue !== currentValue) {
  77851. if (newValue === 1) {
  77852. if (this._onbuttondown) {
  77853. this._onbuttondown(buttonType);
  77854. }
  77855. this.onButtonDownObservable.notifyObservers(buttonType);
  77856. }
  77857. if (newValue === 0) {
  77858. if (this._onbuttonup) {
  77859. this._onbuttonup(buttonType);
  77860. }
  77861. this.onButtonUpObservable.notifyObservers(buttonType);
  77862. }
  77863. }
  77864. return newValue;
  77865. };
  77866. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  77867. if (newValue !== currentValue) {
  77868. if (newValue === 1) {
  77869. if (this._ondpaddown) {
  77870. this._ondpaddown(buttonType);
  77871. }
  77872. this.onPadDownObservable.notifyObservers(buttonType);
  77873. }
  77874. if (newValue === 0) {
  77875. if (this._ondpadup) {
  77876. this._ondpadup(buttonType);
  77877. }
  77878. this.onPadUpObservable.notifyObservers(buttonType);
  77879. }
  77880. }
  77881. return newValue;
  77882. };
  77883. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  77884. /**
  77885. * Gets the value of the `A` button
  77886. */
  77887. get: function () {
  77888. return this._buttonA;
  77889. },
  77890. /**
  77891. * Sets the value of the `A` button
  77892. */
  77893. set: function (value) {
  77894. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  77895. },
  77896. enumerable: true,
  77897. configurable: true
  77898. });
  77899. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  77900. /**
  77901. * Gets the value of the `B` button
  77902. */
  77903. get: function () {
  77904. return this._buttonB;
  77905. },
  77906. /**
  77907. * Sets the value of the `B` button
  77908. */
  77909. set: function (value) {
  77910. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  77911. },
  77912. enumerable: true,
  77913. configurable: true
  77914. });
  77915. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  77916. /**
  77917. * Gets the value of the `X` button
  77918. */
  77919. get: function () {
  77920. return this._buttonX;
  77921. },
  77922. /**
  77923. * Sets the value of the `X` button
  77924. */
  77925. set: function (value) {
  77926. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  77927. },
  77928. enumerable: true,
  77929. configurable: true
  77930. });
  77931. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  77932. /**
  77933. * Gets the value of the `Y` button
  77934. */
  77935. get: function () {
  77936. return this._buttonY;
  77937. },
  77938. /**
  77939. * Sets the value of the `Y` button
  77940. */
  77941. set: function (value) {
  77942. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  77943. },
  77944. enumerable: true,
  77945. configurable: true
  77946. });
  77947. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  77948. /**
  77949. * Gets the value of the `Start` button
  77950. */
  77951. get: function () {
  77952. return this._buttonStart;
  77953. },
  77954. /**
  77955. * Sets the value of the `Start` button
  77956. */
  77957. set: function (value) {
  77958. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  77959. },
  77960. enumerable: true,
  77961. configurable: true
  77962. });
  77963. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  77964. /**
  77965. * Gets the value of the `Back` button
  77966. */
  77967. get: function () {
  77968. return this._buttonBack;
  77969. },
  77970. /**
  77971. * Sets the value of the `Back` button
  77972. */
  77973. set: function (value) {
  77974. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  77975. },
  77976. enumerable: true,
  77977. configurable: true
  77978. });
  77979. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  77980. /**
  77981. * Gets the value of the `Left` button
  77982. */
  77983. get: function () {
  77984. return this._buttonLB;
  77985. },
  77986. /**
  77987. * Sets the value of the `Left` button
  77988. */
  77989. set: function (value) {
  77990. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  77991. },
  77992. enumerable: true,
  77993. configurable: true
  77994. });
  77995. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  77996. /**
  77997. * Gets the value of the `Right` button
  77998. */
  77999. get: function () {
  78000. return this._buttonRB;
  78001. },
  78002. /**
  78003. * Sets the value of the `Right` button
  78004. */
  78005. set: function (value) {
  78006. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  78007. },
  78008. enumerable: true,
  78009. configurable: true
  78010. });
  78011. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  78012. /**
  78013. * Gets the value of the Left joystick
  78014. */
  78015. get: function () {
  78016. return this._buttonLeftStick;
  78017. },
  78018. /**
  78019. * Sets the value of the Left joystick
  78020. */
  78021. set: function (value) {
  78022. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  78023. },
  78024. enumerable: true,
  78025. configurable: true
  78026. });
  78027. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  78028. /**
  78029. * Gets the value of the Right joystick
  78030. */
  78031. get: function () {
  78032. return this._buttonRightStick;
  78033. },
  78034. /**
  78035. * Sets the value of the Right joystick
  78036. */
  78037. set: function (value) {
  78038. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  78039. },
  78040. enumerable: true,
  78041. configurable: true
  78042. });
  78043. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  78044. /**
  78045. * Gets the value of D-pad up
  78046. */
  78047. get: function () {
  78048. return this._dPadUp;
  78049. },
  78050. /**
  78051. * Sets the value of D-pad up
  78052. */
  78053. set: function (value) {
  78054. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  78055. },
  78056. enumerable: true,
  78057. configurable: true
  78058. });
  78059. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  78060. /**
  78061. * Gets the value of D-pad down
  78062. */
  78063. get: function () {
  78064. return this._dPadDown;
  78065. },
  78066. /**
  78067. * Sets the value of D-pad down
  78068. */
  78069. set: function (value) {
  78070. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  78071. },
  78072. enumerable: true,
  78073. configurable: true
  78074. });
  78075. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  78076. /**
  78077. * Gets the value of D-pad left
  78078. */
  78079. get: function () {
  78080. return this._dPadLeft;
  78081. },
  78082. /**
  78083. * Sets the value of D-pad left
  78084. */
  78085. set: function (value) {
  78086. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  78087. },
  78088. enumerable: true,
  78089. configurable: true
  78090. });
  78091. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  78092. /**
  78093. * Gets the value of D-pad right
  78094. */
  78095. get: function () {
  78096. return this._dPadRight;
  78097. },
  78098. /**
  78099. * Sets the value of D-pad right
  78100. */
  78101. set: function (value) {
  78102. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  78103. },
  78104. enumerable: true,
  78105. configurable: true
  78106. });
  78107. /**
  78108. * Force the gamepad to synchronize with device values
  78109. */
  78110. Xbox360Pad.prototype.update = function () {
  78111. _super.prototype.update.call(this);
  78112. if (this._isXboxOnePad) {
  78113. this.buttonA = this.browserGamepad.buttons[0].value;
  78114. this.buttonB = this.browserGamepad.buttons[1].value;
  78115. this.buttonX = this.browserGamepad.buttons[2].value;
  78116. this.buttonY = this.browserGamepad.buttons[3].value;
  78117. this.buttonLB = this.browserGamepad.buttons[4].value;
  78118. this.buttonRB = this.browserGamepad.buttons[5].value;
  78119. this.leftTrigger = this.browserGamepad.axes[2];
  78120. this.rightTrigger = this.browserGamepad.axes[5];
  78121. this.buttonBack = this.browserGamepad.buttons[9].value;
  78122. this.buttonStart = this.browserGamepad.buttons[8].value;
  78123. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  78124. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  78125. this.dPadUp = this.browserGamepad.buttons[11].value;
  78126. this.dPadDown = this.browserGamepad.buttons[12].value;
  78127. this.dPadLeft = this.browserGamepad.buttons[13].value;
  78128. this.dPadRight = this.browserGamepad.buttons[14].value;
  78129. }
  78130. else {
  78131. this.buttonA = this.browserGamepad.buttons[0].value;
  78132. this.buttonB = this.browserGamepad.buttons[1].value;
  78133. this.buttonX = this.browserGamepad.buttons[2].value;
  78134. this.buttonY = this.browserGamepad.buttons[3].value;
  78135. this.buttonLB = this.browserGamepad.buttons[4].value;
  78136. this.buttonRB = this.browserGamepad.buttons[5].value;
  78137. this.leftTrigger = this.browserGamepad.buttons[6].value;
  78138. this.rightTrigger = this.browserGamepad.buttons[7].value;
  78139. this.buttonBack = this.browserGamepad.buttons[8].value;
  78140. this.buttonStart = this.browserGamepad.buttons[9].value;
  78141. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  78142. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  78143. this.dPadUp = this.browserGamepad.buttons[12].value;
  78144. this.dPadDown = this.browserGamepad.buttons[13].value;
  78145. this.dPadLeft = this.browserGamepad.buttons[14].value;
  78146. this.dPadRight = this.browserGamepad.buttons[15].value;
  78147. }
  78148. };
  78149. /**
  78150. * Disposes the gamepad
  78151. */
  78152. Xbox360Pad.prototype.dispose = function () {
  78153. _super.prototype.dispose.call(this);
  78154. this.onButtonDownObservable.clear();
  78155. this.onButtonUpObservable.clear();
  78156. this.onPadDownObservable.clear();
  78157. this.onPadUpObservable.clear();
  78158. };
  78159. return Xbox360Pad;
  78160. }(BABYLON.Gamepad));
  78161. BABYLON.Xbox360Pad = Xbox360Pad;
  78162. })(BABYLON || (BABYLON = {}));
  78163. //# sourceMappingURL=babylon.xboxGamepad.js.map
  78164. var BABYLON;
  78165. (function (BABYLON) {
  78166. /**
  78167. * Defines the types of pose enabled controllers that are supported
  78168. */
  78169. var PoseEnabledControllerType;
  78170. (function (PoseEnabledControllerType) {
  78171. /**
  78172. * HTC Vive
  78173. */
  78174. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  78175. /**
  78176. * Oculus Rift
  78177. */
  78178. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  78179. /**
  78180. * Windows mixed reality
  78181. */
  78182. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  78183. /**
  78184. * Samsung gear VR
  78185. */
  78186. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  78187. /**
  78188. * Google Daydream
  78189. */
  78190. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  78191. /**
  78192. * Generic
  78193. */
  78194. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  78195. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  78196. /**
  78197. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  78198. */
  78199. var PoseEnabledControllerHelper = /** @class */ (function () {
  78200. function PoseEnabledControllerHelper() {
  78201. }
  78202. /**
  78203. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  78204. * @param vrGamepad the gamepad to initialized
  78205. * @returns a vr controller of the type the gamepad identified as
  78206. */
  78207. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  78208. // Oculus Touch
  78209. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  78210. return new BABYLON.OculusTouchController(vrGamepad);
  78211. }
  78212. // Windows Mixed Reality controllers
  78213. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  78214. return new BABYLON.WindowsMotionController(vrGamepad);
  78215. }
  78216. // HTC Vive
  78217. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  78218. return new BABYLON.ViveController(vrGamepad);
  78219. }
  78220. // Samsung/Oculus Gear VR or Oculus Go
  78221. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  78222. return new BABYLON.GearVRController(vrGamepad);
  78223. }
  78224. // Google Daydream
  78225. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  78226. return new BABYLON.DaydreamController(vrGamepad);
  78227. }
  78228. // Generic
  78229. else {
  78230. return new BABYLON.GenericController(vrGamepad);
  78231. }
  78232. };
  78233. return PoseEnabledControllerHelper;
  78234. }());
  78235. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  78236. /**
  78237. * Defines the PoseEnabledController object that contains state of a vr capable controller
  78238. */
  78239. var PoseEnabledController = /** @class */ (function (_super) {
  78240. __extends(PoseEnabledController, _super);
  78241. /**
  78242. * Creates a new PoseEnabledController from a gamepad
  78243. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  78244. */
  78245. function PoseEnabledController(browserGamepad) {
  78246. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  78247. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  78248. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  78249. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  78250. /**
  78251. * The device position in babylon space
  78252. */
  78253. _this.devicePosition = BABYLON.Vector3.Zero();
  78254. /**
  78255. * The device rotation in babylon space
  78256. */
  78257. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  78258. /**
  78259. * The scale factor of the device in babylon space
  78260. */
  78261. _this.deviceScaleFactor = 1;
  78262. // Used to convert 6dof controllers to 3dof
  78263. _this._trackPosition = true;
  78264. _this._maxRotationDistFromHeadset = Math.PI / 5;
  78265. _this._draggedRoomRotation = 0;
  78266. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  78267. /**
  78268. * Internal, matrix used to convert room space to babylon space
  78269. * @hidden
  78270. */
  78271. _this._deviceToWorld = BABYLON.Matrix.Identity();
  78272. /**
  78273. * Node to be used when casting a ray from the controller
  78274. * @hidden
  78275. */
  78276. _this._pointingPoseNode = null;
  78277. _this._workingMatrix = BABYLON.Matrix.Identity();
  78278. /**
  78279. * @hidden
  78280. */
  78281. _this._meshAttachedObservable = new BABYLON.Observable();
  78282. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  78283. _this.controllerType = PoseEnabledControllerType.GENERIC;
  78284. _this.position = BABYLON.Vector3.Zero();
  78285. _this.rotationQuaternion = new BABYLON.Quaternion();
  78286. _this._calculatedPosition = BABYLON.Vector3.Zero();
  78287. _this._calculatedRotation = new BABYLON.Quaternion();
  78288. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  78289. return _this;
  78290. }
  78291. /**
  78292. * @hidden
  78293. */
  78294. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  78295. if (this._trackPosition) {
  78296. this._calculatedPosition.copyFrom(fixedPosition);
  78297. this._trackPosition = false;
  78298. }
  78299. };
  78300. /**
  78301. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  78302. */
  78303. PoseEnabledController.prototype.update = function () {
  78304. _super.prototype.update.call(this);
  78305. this._updatePoseAndMesh();
  78306. };
  78307. /**
  78308. * Updates only the pose device and mesh without doing any button event checking
  78309. */
  78310. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  78311. var pose = this.browserGamepad.pose;
  78312. this.updateFromDevice(pose);
  78313. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  78314. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  78315. camera._computeDevicePosition();
  78316. this._deviceToWorld.setTranslation(camera.devicePosition);
  78317. if (camera.deviceRotationQuaternion) {
  78318. var camera = camera;
  78319. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  78320. // Find the radian distance away that the headset is from the controllers rotation
  78321. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  78322. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  78323. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  78324. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  78325. this._draggedRoomRotation += rotationAmount;
  78326. // Rotate controller around headset
  78327. var sin = Math.sin(-rotationAmount);
  78328. var cos = Math.cos(-rotationAmount);
  78329. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  78330. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  78331. }
  78332. }
  78333. }
  78334. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  78335. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  78336. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78337. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  78338. if (this._mesh) {
  78339. this._mesh.position.copyFrom(this.devicePosition);
  78340. if (this._mesh.rotationQuaternion) {
  78341. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  78342. }
  78343. }
  78344. };
  78345. /**
  78346. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  78347. * @param poseData raw pose fromthe device
  78348. */
  78349. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  78350. if (poseData) {
  78351. this.rawPose = poseData;
  78352. if (poseData.position) {
  78353. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  78354. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  78355. this._deviceRoomPosition.z *= -1;
  78356. }
  78357. if (this._trackPosition) {
  78358. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  78359. }
  78360. this._calculatedPosition.addInPlace(this.position);
  78361. }
  78362. var pose = this.rawPose;
  78363. if (poseData.orientation && pose.orientation) {
  78364. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  78365. if (this._mesh) {
  78366. if (this._mesh.getScene().useRightHandedSystem) {
  78367. this._deviceRoomRotationQuaternion.z *= -1;
  78368. this._deviceRoomRotationQuaternion.w *= -1;
  78369. }
  78370. else {
  78371. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  78372. }
  78373. }
  78374. // if the camera is set, rotate to the camera's rotation
  78375. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  78376. }
  78377. }
  78378. };
  78379. /**
  78380. * Attaches a mesh to the controller
  78381. * @param mesh the mesh to be attached
  78382. */
  78383. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  78384. if (this._mesh) {
  78385. this._mesh.parent = null;
  78386. }
  78387. this._mesh = mesh;
  78388. if (this._poseControlledCamera) {
  78389. this._mesh.parent = this._poseControlledCamera;
  78390. }
  78391. if (!this._mesh.rotationQuaternion) {
  78392. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  78393. }
  78394. // 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
  78395. this._updatePoseAndMesh();
  78396. if (this._pointingPoseNode) {
  78397. var parents = [];
  78398. var obj = this._pointingPoseNode;
  78399. while (obj.parent) {
  78400. parents.push(obj.parent);
  78401. obj = obj.parent;
  78402. }
  78403. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  78404. }
  78405. this._meshAttachedObservable.notifyObservers(mesh);
  78406. };
  78407. /**
  78408. * Attaches the controllers mesh to a camera
  78409. * @param camera the camera the mesh should be attached to
  78410. */
  78411. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  78412. this._poseControlledCamera = camera;
  78413. if (this._mesh) {
  78414. this._mesh.parent = this._poseControlledCamera;
  78415. }
  78416. };
  78417. /**
  78418. * Disposes of the controller
  78419. */
  78420. PoseEnabledController.prototype.dispose = function () {
  78421. if (this._mesh) {
  78422. this._mesh.dispose();
  78423. }
  78424. this._mesh = null;
  78425. _super.prototype.dispose.call(this);
  78426. };
  78427. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  78428. /**
  78429. * The mesh that is attached to the controller
  78430. */
  78431. get: function () {
  78432. return this._mesh;
  78433. },
  78434. enumerable: true,
  78435. configurable: true
  78436. });
  78437. /**
  78438. * Gets the ray of the controller in the direction the controller is pointing
  78439. * @param length the length the resulting ray should be
  78440. * @returns a ray in the direction the controller is pointing
  78441. */
  78442. PoseEnabledController.prototype.getForwardRay = function (length) {
  78443. if (length === void 0) { length = 100; }
  78444. if (!this.mesh) {
  78445. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  78446. }
  78447. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  78448. var origin = m.getTranslation();
  78449. var forward = new BABYLON.Vector3(0, 0, -1);
  78450. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  78451. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  78452. return new BABYLON.Ray(origin, direction, length);
  78453. };
  78454. /**
  78455. * Name of the child mesh that can be used to cast a ray from the controller
  78456. */
  78457. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  78458. return PoseEnabledController;
  78459. }(BABYLON.Gamepad));
  78460. BABYLON.PoseEnabledController = PoseEnabledController;
  78461. })(BABYLON || (BABYLON = {}));
  78462. //# sourceMappingURL=babylon.poseEnabledController.js.map
  78463. var BABYLON;
  78464. (function (BABYLON) {
  78465. /**
  78466. * Defines the WebVRController object that represents controllers tracked in 3D space
  78467. */
  78468. var WebVRController = /** @class */ (function (_super) {
  78469. __extends(WebVRController, _super);
  78470. /**
  78471. * Creates a new WebVRController from a gamepad
  78472. * @param vrGamepad the gamepad that the WebVRController should be created from
  78473. */
  78474. function WebVRController(vrGamepad) {
  78475. var _this = _super.call(this, vrGamepad) || this;
  78476. // Observables
  78477. /**
  78478. * Fired when the trigger state has changed
  78479. */
  78480. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  78481. /**
  78482. * Fired when the main button state has changed
  78483. */
  78484. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  78485. /**
  78486. * Fired when the secondary button state has changed
  78487. */
  78488. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  78489. /**
  78490. * Fired when the pad state has changed
  78491. */
  78492. _this.onPadStateChangedObservable = new BABYLON.Observable();
  78493. /**
  78494. * Fired when controllers stick values have changed
  78495. */
  78496. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  78497. /**
  78498. * X and Y axis corrisponding to the controllers joystick
  78499. */
  78500. _this.pad = { x: 0, y: 0 };
  78501. // avoid GC, store state in a tmp object
  78502. _this._changes = {
  78503. pressChanged: false,
  78504. touchChanged: false,
  78505. valueChanged: false,
  78506. changed: false
  78507. };
  78508. _this._buttons = new Array(vrGamepad.buttons.length);
  78509. _this.hand = vrGamepad.hand;
  78510. return _this;
  78511. }
  78512. /**
  78513. * Fired when a controller button's state has changed
  78514. * @param callback the callback containing the button that was modified
  78515. */
  78516. WebVRController.prototype.onButtonStateChange = function (callback) {
  78517. this._onButtonStateChange = callback;
  78518. };
  78519. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  78520. /**
  78521. * The default controller model for the controller
  78522. */
  78523. get: function () {
  78524. return this._defaultModel;
  78525. },
  78526. enumerable: true,
  78527. configurable: true
  78528. });
  78529. /**
  78530. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  78531. */
  78532. WebVRController.prototype.update = function () {
  78533. _super.prototype.update.call(this);
  78534. for (var index = 0; index < this._buttons.length; index++) {
  78535. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  78536. }
  78537. ;
  78538. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  78539. this.pad.x = this.leftStick.x;
  78540. this.pad.y = this.leftStick.y;
  78541. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  78542. }
  78543. };
  78544. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  78545. if (!newState) {
  78546. newState = {
  78547. pressed: false,
  78548. touched: false,
  78549. value: 0
  78550. };
  78551. }
  78552. if (!currentState) {
  78553. this._buttons[buttonIndex] = {
  78554. pressed: newState.pressed,
  78555. touched: newState.touched,
  78556. value: newState.value
  78557. };
  78558. return;
  78559. }
  78560. this._checkChanges(newState, currentState);
  78561. if (this._changes.changed) {
  78562. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  78563. this._handleButtonChange(buttonIndex, newState, this._changes);
  78564. }
  78565. this._buttons[buttonIndex].pressed = newState.pressed;
  78566. this._buttons[buttonIndex].touched = newState.touched;
  78567. // oculus triggers are never 0, thou not touched.
  78568. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  78569. };
  78570. WebVRController.prototype._checkChanges = function (newState, currentState) {
  78571. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  78572. this._changes.touchChanged = newState.touched !== currentState.touched;
  78573. this._changes.valueChanged = newState.value !== currentState.value;
  78574. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  78575. return this._changes;
  78576. };
  78577. /**
  78578. * Disposes of th webVRCOntroller
  78579. */
  78580. WebVRController.prototype.dispose = function () {
  78581. _super.prototype.dispose.call(this);
  78582. this.onTriggerStateChangedObservable.clear();
  78583. this.onMainButtonStateChangedObservable.clear();
  78584. this.onSecondaryButtonStateChangedObservable.clear();
  78585. this.onPadStateChangedObservable.clear();
  78586. this.onPadValuesChangedObservable.clear();
  78587. };
  78588. return WebVRController;
  78589. }(BABYLON.PoseEnabledController));
  78590. BABYLON.WebVRController = WebVRController;
  78591. })(BABYLON || (BABYLON = {}));
  78592. //# sourceMappingURL=babylon.webVRController.js.map
  78593. var BABYLON;
  78594. (function (BABYLON) {
  78595. /**
  78596. * Oculus Touch Controller
  78597. */
  78598. var OculusTouchController = /** @class */ (function (_super) {
  78599. __extends(OculusTouchController, _super);
  78600. /**
  78601. * Creates a new OculusTouchController from a gamepad
  78602. * @param vrGamepad the gamepad that the controller should be created from
  78603. */
  78604. function OculusTouchController(vrGamepad) {
  78605. var _this = _super.call(this, vrGamepad) || this;
  78606. /**
  78607. * Fired when the secondary trigger on this controller is modified
  78608. */
  78609. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  78610. /**
  78611. * Fired when the thumb rest on this controller is modified
  78612. */
  78613. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  78614. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  78615. return _this;
  78616. }
  78617. /**
  78618. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78619. * @param scene scene in which to add meshes
  78620. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78621. */
  78622. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78623. var _this = this;
  78624. var meshName;
  78625. // Hand
  78626. if (this.hand === 'left') {
  78627. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  78628. }
  78629. else { // Right is the default if no hand is specified
  78630. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  78631. }
  78632. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  78633. /*
  78634. Parent Mesh name: oculus_touch_left
  78635. - body
  78636. - trigger
  78637. - thumbstick
  78638. - grip
  78639. - button_y
  78640. - button_x
  78641. - button_enter
  78642. */
  78643. _this._defaultModel = newMeshes[1];
  78644. _this.attachToMesh(_this._defaultModel);
  78645. if (meshLoaded) {
  78646. meshLoaded(_this._defaultModel);
  78647. }
  78648. });
  78649. };
  78650. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  78651. /**
  78652. * Fired when the A button on this controller is modified
  78653. */
  78654. get: function () {
  78655. if (this.hand === 'right') {
  78656. return this.onMainButtonStateChangedObservable;
  78657. }
  78658. else {
  78659. throw new Error('No A button on left hand');
  78660. }
  78661. },
  78662. enumerable: true,
  78663. configurable: true
  78664. });
  78665. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  78666. /**
  78667. * Fired when the B button on this controller is modified
  78668. */
  78669. get: function () {
  78670. if (this.hand === 'right') {
  78671. return this.onSecondaryButtonStateChangedObservable;
  78672. }
  78673. else {
  78674. throw new Error('No B button on left hand');
  78675. }
  78676. },
  78677. enumerable: true,
  78678. configurable: true
  78679. });
  78680. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  78681. /**
  78682. * Fired when the X button on this controller is modified
  78683. */
  78684. get: function () {
  78685. if (this.hand === 'left') {
  78686. return this.onMainButtonStateChangedObservable;
  78687. }
  78688. else {
  78689. throw new Error('No X button on right hand');
  78690. }
  78691. },
  78692. enumerable: true,
  78693. configurable: true
  78694. });
  78695. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  78696. /**
  78697. * Fired when the Y button on this controller is modified
  78698. */
  78699. get: function () {
  78700. if (this.hand === 'left') {
  78701. return this.onSecondaryButtonStateChangedObservable;
  78702. }
  78703. else {
  78704. throw new Error('No Y button on right hand');
  78705. }
  78706. },
  78707. enumerable: true,
  78708. configurable: true
  78709. });
  78710. /**
  78711. * Called once for each button that changed state since the last frame
  78712. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  78713. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  78714. * 2) secondary trigger (same)
  78715. * 3) A (right) X (left), touch, pressed = value
  78716. * 4) B / Y
  78717. * 5) thumb rest
  78718. * @param buttonIdx Which button index changed
  78719. * @param state New state of the button
  78720. * @param changes Which properties on the state changed since last frame
  78721. */
  78722. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78723. var notifyObject = state; //{ state: state, changes: changes };
  78724. var triggerDirection = this.hand === 'right' ? -1 : 1;
  78725. switch (buttonIdx) {
  78726. case 0:
  78727. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  78728. return;
  78729. case 1: // index trigger
  78730. if (this._defaultModel) {
  78731. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  78732. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  78733. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  78734. }
  78735. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  78736. return;
  78737. case 2: // secondary trigger
  78738. if (this._defaultModel) {
  78739. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  78740. }
  78741. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  78742. return;
  78743. case 3:
  78744. if (this._defaultModel) {
  78745. if (notifyObject.pressed) {
  78746. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  78747. }
  78748. else {
  78749. (this._defaultModel.getChildren()[1]).position.y = 0;
  78750. }
  78751. }
  78752. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  78753. return;
  78754. case 4:
  78755. if (this._defaultModel) {
  78756. if (notifyObject.pressed) {
  78757. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  78758. }
  78759. else {
  78760. (this._defaultModel.getChildren()[2]).position.y = 0;
  78761. }
  78762. }
  78763. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  78764. return;
  78765. case 5:
  78766. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  78767. return;
  78768. }
  78769. };
  78770. /**
  78771. * Base Url for the controller model.
  78772. */
  78773. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  78774. /**
  78775. * File name for the left controller model.
  78776. */
  78777. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  78778. /**
  78779. * File name for the right controller model.
  78780. */
  78781. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  78782. return OculusTouchController;
  78783. }(BABYLON.WebVRController));
  78784. BABYLON.OculusTouchController = OculusTouchController;
  78785. })(BABYLON || (BABYLON = {}));
  78786. //# sourceMappingURL=babylon.oculusTouchController.js.map
  78787. var BABYLON;
  78788. (function (BABYLON) {
  78789. /**
  78790. * Vive Controller
  78791. */
  78792. var ViveController = /** @class */ (function (_super) {
  78793. __extends(ViveController, _super);
  78794. /**
  78795. * Creates a new ViveController from a gamepad
  78796. * @param vrGamepad the gamepad that the controller should be created from
  78797. */
  78798. function ViveController(vrGamepad) {
  78799. var _this = _super.call(this, vrGamepad) || this;
  78800. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  78801. _this._invertLeftStickY = true;
  78802. return _this;
  78803. }
  78804. /**
  78805. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78806. * @param scene scene in which to add meshes
  78807. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78808. */
  78809. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78810. var _this = this;
  78811. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  78812. /*
  78813. Parent Mesh name: ViveWand
  78814. - body
  78815. - r_gripper
  78816. - l_gripper
  78817. - menu_button
  78818. - system_button
  78819. - trackpad
  78820. - trigger
  78821. - LED
  78822. */
  78823. _this._defaultModel = newMeshes[1];
  78824. _this.attachToMesh(_this._defaultModel);
  78825. if (meshLoaded) {
  78826. meshLoaded(_this._defaultModel);
  78827. }
  78828. });
  78829. };
  78830. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  78831. /**
  78832. * Fired when the left button on this controller is modified
  78833. */
  78834. get: function () {
  78835. return this.onMainButtonStateChangedObservable;
  78836. },
  78837. enumerable: true,
  78838. configurable: true
  78839. });
  78840. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  78841. /**
  78842. * Fired when the right button on this controller is modified
  78843. */
  78844. get: function () {
  78845. return this.onMainButtonStateChangedObservable;
  78846. },
  78847. enumerable: true,
  78848. configurable: true
  78849. });
  78850. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  78851. /**
  78852. * Fired when the menu button on this controller is modified
  78853. */
  78854. get: function () {
  78855. return this.onSecondaryButtonStateChangedObservable;
  78856. },
  78857. enumerable: true,
  78858. configurable: true
  78859. });
  78860. /**
  78861. * Called once for each button that changed state since the last frame
  78862. * Vive mapping:
  78863. * 0: touchpad
  78864. * 1: trigger
  78865. * 2: left AND right buttons
  78866. * 3: menu button
  78867. * @param buttonIdx Which button index changed
  78868. * @param state New state of the button
  78869. * @param changes Which properties on the state changed since last frame
  78870. */
  78871. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78872. var notifyObject = state; //{ state: state, changes: changes };
  78873. switch (buttonIdx) {
  78874. case 0:
  78875. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  78876. return;
  78877. case 1: // index trigger
  78878. if (this._defaultModel) {
  78879. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  78880. }
  78881. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  78882. return;
  78883. case 2: // left AND right button
  78884. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  78885. return;
  78886. case 3:
  78887. if (this._defaultModel) {
  78888. if (notifyObject.pressed) {
  78889. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  78890. }
  78891. else {
  78892. (this._defaultModel.getChildren()[2]).position.y = 0;
  78893. }
  78894. }
  78895. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  78896. return;
  78897. }
  78898. };
  78899. /**
  78900. * Base Url for the controller model.
  78901. */
  78902. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  78903. /**
  78904. * File name for the controller model.
  78905. */
  78906. ViveController.MODEL_FILENAME = 'wand.babylon';
  78907. return ViveController;
  78908. }(BABYLON.WebVRController));
  78909. BABYLON.ViveController = ViveController;
  78910. })(BABYLON || (BABYLON = {}));
  78911. //# sourceMappingURL=babylon.viveController.js.map
  78912. var BABYLON;
  78913. (function (BABYLON) {
  78914. /**
  78915. * Generic Controller
  78916. */
  78917. var GenericController = /** @class */ (function (_super) {
  78918. __extends(GenericController, _super);
  78919. /**
  78920. * Creates a new GenericController from a gamepad
  78921. * @param vrGamepad the gamepad that the controller should be created from
  78922. */
  78923. function GenericController(vrGamepad) {
  78924. return _super.call(this, vrGamepad) || this;
  78925. }
  78926. /**
  78927. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78928. * @param scene scene in which to add meshes
  78929. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78930. */
  78931. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78932. var _this = this;
  78933. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  78934. _this._defaultModel = newMeshes[1];
  78935. _this.attachToMesh(_this._defaultModel);
  78936. if (meshLoaded) {
  78937. meshLoaded(_this._defaultModel);
  78938. }
  78939. });
  78940. };
  78941. /**
  78942. * Called once for each button that changed state since the last frame
  78943. * @param buttonIdx Which button index changed
  78944. * @param state New state of the button
  78945. * @param changes Which properties on the state changed since last frame
  78946. */
  78947. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78948. console.log("Button id: " + buttonIdx + "state: ");
  78949. console.dir(state);
  78950. };
  78951. /**
  78952. * Base Url for the controller model.
  78953. */
  78954. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78955. /**
  78956. * File name for the controller model.
  78957. */
  78958. GenericController.MODEL_FILENAME = 'generic.babylon';
  78959. return GenericController;
  78960. }(BABYLON.WebVRController));
  78961. BABYLON.GenericController = GenericController;
  78962. })(BABYLON || (BABYLON = {}));
  78963. //# sourceMappingURL=babylon.genericController.js.map
  78964. var BABYLON;
  78965. (function (BABYLON) {
  78966. /**
  78967. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  78968. */
  78969. var LoadedMeshInfo = /** @class */ (function () {
  78970. function LoadedMeshInfo() {
  78971. /**
  78972. * Map of the button meshes contained in the controller
  78973. */
  78974. this.buttonMeshes = {};
  78975. /**
  78976. * Map of the axis meshes contained in the controller
  78977. */
  78978. this.axisMeshes = {};
  78979. }
  78980. return LoadedMeshInfo;
  78981. }());
  78982. /**
  78983. * Defines the WindowsMotionController object that the state of the windows motion controller
  78984. */
  78985. var WindowsMotionController = /** @class */ (function (_super) {
  78986. __extends(WindowsMotionController, _super);
  78987. /**
  78988. * Creates a new WindowsMotionController from a gamepad
  78989. * @param vrGamepad the gamepad that the controller should be created from
  78990. */
  78991. function WindowsMotionController(vrGamepad) {
  78992. var _this = _super.call(this, vrGamepad) || this;
  78993. _this._mapping = {
  78994. // Semantic button names
  78995. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  78996. // A mapping of the button name to glTF model node name
  78997. // that should be transformed by button value.
  78998. buttonMeshNames: {
  78999. 'trigger': 'SELECT',
  79000. 'menu': 'MENU',
  79001. 'grip': 'GRASP',
  79002. 'thumbstick': 'THUMBSTICK_PRESS',
  79003. 'trackpad': 'TOUCHPAD_PRESS'
  79004. },
  79005. // This mapping is used to translate from the Motion Controller to Babylon semantics
  79006. buttonObservableNames: {
  79007. 'trigger': 'onTriggerStateChangedObservable',
  79008. 'menu': 'onSecondaryButtonStateChangedObservable',
  79009. 'grip': 'onMainButtonStateChangedObservable',
  79010. 'thumbstick': 'onPadStateChangedObservable',
  79011. 'trackpad': 'onTrackpadChangedObservable'
  79012. },
  79013. // A mapping of the axis name to glTF model node name
  79014. // that should be transformed by axis value.
  79015. // This array mirrors the browserGamepad.axes array, such that
  79016. // the mesh corresponding to axis 0 is in this array index 0.
  79017. axisMeshNames: [
  79018. 'THUMBSTICK_X',
  79019. 'THUMBSTICK_Y',
  79020. 'TOUCHPAD_TOUCH_X',
  79021. 'TOUCHPAD_TOUCH_Y'
  79022. ],
  79023. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  79024. };
  79025. /**
  79026. * Fired when the trackpad on this controller is clicked
  79027. */
  79028. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  79029. /**
  79030. * Fired when the trackpad on this controller is modified
  79031. */
  79032. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  79033. /**
  79034. * The current x and y values of this controller's trackpad
  79035. */
  79036. _this.trackpad = { x: 0, y: 0 };
  79037. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  79038. _this._loadedMeshInfo = null;
  79039. return _this;
  79040. }
  79041. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  79042. /**
  79043. * Fired when the trigger on this controller is modified
  79044. */
  79045. get: function () {
  79046. return this.onTriggerStateChangedObservable;
  79047. },
  79048. enumerable: true,
  79049. configurable: true
  79050. });
  79051. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  79052. /**
  79053. * Fired when the menu button on this controller is modified
  79054. */
  79055. get: function () {
  79056. return this.onSecondaryButtonStateChangedObservable;
  79057. },
  79058. enumerable: true,
  79059. configurable: true
  79060. });
  79061. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  79062. /**
  79063. * Fired when the grip button on this controller is modified
  79064. */
  79065. get: function () {
  79066. return this.onMainButtonStateChangedObservable;
  79067. },
  79068. enumerable: true,
  79069. configurable: true
  79070. });
  79071. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  79072. /**
  79073. * Fired when the thumbstick button on this controller is modified
  79074. */
  79075. get: function () {
  79076. return this.onPadStateChangedObservable;
  79077. },
  79078. enumerable: true,
  79079. configurable: true
  79080. });
  79081. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  79082. /**
  79083. * Fired when the touchpad button on this controller is modified
  79084. */
  79085. get: function () {
  79086. return this.onTrackpadChangedObservable;
  79087. },
  79088. enumerable: true,
  79089. configurable: true
  79090. });
  79091. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  79092. /**
  79093. * Fired when the touchpad values on this controller are modified
  79094. */
  79095. get: function () {
  79096. return this.onTrackpadValuesChangedObservable;
  79097. },
  79098. enumerable: true,
  79099. configurable: true
  79100. });
  79101. WindowsMotionController.prototype._updateTrackpad = function () {
  79102. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  79103. this.trackpad.x = this.browserGamepad["axes"][2];
  79104. this.trackpad.y = this.browserGamepad["axes"][3];
  79105. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  79106. }
  79107. };
  79108. /**
  79109. * Called once per frame by the engine.
  79110. */
  79111. WindowsMotionController.prototype.update = function () {
  79112. _super.prototype.update.call(this);
  79113. if (this.browserGamepad.axes) {
  79114. this._updateTrackpad();
  79115. // Only need to animate axes if there is a loaded mesh
  79116. if (this._loadedMeshInfo) {
  79117. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  79118. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  79119. }
  79120. }
  79121. }
  79122. };
  79123. /**
  79124. * Called once for each button that changed state since the last frame
  79125. * @param buttonIdx Which button index changed
  79126. * @param state New state of the button
  79127. * @param changes Which properties on the state changed since last frame
  79128. */
  79129. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79130. var buttonName = this._mapping.buttons[buttonIdx];
  79131. if (!buttonName) {
  79132. return;
  79133. }
  79134. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  79135. this._updateTrackpad();
  79136. // Only emit events for buttons that we know how to map from index to name
  79137. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  79138. if (observable) {
  79139. observable.notifyObservers(state);
  79140. }
  79141. this._lerpButtonTransform(buttonName, state.value);
  79142. };
  79143. /**
  79144. * Moves the buttons on the controller mesh based on their current state
  79145. * @param buttonName the name of the button to move
  79146. * @param buttonValue the value of the button which determines the buttons new position
  79147. */
  79148. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  79149. // If there is no loaded mesh, there is nothing to transform.
  79150. if (!this._loadedMeshInfo) {
  79151. return;
  79152. }
  79153. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  79154. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  79155. return;
  79156. }
  79157. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  79158. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  79159. };
  79160. /**
  79161. * Moves the axis on the controller mesh based on its current state
  79162. * @param axis the index of the axis
  79163. * @param axisValue the value of the axis which determines the meshes new position
  79164. * @hidden
  79165. */
  79166. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  79167. if (!this._loadedMeshInfo) {
  79168. return;
  79169. }
  79170. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  79171. if (!meshInfo) {
  79172. return;
  79173. }
  79174. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  79175. return;
  79176. }
  79177. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  79178. var lerpValue = axisValue * 0.5 + 0.5;
  79179. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  79180. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  79181. };
  79182. /**
  79183. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79184. * @param scene scene in which to add meshes
  79185. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79186. */
  79187. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  79188. var _this = this;
  79189. if (forceDefault === void 0) { forceDefault = false; }
  79190. var path;
  79191. var filename;
  79192. // Checking if GLB loader is present
  79193. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  79194. // Determine the device specific folder based on the ID suffix
  79195. var device = 'default';
  79196. if (this.id && !forceDefault) {
  79197. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  79198. device = ((match && match[0]) || device);
  79199. }
  79200. // Hand
  79201. if (this.hand === 'left') {
  79202. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  79203. }
  79204. else { // Right is the default if no hand is specified
  79205. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  79206. }
  79207. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  79208. }
  79209. else {
  79210. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  79211. path = BABYLON.GenericController.MODEL_BASE_URL;
  79212. filename = BABYLON.GenericController.MODEL_FILENAME;
  79213. }
  79214. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  79215. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  79216. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  79217. if (!_this._loadedMeshInfo) {
  79218. return;
  79219. }
  79220. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  79221. _this.attachToMesh(_this._defaultModel);
  79222. if (meshLoaded) {
  79223. meshLoaded(_this._defaultModel);
  79224. }
  79225. }, null, function (scene, message) {
  79226. BABYLON.Tools.Log(message);
  79227. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  79228. if (!forceDefault) {
  79229. _this.initControllerMesh(scene, meshLoaded, true);
  79230. }
  79231. });
  79232. };
  79233. /**
  79234. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  79235. * can be transformed by button presses and axes values, based on this._mapping.
  79236. *
  79237. * @param scene scene in which the meshes exist
  79238. * @param meshes list of meshes that make up the controller model to process
  79239. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  79240. */
  79241. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  79242. var loadedMeshInfo = null;
  79243. // Create a new mesh to contain the glTF hierarchy
  79244. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  79245. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  79246. var childMesh = null;
  79247. for (var i = 0; i < meshes.length; i++) {
  79248. var mesh = meshes[i];
  79249. if (!mesh.parent) {
  79250. // Exclude controller meshes from picking results
  79251. mesh.isPickable = false;
  79252. // Handle root node, attach to the new parentMesh
  79253. childMesh = mesh;
  79254. break;
  79255. }
  79256. }
  79257. if (childMesh) {
  79258. childMesh.setParent(parentMesh);
  79259. // Create our mesh info. Note that this method will always return non-null.
  79260. loadedMeshInfo = this.createMeshInfo(parentMesh);
  79261. }
  79262. else {
  79263. BABYLON.Tools.Warn('Could not find root node in model file.');
  79264. }
  79265. return loadedMeshInfo;
  79266. };
  79267. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  79268. var loadedMeshInfo = new LoadedMeshInfo();
  79269. var i;
  79270. loadedMeshInfo.rootNode = rootNode;
  79271. // Reset the caches
  79272. loadedMeshInfo.buttonMeshes = {};
  79273. loadedMeshInfo.axisMeshes = {};
  79274. // Button Meshes
  79275. for (i = 0; i < this._mapping.buttons.length; i++) {
  79276. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  79277. if (!buttonMeshName) {
  79278. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  79279. continue;
  79280. }
  79281. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  79282. if (!buttonMesh) {
  79283. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  79284. continue;
  79285. }
  79286. var buttonMeshInfo = {
  79287. index: i,
  79288. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  79289. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  79290. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  79291. };
  79292. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  79293. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  79294. }
  79295. else {
  79296. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  79297. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  79298. '(VALUE: ' + !!buttonMeshInfo.value +
  79299. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  79300. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  79301. ')');
  79302. }
  79303. }
  79304. // Axis Meshes
  79305. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  79306. var axisMeshName = this._mapping.axisMeshNames[i];
  79307. if (!axisMeshName) {
  79308. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  79309. continue;
  79310. }
  79311. var axisMesh = getChildByName(rootNode, axisMeshName);
  79312. if (!axisMesh) {
  79313. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  79314. continue;
  79315. }
  79316. var axisMeshInfo = {
  79317. index: i,
  79318. value: getImmediateChildByName(axisMesh, 'VALUE'),
  79319. min: getImmediateChildByName(axisMesh, 'MIN'),
  79320. max: getImmediateChildByName(axisMesh, 'MAX')
  79321. };
  79322. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  79323. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  79324. }
  79325. else {
  79326. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  79327. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  79328. '(VALUE: ' + !!axisMeshInfo.value +
  79329. ', MIN: ' + !!axisMeshInfo.min +
  79330. ', MAX:' + !!axisMeshInfo.max +
  79331. ')');
  79332. }
  79333. }
  79334. // Pointing Ray
  79335. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  79336. if (!loadedMeshInfo.pointingPoseNode) {
  79337. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  79338. }
  79339. else {
  79340. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  79341. }
  79342. return loadedMeshInfo;
  79343. // Look through all children recursively. This will return null if no mesh exists with the given name.
  79344. function getChildByName(node, name) {
  79345. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  79346. }
  79347. // Look through only immediate children. This will return null if no mesh exists with the given name.
  79348. function getImmediateChildByName(node, name) {
  79349. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  79350. }
  79351. };
  79352. /**
  79353. * Gets the ray of the controller in the direction the controller is pointing
  79354. * @param length the length the resulting ray should be
  79355. * @returns a ray in the direction the controller is pointing
  79356. */
  79357. WindowsMotionController.prototype.getForwardRay = function (length) {
  79358. if (length === void 0) { length = 100; }
  79359. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  79360. return _super.prototype.getForwardRay.call(this, length);
  79361. }
  79362. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  79363. var origin = m.getTranslation();
  79364. var forward = new BABYLON.Vector3(0, 0, -1);
  79365. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  79366. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  79367. return new BABYLON.Ray(origin, direction, length);
  79368. };
  79369. /**
  79370. * Disposes of the controller
  79371. */
  79372. WindowsMotionController.prototype.dispose = function () {
  79373. _super.prototype.dispose.call(this);
  79374. this.onTrackpadChangedObservable.clear();
  79375. };
  79376. /**
  79377. * The base url used to load the left and right controller models
  79378. */
  79379. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  79380. /**
  79381. * The name of the left controller model file
  79382. */
  79383. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  79384. /**
  79385. * The name of the right controller model file
  79386. */
  79387. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  79388. /**
  79389. * The controller name prefix for this controller type
  79390. */
  79391. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  79392. /**
  79393. * The controller id pattern for this controller type
  79394. */
  79395. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  79396. return WindowsMotionController;
  79397. }(BABYLON.WebVRController));
  79398. BABYLON.WindowsMotionController = WindowsMotionController;
  79399. })(BABYLON || (BABYLON = {}));
  79400. //# sourceMappingURL=babylon.windowsMotionController.js.map
  79401. var BABYLON;
  79402. (function (BABYLON) {
  79403. /**
  79404. * Gear VR Controller
  79405. */
  79406. var GearVRController = /** @class */ (function (_super) {
  79407. __extends(GearVRController, _super);
  79408. /**
  79409. * Creates a new GearVRController from a gamepad
  79410. * @param vrGamepad the gamepad that the controller should be created from
  79411. */
  79412. function GearVRController(vrGamepad) {
  79413. var _this = _super.call(this, vrGamepad) || this;
  79414. _this._buttonIndexToObservableNameMap = [
  79415. 'onTrackpadChangedObservable',
  79416. 'onTriggerStateChangedObservable' // Trigger
  79417. ];
  79418. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  79419. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  79420. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  79421. _this._disableTrackPosition(_this._calculatedPosition);
  79422. return _this;
  79423. }
  79424. /**
  79425. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79426. * @param scene scene in which to add meshes
  79427. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79428. */
  79429. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79430. var _this = this;
  79431. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  79432. // Offset the controller so it will rotate around the users wrist
  79433. var mesh = new BABYLON.Mesh("", scene);
  79434. newMeshes[1].parent = mesh;
  79435. newMeshes[1].position.z = -0.15;
  79436. _this._defaultModel = mesh;
  79437. _this.attachToMesh(_this._defaultModel);
  79438. if (meshLoaded) {
  79439. meshLoaded(_this._defaultModel);
  79440. }
  79441. });
  79442. };
  79443. /**
  79444. * Called once for each button that changed state since the last frame
  79445. * @param buttonIdx Which button index changed
  79446. * @param state New state of the button
  79447. * @param changes Which properties on the state changed since last frame
  79448. */
  79449. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79450. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  79451. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  79452. // Only emit events for buttons that we know how to map from index to observable
  79453. var observable = this[observableName];
  79454. if (observable) {
  79455. observable.notifyObservers(state);
  79456. }
  79457. }
  79458. };
  79459. /**
  79460. * Base Url for the controller model.
  79461. */
  79462. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79463. /**
  79464. * File name for the controller model.
  79465. */
  79466. GearVRController.MODEL_FILENAME = 'generic.babylon';
  79467. /**
  79468. * Gamepad Id prefix used to identify this controller.
  79469. */
  79470. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  79471. return GearVRController;
  79472. }(BABYLON.WebVRController));
  79473. BABYLON.GearVRController = GearVRController;
  79474. })(BABYLON || (BABYLON = {}));
  79475. //# sourceMappingURL=babylon.gearVRController.js.map
  79476. var BABYLON;
  79477. (function (BABYLON) {
  79478. /**
  79479. * Google Daydream controller
  79480. */
  79481. var DaydreamController = /** @class */ (function (_super) {
  79482. __extends(DaydreamController, _super);
  79483. /**
  79484. * Creates a new DaydreamController from a gamepad
  79485. * @param vrGamepad the gamepad that the controller should be created from
  79486. */
  79487. function DaydreamController(vrGamepad) {
  79488. var _this = _super.call(this, vrGamepad) || this;
  79489. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  79490. return _this;
  79491. }
  79492. /**
  79493. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79494. * @param scene scene in which to add meshes
  79495. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79496. */
  79497. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79498. var _this = this;
  79499. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  79500. _this._defaultModel = newMeshes[1];
  79501. _this.attachToMesh(_this._defaultModel);
  79502. if (meshLoaded) {
  79503. meshLoaded(_this._defaultModel);
  79504. }
  79505. });
  79506. };
  79507. /**
  79508. * Called once for each button that changed state since the last frame
  79509. * @param buttonIdx Which button index changed
  79510. * @param state New state of the button
  79511. * @param changes Which properties on the state changed since last frame
  79512. */
  79513. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79514. // Daydream controller only has 1 GamepadButton (on the trackpad).
  79515. if (buttonIdx === 0) {
  79516. var observable = this.onTriggerStateChangedObservable;
  79517. if (observable) {
  79518. observable.notifyObservers(state);
  79519. }
  79520. }
  79521. else {
  79522. // If the app or home buttons are ever made available
  79523. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  79524. }
  79525. };
  79526. /**
  79527. * Base Url for the controller model.
  79528. */
  79529. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79530. /**
  79531. * File name for the controller model.
  79532. */
  79533. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  79534. /**
  79535. * Gamepad Id prefix used to identify Daydream Controller.
  79536. */
  79537. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  79538. return DaydreamController;
  79539. }(BABYLON.WebVRController));
  79540. BABYLON.DaydreamController = DaydreamController;
  79541. })(BABYLON || (BABYLON = {}));
  79542. //# sourceMappingURL=babylon.daydreamController.js.map
  79543. var BABYLON;
  79544. (function (BABYLON) {
  79545. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  79546. get: function () {
  79547. if (!this._gamepadManager) {
  79548. this._gamepadManager = new BABYLON.GamepadManager(this);
  79549. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  79550. if (!component) {
  79551. component = new GamepadSystemSceneComponent(this);
  79552. this._addComponent(component);
  79553. }
  79554. }
  79555. return this._gamepadManager;
  79556. },
  79557. enumerable: true,
  79558. configurable: true
  79559. });
  79560. /**
  79561. * Adds a gamepad to the free camera inputs manager
  79562. */
  79563. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  79564. this.add(new BABYLON.FreeCameraGamepadInput());
  79565. return this;
  79566. };
  79567. /**
  79568. * Adds a gamepad to the arc rotate camera inputs manager
  79569. */
  79570. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  79571. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  79572. return this;
  79573. };
  79574. /**
  79575. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  79576. */
  79577. var GamepadSystemSceneComponent = /** @class */ (function () {
  79578. /**
  79579. * Creates a new instance of the component for the given scene
  79580. * @param scene Defines the scene to register the component in
  79581. */
  79582. function GamepadSystemSceneComponent(scene) {
  79583. /**
  79584. * The component name helpfull to identify the component in the list of scene components.
  79585. */
  79586. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  79587. this.scene = scene;
  79588. }
  79589. /**
  79590. * Registers the component in a given scene
  79591. */
  79592. GamepadSystemSceneComponent.prototype.register = function () {
  79593. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  79594. };
  79595. /**
  79596. * Rebuilds the elements related to this component in case of
  79597. * context lost for instance.
  79598. */
  79599. GamepadSystemSceneComponent.prototype.rebuild = function () {
  79600. // Nothing to do for gamepads
  79601. };
  79602. /**
  79603. * Disposes the component and the associated ressources
  79604. */
  79605. GamepadSystemSceneComponent.prototype.dispose = function () {
  79606. var gamepadManager = this.scene._gamepadManager;
  79607. if (gamepadManager) {
  79608. gamepadManager.dispose();
  79609. this.scene._gamepadManager = null;
  79610. }
  79611. };
  79612. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  79613. var gamepadManager = this.scene._gamepadManager;
  79614. if (gamepadManager && gamepadManager._isMonitoring) {
  79615. gamepadManager._checkGamepadsStatus();
  79616. }
  79617. };
  79618. return GamepadSystemSceneComponent;
  79619. }());
  79620. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  79621. })(BABYLON || (BABYLON = {}));
  79622. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  79623. var BABYLON;
  79624. (function (BABYLON) {
  79625. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  79626. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  79627. });
  79628. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  79629. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  79630. });
  79631. /**
  79632. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  79633. * an arc rotate version arcFollowCamera are available.
  79634. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79635. */
  79636. var FollowCamera = /** @class */ (function (_super) {
  79637. __extends(FollowCamera, _super);
  79638. /**
  79639. * Instantiates the follow camera.
  79640. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79641. * @param name Define the name of the camera in the scene
  79642. * @param position Define the position of the camera
  79643. * @param scene Define the scene the camera belong to
  79644. * @param lockedTarget Define the target of the camera
  79645. */
  79646. function FollowCamera(name, position, scene, lockedTarget) {
  79647. if (lockedTarget === void 0) { lockedTarget = null; }
  79648. var _this = _super.call(this, name, position, scene) || this;
  79649. /**
  79650. * Distance the follow camera should follow an object at
  79651. */
  79652. _this.radius = 12;
  79653. /**
  79654. * Define a rotation offset between the camera and the object it follows
  79655. */
  79656. _this.rotationOffset = 0;
  79657. /**
  79658. * Define a height offset between the camera and the object it follows.
  79659. * It can help following an object from the top (like a car chaing a plane)
  79660. */
  79661. _this.heightOffset = 4;
  79662. /**
  79663. * Define how fast the camera can accelerate to follow it s target.
  79664. */
  79665. _this.cameraAcceleration = 0.05;
  79666. /**
  79667. * Define the speed limit of the camera following an object.
  79668. */
  79669. _this.maxCameraSpeed = 20;
  79670. _this.lockedTarget = lockedTarget;
  79671. return _this;
  79672. }
  79673. FollowCamera.prototype._follow = function (cameraTarget) {
  79674. if (!cameraTarget)
  79675. return;
  79676. var yRotation;
  79677. if (cameraTarget.rotationQuaternion) {
  79678. var rotMatrix = new BABYLON.Matrix();
  79679. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  79680. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  79681. }
  79682. else {
  79683. yRotation = cameraTarget.rotation.y;
  79684. }
  79685. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  79686. var targetPosition = cameraTarget.getAbsolutePosition();
  79687. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  79688. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  79689. var dx = targetX - this.position.x;
  79690. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  79691. var dz = (targetZ) - this.position.z;
  79692. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  79693. var vy = dy * this.cameraAcceleration;
  79694. var vz = dz * this.cameraAcceleration * 2;
  79695. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  79696. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79697. }
  79698. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  79699. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79700. }
  79701. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  79702. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79703. }
  79704. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  79705. this.setTarget(targetPosition);
  79706. };
  79707. /** @hidden */
  79708. FollowCamera.prototype._checkInputs = function () {
  79709. _super.prototype._checkInputs.call(this);
  79710. if (this.lockedTarget) {
  79711. this._follow(this.lockedTarget);
  79712. }
  79713. };
  79714. /**
  79715. * Gets the camera class name.
  79716. * @returns the class name
  79717. */
  79718. FollowCamera.prototype.getClassName = function () {
  79719. return "FollowCamera";
  79720. };
  79721. __decorate([
  79722. BABYLON.serialize()
  79723. ], FollowCamera.prototype, "radius", void 0);
  79724. __decorate([
  79725. BABYLON.serialize()
  79726. ], FollowCamera.prototype, "rotationOffset", void 0);
  79727. __decorate([
  79728. BABYLON.serialize()
  79729. ], FollowCamera.prototype, "heightOffset", void 0);
  79730. __decorate([
  79731. BABYLON.serialize()
  79732. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  79733. __decorate([
  79734. BABYLON.serialize()
  79735. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  79736. __decorate([
  79737. BABYLON.serializeAsMeshReference("lockedTargetId")
  79738. ], FollowCamera.prototype, "lockedTarget", void 0);
  79739. return FollowCamera;
  79740. }(BABYLON.TargetCamera));
  79741. BABYLON.FollowCamera = FollowCamera;
  79742. /**
  79743. * Arc Rotate version of the follow camera.
  79744. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  79745. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79746. */
  79747. var ArcFollowCamera = /** @class */ (function (_super) {
  79748. __extends(ArcFollowCamera, _super);
  79749. /**
  79750. * Instantiates a new ArcFollowCamera
  79751. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79752. * @param name Define the name of the camera
  79753. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  79754. * @param beta Define the rotation angle of the camera around the elevation axis
  79755. * @param radius Define the radius of the camera from its target point
  79756. * @param target Define the target of the camera
  79757. * @param scene Define the scene the camera belongs to
  79758. */
  79759. function ArcFollowCamera(name,
  79760. /** The longitudinal angle of the camera */
  79761. alpha,
  79762. /** The latitudinal angle of the camera */
  79763. beta,
  79764. /** The radius of the camera from its target */
  79765. radius,
  79766. /** Define the camera target (the messh it should follow) */
  79767. target, scene) {
  79768. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  79769. _this.alpha = alpha;
  79770. _this.beta = beta;
  79771. _this.radius = radius;
  79772. _this.target = target;
  79773. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  79774. _this._follow();
  79775. return _this;
  79776. }
  79777. ArcFollowCamera.prototype._follow = function () {
  79778. if (!this.target) {
  79779. return;
  79780. }
  79781. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  79782. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  79783. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  79784. var targetPosition = this.target.getAbsolutePosition();
  79785. this.position = targetPosition.add(this._cartesianCoordinates);
  79786. this.setTarget(targetPosition);
  79787. };
  79788. /** @hidden */
  79789. ArcFollowCamera.prototype._checkInputs = function () {
  79790. _super.prototype._checkInputs.call(this);
  79791. this._follow();
  79792. };
  79793. /**
  79794. * Returns the class name of the object.
  79795. * It is mostly used internally for serialization purposes.
  79796. */
  79797. ArcFollowCamera.prototype.getClassName = function () {
  79798. return "ArcFollowCamera";
  79799. };
  79800. return ArcFollowCamera;
  79801. }(BABYLON.TargetCamera));
  79802. BABYLON.ArcFollowCamera = ArcFollowCamera;
  79803. })(BABYLON || (BABYLON = {}));
  79804. //# sourceMappingURL=babylon.followCamera.js.map
  79805. var BABYLON;
  79806. (function (BABYLON) {
  79807. /**
  79808. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  79809. * which still works and will still be found in many Playgrounds.
  79810. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79811. */
  79812. var UniversalCamera = /** @class */ (function (_super) {
  79813. __extends(UniversalCamera, _super);
  79814. /**
  79815. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  79816. * which still works and will still be found in many Playgrounds.
  79817. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79818. * @param name Define the name of the camera in the scene
  79819. * @param position Define the start position of the camera in the scene
  79820. * @param scene Define the scene the camera belongs to
  79821. */
  79822. function UniversalCamera(name, position, scene) {
  79823. var _this = _super.call(this, name, position, scene) || this;
  79824. _this.inputs.addGamepad();
  79825. return _this;
  79826. }
  79827. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  79828. /**
  79829. * Defines the gamepad rotation sensiblity.
  79830. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79831. */
  79832. get: function () {
  79833. var gamepad = this.inputs.attached["gamepad"];
  79834. if (gamepad)
  79835. return gamepad.gamepadAngularSensibility;
  79836. return 0;
  79837. },
  79838. set: function (value) {
  79839. var gamepad = this.inputs.attached["gamepad"];
  79840. if (gamepad)
  79841. gamepad.gamepadAngularSensibility = value;
  79842. },
  79843. enumerable: true,
  79844. configurable: true
  79845. });
  79846. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  79847. /**
  79848. * Defines the gamepad move sensiblity.
  79849. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79850. */
  79851. get: function () {
  79852. var gamepad = this.inputs.attached["gamepad"];
  79853. if (gamepad)
  79854. return gamepad.gamepadMoveSensibility;
  79855. return 0;
  79856. },
  79857. set: function (value) {
  79858. var gamepad = this.inputs.attached["gamepad"];
  79859. if (gamepad)
  79860. gamepad.gamepadMoveSensibility = value;
  79861. },
  79862. enumerable: true,
  79863. configurable: true
  79864. });
  79865. /**
  79866. * Gets the current object class name.
  79867. * @return the class name
  79868. */
  79869. UniversalCamera.prototype.getClassName = function () {
  79870. return "UniversalCamera";
  79871. };
  79872. return UniversalCamera;
  79873. }(BABYLON.TouchCamera));
  79874. BABYLON.UniversalCamera = UniversalCamera;
  79875. })(BABYLON || (BABYLON = {}));
  79876. //# sourceMappingURL=babylon.universalCamera.js.map
  79877. var BABYLON;
  79878. (function (BABYLON) {
  79879. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  79880. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  79881. });
  79882. /**
  79883. * This represents a FPS type of camera. This is only here for back compat purpose.
  79884. * Please use the UniversalCamera instead as both are identical.
  79885. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79886. */
  79887. var GamepadCamera = /** @class */ (function (_super) {
  79888. __extends(GamepadCamera, _super);
  79889. /**
  79890. * Instantiates a new Gamepad Camera
  79891. * This represents a FPS type of camera. This is only here for back compat purpose.
  79892. * Please use the UniversalCamera instead as both are identical.
  79893. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79894. * @param name Define the name of the camera in the scene
  79895. * @param position Define the start position of the camera in the scene
  79896. * @param scene Define the scene the camera belongs to
  79897. */
  79898. function GamepadCamera(name, position, scene) {
  79899. return _super.call(this, name, position, scene) || this;
  79900. }
  79901. /**
  79902. * Gets the current object class name.
  79903. * @return the class name
  79904. */
  79905. GamepadCamera.prototype.getClassName = function () {
  79906. return "GamepadCamera";
  79907. };
  79908. return GamepadCamera;
  79909. }(BABYLON.UniversalCamera));
  79910. BABYLON.GamepadCamera = GamepadCamera;
  79911. })(BABYLON || (BABYLON = {}));
  79912. //# sourceMappingURL=babylon.gamepadCamera.js.map
  79913. var BABYLON;
  79914. (function (BABYLON) {
  79915. var PostProcessRenderPipelineManager = /** @class */ (function () {
  79916. function PostProcessRenderPipelineManager() {
  79917. this._renderPipelines = {};
  79918. }
  79919. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  79920. this._renderPipelines[renderPipeline._name] = renderPipeline;
  79921. };
  79922. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  79923. if (unique === void 0) { unique = false; }
  79924. var renderPipeline = this._renderPipelines[renderPipelineName];
  79925. if (!renderPipeline) {
  79926. return;
  79927. }
  79928. renderPipeline._attachCameras(cameras, unique);
  79929. };
  79930. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  79931. var renderPipeline = this._renderPipelines[renderPipelineName];
  79932. if (!renderPipeline) {
  79933. return;
  79934. }
  79935. renderPipeline._detachCameras(cameras);
  79936. };
  79937. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79938. var renderPipeline = this._renderPipelines[renderPipelineName];
  79939. if (!renderPipeline) {
  79940. return;
  79941. }
  79942. renderPipeline._enableEffect(renderEffectName, cameras);
  79943. };
  79944. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79945. var renderPipeline = this._renderPipelines[renderPipelineName];
  79946. if (!renderPipeline) {
  79947. return;
  79948. }
  79949. renderPipeline._disableEffect(renderEffectName, cameras);
  79950. };
  79951. PostProcessRenderPipelineManager.prototype.update = function () {
  79952. for (var renderPipelineName in this._renderPipelines) {
  79953. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79954. var pipeline = this._renderPipelines[renderPipelineName];
  79955. if (!pipeline.isSupported) {
  79956. pipeline.dispose();
  79957. delete this._renderPipelines[renderPipelineName];
  79958. }
  79959. else {
  79960. pipeline._update();
  79961. }
  79962. }
  79963. }
  79964. };
  79965. /** @hidden */
  79966. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  79967. for (var renderPipelineName in this._renderPipelines) {
  79968. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79969. var pipeline = this._renderPipelines[renderPipelineName];
  79970. pipeline._rebuild();
  79971. }
  79972. }
  79973. };
  79974. PostProcessRenderPipelineManager.prototype.dispose = function () {
  79975. for (var renderPipelineName in this._renderPipelines) {
  79976. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79977. var pipeline = this._renderPipelines[renderPipelineName];
  79978. pipeline.dispose();
  79979. }
  79980. }
  79981. };
  79982. return PostProcessRenderPipelineManager;
  79983. }());
  79984. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  79985. })(BABYLON || (BABYLON = {}));
  79986. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  79987. var BABYLON;
  79988. (function (BABYLON) {
  79989. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  79990. get: function () {
  79991. if (!this._postProcessRenderPipelineManager) {
  79992. // Register the G Buffer component to the scene.
  79993. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  79994. if (!component) {
  79995. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  79996. this._addComponent(component);
  79997. }
  79998. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  79999. }
  80000. return this._postProcessRenderPipelineManager;
  80001. },
  80002. enumerable: true,
  80003. configurable: true
  80004. });
  80005. /**
  80006. * Defines the Render Pipeline scene component responsible to rendering pipelines
  80007. */
  80008. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  80009. /**
  80010. * Creates a new instance of the component for the given scene
  80011. * @param scene Defines the scene to register the component in
  80012. */
  80013. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  80014. /**
  80015. * The component name helpfull to identify the component in the list of scene components.
  80016. */
  80017. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  80018. this.scene = scene;
  80019. }
  80020. /**
  80021. * Registers the component in a given scene
  80022. */
  80023. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  80024. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  80025. };
  80026. /**
  80027. * Rebuilds the elements related to this component in case of
  80028. * context lost for instance.
  80029. */
  80030. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  80031. if (this.scene._postProcessRenderPipelineManager) {
  80032. this.scene._postProcessRenderPipelineManager._rebuild();
  80033. }
  80034. };
  80035. /**
  80036. * Disposes the component and the associated ressources
  80037. */
  80038. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  80039. if (this.scene._postProcessRenderPipelineManager) {
  80040. this.scene._postProcessRenderPipelineManager.dispose();
  80041. }
  80042. };
  80043. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80044. if (this.scene._postProcessRenderPipelineManager) {
  80045. this.scene._postProcessRenderPipelineManager.update();
  80046. }
  80047. };
  80048. return PostProcessRenderPipelineManagerSceneComponent;
  80049. }());
  80050. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  80051. })(BABYLON || (BABYLON = {}));
  80052. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  80053. var BABYLON;
  80054. (function (BABYLON) {
  80055. /**
  80056. * This represents a set of one or more post processes in Babylon.
  80057. * A post process can be used to apply a shader to a texture after it is rendered.
  80058. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  80059. */
  80060. var PostProcessRenderEffect = /** @class */ (function () {
  80061. /**
  80062. * Instantiates a post process render effect.
  80063. * A post process can be used to apply a shader to a texture after it is rendered.
  80064. * @param engine The engine the effect is tied to
  80065. * @param name The name of the effect
  80066. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  80067. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  80068. */
  80069. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  80070. this._name = name;
  80071. this._singleInstance = singleInstance || true;
  80072. this._getPostProcesses = getPostProcesses;
  80073. this._cameras = {};
  80074. this._indicesForCamera = {};
  80075. this._postProcesses = {};
  80076. }
  80077. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  80078. /**
  80079. * Checks if all the post processes in the effect are supported.
  80080. */
  80081. get: function () {
  80082. for (var index in this._postProcesses) {
  80083. if (this._postProcesses.hasOwnProperty(index)) {
  80084. var pps = this._postProcesses[index];
  80085. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  80086. if (!pps[ppIndex].isSupported) {
  80087. return false;
  80088. }
  80089. }
  80090. }
  80091. }
  80092. return true;
  80093. },
  80094. enumerable: true,
  80095. configurable: true
  80096. });
  80097. /**
  80098. * Updates the current state of the effect
  80099. * @hidden
  80100. */
  80101. PostProcessRenderEffect.prototype._update = function () {
  80102. };
  80103. /**
  80104. * Attaches the effect on cameras
  80105. * @param cameras The camera to attach to.
  80106. * @hidden
  80107. */
  80108. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  80109. var _this = this;
  80110. var cameraKey;
  80111. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80112. if (!cams) {
  80113. return;
  80114. }
  80115. for (var i = 0; i < cams.length; i++) {
  80116. var camera = cams[i];
  80117. var cameraName = camera.name;
  80118. if (this._singleInstance) {
  80119. cameraKey = 0;
  80120. }
  80121. else {
  80122. cameraKey = cameraName;
  80123. }
  80124. if (!this._postProcesses[cameraKey]) {
  80125. var postProcess = this._getPostProcesses();
  80126. if (postProcess) {
  80127. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  80128. }
  80129. }
  80130. if (!this._indicesForCamera[cameraName]) {
  80131. this._indicesForCamera[cameraName] = [];
  80132. }
  80133. this._postProcesses[cameraKey].forEach(function (postProcess) {
  80134. var index = camera.attachPostProcess(postProcess);
  80135. _this._indicesForCamera[cameraName].push(index);
  80136. });
  80137. if (!this._cameras[cameraName]) {
  80138. this._cameras[cameraName] = camera;
  80139. }
  80140. }
  80141. };
  80142. /**
  80143. * Detatches the effect on cameras
  80144. * @param cameras The camera to detatch from.
  80145. * @hidden
  80146. */
  80147. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  80148. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80149. if (!cams) {
  80150. return;
  80151. }
  80152. for (var i = 0; i < cams.length; i++) {
  80153. var camera = cams[i];
  80154. var cameraName = camera.name;
  80155. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80156. camera.detachPostProcess(postProcess);
  80157. });
  80158. if (this._cameras[cameraName]) {
  80159. //this._indicesForCamera.splice(index, 1);
  80160. this._cameras[cameraName] = null;
  80161. }
  80162. }
  80163. };
  80164. /**
  80165. * Enables the effect on given cameras
  80166. * @param cameras The camera to enable.
  80167. * @hidden
  80168. */
  80169. PostProcessRenderEffect.prototype._enable = function (cameras) {
  80170. var _this = this;
  80171. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80172. if (!cams) {
  80173. return;
  80174. }
  80175. for (var i = 0; i < cams.length; i++) {
  80176. var camera = cams[i];
  80177. var cameraName = camera.name;
  80178. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  80179. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  80180. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80181. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  80182. });
  80183. }
  80184. }
  80185. }
  80186. };
  80187. /**
  80188. * Disables the effect on the given cameras
  80189. * @param cameras The camera to disable.
  80190. * @hidden
  80191. */
  80192. PostProcessRenderEffect.prototype._disable = function (cameras) {
  80193. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80194. if (!cams) {
  80195. return;
  80196. }
  80197. for (var i = 0; i < cams.length; i++) {
  80198. var camera = cams[i];
  80199. var cameraName = camera.name;
  80200. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80201. camera.detachPostProcess(postProcess);
  80202. });
  80203. }
  80204. };
  80205. /**
  80206. * Gets a list of the post processes contained in the effect.
  80207. * @param camera The camera to get the post processes on.
  80208. * @returns The list of the post processes in the effect.
  80209. */
  80210. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  80211. if (this._singleInstance) {
  80212. return this._postProcesses[0];
  80213. }
  80214. else {
  80215. if (!camera) {
  80216. return null;
  80217. }
  80218. return this._postProcesses[camera.name];
  80219. }
  80220. };
  80221. return PostProcessRenderEffect;
  80222. }());
  80223. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  80224. })(BABYLON || (BABYLON = {}));
  80225. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  80226. var BABYLON;
  80227. (function (BABYLON) {
  80228. var PostProcessRenderPipeline = /** @class */ (function () {
  80229. function PostProcessRenderPipeline(engine, name) {
  80230. this.engine = engine;
  80231. this._name = name;
  80232. this._renderEffects = {};
  80233. this._renderEffectsForIsolatedPass = new Array();
  80234. this._cameras = [];
  80235. }
  80236. PostProcessRenderPipeline.prototype.getClassName = function () {
  80237. return "PostProcessRenderPipeline";
  80238. };
  80239. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  80240. get: function () {
  80241. for (var renderEffectName in this._renderEffects) {
  80242. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80243. if (!this._renderEffects[renderEffectName].isSupported) {
  80244. return false;
  80245. }
  80246. }
  80247. }
  80248. return true;
  80249. },
  80250. enumerable: true,
  80251. configurable: true
  80252. });
  80253. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  80254. this._renderEffects[renderEffect._name] = renderEffect;
  80255. };
  80256. // private
  80257. /** @hidden */
  80258. PostProcessRenderPipeline.prototype._rebuild = function () {
  80259. };
  80260. /** @hidden */
  80261. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  80262. var renderEffects = this._renderEffects[renderEffectName];
  80263. if (!renderEffects) {
  80264. return;
  80265. }
  80266. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  80267. };
  80268. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  80269. var renderEffects = this._renderEffects[renderEffectName];
  80270. if (!renderEffects) {
  80271. return;
  80272. }
  80273. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  80274. };
  80275. /** @hidden */
  80276. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  80277. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80278. if (!cams) {
  80279. return;
  80280. }
  80281. var indicesToDelete = [];
  80282. var i;
  80283. for (i = 0; i < cams.length; i++) {
  80284. var camera = cams[i];
  80285. var cameraName = camera.name;
  80286. if (this._cameras.indexOf(camera) === -1) {
  80287. this._cameras[cameraName] = camera;
  80288. }
  80289. else if (unique) {
  80290. indicesToDelete.push(i);
  80291. }
  80292. }
  80293. for (i = 0; i < indicesToDelete.length; i++) {
  80294. cameras.splice(indicesToDelete[i], 1);
  80295. }
  80296. for (var renderEffectName in this._renderEffects) {
  80297. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80298. this._renderEffects[renderEffectName]._attachCameras(cams);
  80299. }
  80300. }
  80301. };
  80302. /** @hidden */
  80303. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  80304. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80305. if (!cams) {
  80306. return;
  80307. }
  80308. for (var renderEffectName in this._renderEffects) {
  80309. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80310. this._renderEffects[renderEffectName]._detachCameras(cams);
  80311. }
  80312. }
  80313. for (var i = 0; i < cams.length; i++) {
  80314. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  80315. }
  80316. };
  80317. /** @hidden */
  80318. PostProcessRenderPipeline.prototype._update = function () {
  80319. for (var renderEffectName in this._renderEffects) {
  80320. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80321. this._renderEffects[renderEffectName]._update();
  80322. }
  80323. }
  80324. for (var i = 0; i < this._cameras.length; i++) {
  80325. var cameraName = this._cameras[i].name;
  80326. if (this._renderEffectsForIsolatedPass[cameraName]) {
  80327. this._renderEffectsForIsolatedPass[cameraName]._update();
  80328. }
  80329. }
  80330. };
  80331. /** @hidden */
  80332. PostProcessRenderPipeline.prototype._reset = function () {
  80333. this._renderEffects = {};
  80334. this._renderEffectsForIsolatedPass = new Array();
  80335. };
  80336. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  80337. // 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)
  80338. var effectKeys = Object.keys(this._renderEffects);
  80339. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  80340. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  80341. if (postProcesses) {
  80342. postProcesses[0].samples = sampleCount;
  80343. return true;
  80344. }
  80345. }
  80346. return false;
  80347. };
  80348. PostProcessRenderPipeline.prototype.dispose = function () {
  80349. // Must be implemented by children
  80350. };
  80351. __decorate([
  80352. BABYLON.serialize()
  80353. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  80354. return PostProcessRenderPipeline;
  80355. }());
  80356. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  80357. })(BABYLON || (BABYLON = {}));
  80358. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  80359. var BABYLON;
  80360. (function (BABYLON) {
  80361. /**
  80362. * This represents a depth renderer in Babylon.
  80363. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  80364. */
  80365. var DepthRenderer = /** @class */ (function () {
  80366. /**
  80367. * Instantiates a depth renderer
  80368. * @param scene The scene the renderer belongs to
  80369. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  80370. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  80371. */
  80372. function DepthRenderer(scene, type, camera) {
  80373. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  80374. if (camera === void 0) { camera = null; }
  80375. var _this = this;
  80376. /**
  80377. * Specifiess that the depth renderer will only be used within
  80378. * the camera it is created for.
  80379. * This can help forcing its rendering during the camera processing.
  80380. */
  80381. this.useOnlyInActiveCamera = false;
  80382. this._scene = scene;
  80383. // Register the G Buffer component to the scene.
  80384. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  80385. if (!component) {
  80386. component = new BABYLON.DepthRendererSceneComponent(scene);
  80387. scene._addComponent(component);
  80388. }
  80389. this._camera = camera;
  80390. var engine = scene.getEngine();
  80391. // Render target
  80392. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  80393. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80394. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80395. this._depthMap.refreshRate = 1;
  80396. this._depthMap.renderParticles = false;
  80397. this._depthMap.renderList = null;
  80398. // Camera to get depth map from to support multiple concurrent cameras
  80399. this._depthMap.activeCamera = this._camera;
  80400. this._depthMap.ignoreCameraViewport = true;
  80401. this._depthMap.useCameraPostProcesses = false;
  80402. // set default depth value to 1.0 (far away)
  80403. this._depthMap.onClearObservable.add(function (engine) {
  80404. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  80405. });
  80406. // Custom render function
  80407. var renderSubMesh = function (subMesh) {
  80408. var mesh = subMesh.getRenderingMesh();
  80409. var scene = _this._scene;
  80410. var engine = scene.getEngine();
  80411. var material = subMesh.getMaterial();
  80412. if (!material) {
  80413. return;
  80414. }
  80415. // Culling and reverse (right handed system)
  80416. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  80417. // Managing instances
  80418. var batch = mesh._getInstancesRenderList(subMesh._id);
  80419. if (batch.mustReturn) {
  80420. return;
  80421. }
  80422. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80423. var camera = _this._camera || scene.activeCamera;
  80424. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  80425. engine.enableEffect(_this._effect);
  80426. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  80427. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80428. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  80429. // Alpha test
  80430. if (material && material.needAlphaTesting()) {
  80431. var alphaTexture = material.getAlphaTestTexture();
  80432. if (alphaTexture) {
  80433. _this._effect.setTexture("diffuseSampler", alphaTexture);
  80434. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80435. }
  80436. }
  80437. // Bones
  80438. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80439. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80440. }
  80441. // Draw
  80442. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  80443. }
  80444. };
  80445. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80446. var index;
  80447. if (depthOnlySubMeshes.length) {
  80448. engine.setColorWrite(false);
  80449. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80450. renderSubMesh(depthOnlySubMeshes.data[index]);
  80451. }
  80452. engine.setColorWrite(true);
  80453. }
  80454. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80455. renderSubMesh(opaqueSubMeshes.data[index]);
  80456. }
  80457. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80458. renderSubMesh(alphaTestSubMeshes.data[index]);
  80459. }
  80460. };
  80461. }
  80462. /**
  80463. * Creates the depth rendering effect and checks if the effect is ready.
  80464. * @param subMesh The submesh to be used to render the depth map of
  80465. * @param useInstances If multiple world instances should be used
  80466. * @returns if the depth renderer is ready to render the depth map
  80467. */
  80468. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  80469. var material = subMesh.getMaterial();
  80470. if (material.disableDepthWrite) {
  80471. return false;
  80472. }
  80473. var defines = [];
  80474. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80475. var mesh = subMesh.getMesh();
  80476. // Alpha test
  80477. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  80478. defines.push("#define ALPHATEST");
  80479. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80480. attribs.push(BABYLON.VertexBuffer.UVKind);
  80481. defines.push("#define UV1");
  80482. }
  80483. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80484. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80485. defines.push("#define UV2");
  80486. }
  80487. }
  80488. // Bones
  80489. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80490. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80491. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80492. if (mesh.numBoneInfluencers > 4) {
  80493. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80494. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80495. }
  80496. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80497. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80498. }
  80499. else {
  80500. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80501. }
  80502. // Instances
  80503. if (useInstances) {
  80504. defines.push("#define INSTANCES");
  80505. attribs.push("world0");
  80506. attribs.push("world1");
  80507. attribs.push("world2");
  80508. attribs.push("world3");
  80509. }
  80510. // Get correct effect
  80511. var join = defines.join("\n");
  80512. if (this._cachedDefines !== join) {
  80513. this._cachedDefines = join;
  80514. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  80515. }
  80516. return this._effect.isReady();
  80517. };
  80518. /**
  80519. * Gets the texture which the depth map will be written to.
  80520. * @returns The depth map texture
  80521. */
  80522. DepthRenderer.prototype.getDepthMap = function () {
  80523. return this._depthMap;
  80524. };
  80525. /**
  80526. * Disposes of the depth renderer.
  80527. */
  80528. DepthRenderer.prototype.dispose = function () {
  80529. this._depthMap.dispose();
  80530. };
  80531. return DepthRenderer;
  80532. }());
  80533. BABYLON.DepthRenderer = DepthRenderer;
  80534. })(BABYLON || (BABYLON = {}));
  80535. //# sourceMappingURL=babylon.depthRenderer.js.map
  80536. var BABYLON;
  80537. (function (BABYLON) {
  80538. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  80539. camera = camera || this.activeCamera;
  80540. if (!camera) {
  80541. throw "No camera available to enable depth renderer";
  80542. }
  80543. if (!this._depthRenderer) {
  80544. this._depthRenderer = {};
  80545. }
  80546. if (!this._depthRenderer[camera.id]) {
  80547. var textureType = 0;
  80548. if (this.getEngine().getCaps().textureHalfFloatRender) {
  80549. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80550. }
  80551. else if (this.getEngine().getCaps().textureFloatRender) {
  80552. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80553. }
  80554. else {
  80555. throw "Depth renderer does not support int texture type";
  80556. }
  80557. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  80558. }
  80559. return this._depthRenderer[camera.id];
  80560. };
  80561. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  80562. camera = camera || this.activeCamera;
  80563. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  80564. return;
  80565. }
  80566. this._depthRenderer[camera.id].dispose();
  80567. delete this._depthRenderer[camera.id];
  80568. };
  80569. /**
  80570. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  80571. * in several rendering techniques.
  80572. */
  80573. var DepthRendererSceneComponent = /** @class */ (function () {
  80574. /**
  80575. * Creates a new instance of the component for the given scene
  80576. * @param scene Defines the scene to register the component in
  80577. */
  80578. function DepthRendererSceneComponent(scene) {
  80579. /**
  80580. * The component name helpfull to identify the component in the list of scene components.
  80581. */
  80582. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  80583. this.scene = scene;
  80584. }
  80585. /**
  80586. * Registers the component in a given scene
  80587. */
  80588. DepthRendererSceneComponent.prototype.register = function () {
  80589. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  80590. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  80591. };
  80592. /**
  80593. * Rebuilds the elements related to this component in case of
  80594. * context lost for instance.
  80595. */
  80596. DepthRendererSceneComponent.prototype.rebuild = function () {
  80597. // Nothing to do for this component
  80598. };
  80599. /**
  80600. * Disposes the component and the associated ressources
  80601. */
  80602. DepthRendererSceneComponent.prototype.dispose = function () {
  80603. for (var key in this.scene._depthRenderer) {
  80604. this.scene._depthRenderer[key].dispose();
  80605. }
  80606. };
  80607. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80608. if (this.scene._depthRenderer) {
  80609. for (var key in this.scene._depthRenderer) {
  80610. var depthRenderer = this.scene._depthRenderer[key];
  80611. if (!depthRenderer.useOnlyInActiveCamera) {
  80612. renderTargets.push(depthRenderer.getDepthMap());
  80613. }
  80614. }
  80615. }
  80616. };
  80617. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  80618. if (this.scene._depthRenderer) {
  80619. for (var key in this.scene._depthRenderer) {
  80620. var depthRenderer = this.scene._depthRenderer[key];
  80621. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  80622. renderTargets.push(depthRenderer.getDepthMap());
  80623. }
  80624. }
  80625. }
  80626. };
  80627. return DepthRendererSceneComponent;
  80628. }());
  80629. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  80630. })(BABYLON || (BABYLON = {}));
  80631. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  80632. var BABYLON;
  80633. (function (BABYLON) {
  80634. /**
  80635. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  80636. */
  80637. var GeometryBufferRenderer = /** @class */ (function () {
  80638. /**
  80639. * Creates a new G Buffer for the scene
  80640. * @param scene The scene the buffer belongs to
  80641. * @param ratio How big is the buffer related to the main canvas.
  80642. */
  80643. function GeometryBufferRenderer(scene, ratio) {
  80644. if (ratio === void 0) { ratio = 1; }
  80645. this._enablePosition = false;
  80646. this._scene = scene;
  80647. this._ratio = ratio;
  80648. // Register the G Buffer component to the scene.
  80649. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  80650. if (!component) {
  80651. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  80652. scene._addComponent(component);
  80653. }
  80654. // Render target
  80655. this._createRenderTargets();
  80656. }
  80657. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  80658. /**
  80659. * Set the render list (meshes to be rendered) used in the G buffer.
  80660. */
  80661. set: function (meshes) {
  80662. this._multiRenderTarget.renderList = meshes;
  80663. },
  80664. enumerable: true,
  80665. configurable: true
  80666. });
  80667. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  80668. /**
  80669. * Gets wether or not G buffer are supported by the running hardware.
  80670. * This requires draw buffer supports
  80671. */
  80672. get: function () {
  80673. return this._multiRenderTarget.isSupported;
  80674. },
  80675. enumerable: true,
  80676. configurable: true
  80677. });
  80678. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  80679. /**
  80680. * Gets wether or not position are enabled for the G buffer.
  80681. */
  80682. get: function () {
  80683. return this._enablePosition;
  80684. },
  80685. /**
  80686. * Sets wether or not position are enabled for the G buffer.
  80687. */
  80688. set: function (enable) {
  80689. this._enablePosition = enable;
  80690. this.dispose();
  80691. this._createRenderTargets();
  80692. },
  80693. enumerable: true,
  80694. configurable: true
  80695. });
  80696. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  80697. /**
  80698. * Gets the scene associated with the buffer.
  80699. */
  80700. get: function () {
  80701. return this._scene;
  80702. },
  80703. enumerable: true,
  80704. configurable: true
  80705. });
  80706. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  80707. /**
  80708. * Gets the ratio used by the buffer during its creation.
  80709. * How big is the buffer related to the main canvas.
  80710. */
  80711. get: function () {
  80712. return this._ratio;
  80713. },
  80714. enumerable: true,
  80715. configurable: true
  80716. });
  80717. /**
  80718. * Checks wether everything is ready to render a submesh to the G buffer.
  80719. * @param subMesh the submesh to check readiness for
  80720. * @param useInstances is the mesh drawn using instance or not
  80721. * @returns true if ready otherwise false
  80722. */
  80723. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  80724. var material = subMesh.getMaterial();
  80725. if (material && material.disableDepthWrite) {
  80726. return false;
  80727. }
  80728. var defines = [];
  80729. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  80730. var mesh = subMesh.getMesh();
  80731. // Alpha test
  80732. if (material && material.needAlphaTesting()) {
  80733. defines.push("#define ALPHATEST");
  80734. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80735. attribs.push(BABYLON.VertexBuffer.UVKind);
  80736. defines.push("#define UV1");
  80737. }
  80738. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80739. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80740. defines.push("#define UV2");
  80741. }
  80742. }
  80743. // Buffers
  80744. if (this._enablePosition) {
  80745. defines.push("#define POSITION");
  80746. }
  80747. // Bones
  80748. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80749. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80750. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80751. if (mesh.numBoneInfluencers > 4) {
  80752. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80753. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80754. }
  80755. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80756. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80757. }
  80758. else {
  80759. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80760. }
  80761. // Instances
  80762. if (useInstances) {
  80763. defines.push("#define INSTANCES");
  80764. attribs.push("world0");
  80765. attribs.push("world1");
  80766. attribs.push("world2");
  80767. attribs.push("world3");
  80768. }
  80769. // Get correct effect
  80770. var join = defines.join("\n");
  80771. if (this._cachedDefines !== join) {
  80772. this._cachedDefines = join;
  80773. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  80774. }
  80775. return this._effect.isReady();
  80776. };
  80777. /**
  80778. * Gets the current underlying G Buffer.
  80779. * @returns the buffer
  80780. */
  80781. GeometryBufferRenderer.prototype.getGBuffer = function () {
  80782. return this._multiRenderTarget;
  80783. };
  80784. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  80785. /**
  80786. * Gets the number of samples used to render the buffer (anti aliasing).
  80787. */
  80788. get: function () {
  80789. return this._multiRenderTarget.samples;
  80790. },
  80791. /**
  80792. * Sets the number of samples used to render the buffer (anti aliasing).
  80793. */
  80794. set: function (value) {
  80795. this._multiRenderTarget.samples = value;
  80796. },
  80797. enumerable: true,
  80798. configurable: true
  80799. });
  80800. /**
  80801. * Disposes the renderer and frees up associated resources.
  80802. */
  80803. GeometryBufferRenderer.prototype.dispose = function () {
  80804. this.getGBuffer().dispose();
  80805. };
  80806. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  80807. var _this = this;
  80808. var engine = this._scene.getEngine();
  80809. var count = this._enablePosition ? 3 : 2;
  80810. 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 });
  80811. if (!this.isSupported) {
  80812. return;
  80813. }
  80814. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80815. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80816. this._multiRenderTarget.refreshRate = 1;
  80817. this._multiRenderTarget.renderParticles = false;
  80818. this._multiRenderTarget.renderList = null;
  80819. // set default depth value to 1.0 (far away)
  80820. this._multiRenderTarget.onClearObservable.add(function (engine) {
  80821. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  80822. });
  80823. // Custom render function
  80824. var renderSubMesh = function (subMesh) {
  80825. var mesh = subMesh.getRenderingMesh();
  80826. var scene = _this._scene;
  80827. var engine = scene.getEngine();
  80828. var material = subMesh.getMaterial();
  80829. if (!material) {
  80830. return;
  80831. }
  80832. // Culling
  80833. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  80834. // Managing instances
  80835. var batch = mesh._getInstancesRenderList(subMesh._id);
  80836. if (batch.mustReturn) {
  80837. return;
  80838. }
  80839. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80840. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  80841. engine.enableEffect(_this._effect);
  80842. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  80843. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80844. _this._effect.setMatrix("view", scene.getViewMatrix());
  80845. // Alpha test
  80846. if (material && material.needAlphaTesting()) {
  80847. var alphaTexture = material.getAlphaTestTexture();
  80848. if (alphaTexture) {
  80849. _this._effect.setTexture("diffuseSampler", alphaTexture);
  80850. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80851. }
  80852. }
  80853. // Bones
  80854. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80855. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80856. }
  80857. // Draw
  80858. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  80859. }
  80860. };
  80861. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80862. var index;
  80863. if (depthOnlySubMeshes.length) {
  80864. engine.setColorWrite(false);
  80865. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80866. renderSubMesh(depthOnlySubMeshes.data[index]);
  80867. }
  80868. engine.setColorWrite(true);
  80869. }
  80870. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80871. renderSubMesh(opaqueSubMeshes.data[index]);
  80872. }
  80873. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80874. renderSubMesh(alphaTestSubMeshes.data[index]);
  80875. }
  80876. };
  80877. };
  80878. return GeometryBufferRenderer;
  80879. }());
  80880. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  80881. })(BABYLON || (BABYLON = {}));
  80882. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  80883. var BABYLON;
  80884. (function (BABYLON) {
  80885. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  80886. get: function () {
  80887. this._geometryBufferRenderer;
  80888. },
  80889. set: function (value) {
  80890. if (value && value.isSupported) {
  80891. this._geometryBufferRenderer = value;
  80892. }
  80893. ;
  80894. },
  80895. enumerable: true,
  80896. configurable: true
  80897. });
  80898. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  80899. if (ratio === void 0) { ratio = 1; }
  80900. if (this._geometryBufferRenderer) {
  80901. return this._geometryBufferRenderer;
  80902. }
  80903. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  80904. if (!this._geometryBufferRenderer.isSupported) {
  80905. this._geometryBufferRenderer = null;
  80906. }
  80907. return this._geometryBufferRenderer;
  80908. };
  80909. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  80910. if (!this._geometryBufferRenderer) {
  80911. return;
  80912. }
  80913. this._geometryBufferRenderer.dispose();
  80914. this._geometryBufferRenderer = null;
  80915. };
  80916. /**
  80917. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  80918. * in several rendering techniques.
  80919. */
  80920. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  80921. /**
  80922. * Creates a new instance of the component for the given scene
  80923. * @param scene Defines the scene to register the component in
  80924. */
  80925. function GeometryBufferRendererSceneComponent(scene) {
  80926. /**
  80927. * The component name helpful to identify the component in the list of scene components.
  80928. */
  80929. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  80930. this.scene = scene;
  80931. }
  80932. /**
  80933. * Registers the component in a given scene
  80934. */
  80935. GeometryBufferRendererSceneComponent.prototype.register = function () {
  80936. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  80937. };
  80938. /**
  80939. * Rebuilds the elements related to this component in case of
  80940. * context lost for instance.
  80941. */
  80942. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  80943. // Nothing to do for this component
  80944. };
  80945. /**
  80946. * Disposes the component and the associated ressources
  80947. */
  80948. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  80949. // Nothing to do for this component
  80950. };
  80951. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80952. if (this.scene._geometryBufferRenderer) {
  80953. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  80954. }
  80955. };
  80956. return GeometryBufferRendererSceneComponent;
  80957. }());
  80958. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  80959. })(BABYLON || (BABYLON = {}));
  80960. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  80961. var BABYLON;
  80962. (function (BABYLON) {
  80963. var SSAORenderingPipeline = /** @class */ (function (_super) {
  80964. __extends(SSAORenderingPipeline, _super);
  80965. /**
  80966. * @constructor
  80967. * @param {string} name - The rendering pipeline name
  80968. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80969. * @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 }
  80970. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80971. */
  80972. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  80973. var _this = _super.call(this, scene.getEngine(), name) || this;
  80974. // Members
  80975. /**
  80976. * The PassPostProcess id in the pipeline that contains the original scene color
  80977. */
  80978. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  80979. /**
  80980. * The SSAO PostProcess id in the pipeline
  80981. */
  80982. _this.SSAORenderEffect = "SSAORenderEffect";
  80983. /**
  80984. * The horizontal blur PostProcess id in the pipeline
  80985. */
  80986. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  80987. /**
  80988. * The vertical blur PostProcess id in the pipeline
  80989. */
  80990. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  80991. /**
  80992. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  80993. */
  80994. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  80995. /**
  80996. * The output strength of the SSAO post-process. Default value is 1.0.
  80997. */
  80998. _this.totalStrength = 1.0;
  80999. /**
  81000. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  81001. */
  81002. _this.radius = 0.0001;
  81003. /**
  81004. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  81005. * Must not be equal to fallOff and superior to fallOff.
  81006. * Default value is 0.975
  81007. */
  81008. _this.area = 0.0075;
  81009. /**
  81010. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  81011. * Must not be equal to area and inferior to area.
  81012. * Default value is 0.0
  81013. */
  81014. _this.fallOff = 0.000001;
  81015. /**
  81016. * The base color of the SSAO post-process
  81017. * The final result is "base + ssao" between [0, 1]
  81018. */
  81019. _this.base = 0.5;
  81020. _this._firstUpdate = true;
  81021. _this._scene = scene;
  81022. // Set up assets
  81023. _this._createRandomTexture();
  81024. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81025. var ssaoRatio = ratio.ssaoRatio || ratio;
  81026. var combineRatio = ratio.combineRatio || ratio;
  81027. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  81028. _this._createSSAOPostProcess(ssaoRatio);
  81029. _this._createBlurPostProcess(ssaoRatio);
  81030. _this._createSSAOCombinePostProcess(combineRatio);
  81031. // Set up pipeline
  81032. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  81033. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  81034. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  81035. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  81036. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  81037. // Finish
  81038. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81039. if (cameras)
  81040. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81041. return _this;
  81042. }
  81043. // Public Methods
  81044. /**
  81045. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  81046. */
  81047. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  81048. if (disableDepthRender === void 0) { disableDepthRender = false; }
  81049. for (var i = 0; i < this._scene.cameras.length; i++) {
  81050. var camera = this._scene.cameras[i];
  81051. this._originalColorPostProcess.dispose(camera);
  81052. this._ssaoPostProcess.dispose(camera);
  81053. this._blurHPostProcess.dispose(camera);
  81054. this._blurVPostProcess.dispose(camera);
  81055. this._ssaoCombinePostProcess.dispose(camera);
  81056. }
  81057. this._randomTexture.dispose();
  81058. if (disableDepthRender)
  81059. this._scene.disableDepthRenderer();
  81060. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81061. _super.prototype.dispose.call(this);
  81062. };
  81063. // Private Methods
  81064. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  81065. var _this = this;
  81066. var size = 16;
  81067. 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);
  81068. 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);
  81069. this._blurHPostProcess.onActivateObservable.add(function () {
  81070. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  81071. _this._blurHPostProcess.kernel = size * dw;
  81072. });
  81073. this._blurVPostProcess.onActivateObservable.add(function () {
  81074. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  81075. _this._blurVPostProcess.kernel = size * dw;
  81076. });
  81077. };
  81078. /** @hidden */
  81079. SSAORenderingPipeline.prototype._rebuild = function () {
  81080. this._firstUpdate = true;
  81081. _super.prototype._rebuild.call(this);
  81082. };
  81083. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  81084. var _this = this;
  81085. var numSamples = 16;
  81086. var sampleSphere = [
  81087. 0.5381, 0.1856, -0.4319,
  81088. 0.1379, 0.2486, 0.4430,
  81089. 0.3371, 0.5679, -0.0057,
  81090. -0.6999, -0.0451, -0.0019,
  81091. 0.0689, -0.1598, -0.8547,
  81092. 0.0560, 0.0069, -0.1843,
  81093. -0.0146, 0.1402, 0.0762,
  81094. 0.0100, -0.1924, -0.0344,
  81095. -0.3577, -0.5301, -0.4358,
  81096. -0.3169, 0.1063, 0.0158,
  81097. 0.0103, -0.5869, 0.0046,
  81098. -0.0897, -0.4940, 0.3287,
  81099. 0.7119, -0.0154, -0.0918,
  81100. -0.0533, 0.0596, -0.5411,
  81101. 0.0352, -0.0631, 0.5460,
  81102. -0.4776, 0.2847, -0.0271
  81103. ];
  81104. var samplesFactor = 1.0 / numSamples;
  81105. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  81106. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  81107. "area", "fallOff", "base", "range", "viewport"
  81108. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  81109. this._ssaoPostProcess.onApply = function (effect) {
  81110. if (_this._firstUpdate) {
  81111. effect.setArray3("sampleSphere", sampleSphere);
  81112. effect.setFloat("samplesFactor", samplesFactor);
  81113. effect.setFloat("randTextureTiles", 4.0);
  81114. }
  81115. effect.setFloat("totalStrength", _this.totalStrength);
  81116. effect.setFloat("radius", _this.radius);
  81117. effect.setFloat("area", _this.area);
  81118. effect.setFloat("fallOff", _this.fallOff);
  81119. effect.setFloat("base", _this.base);
  81120. effect.setTexture("textureSampler", _this._depthTexture);
  81121. effect.setTexture("randomSampler", _this._randomTexture);
  81122. };
  81123. };
  81124. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  81125. var _this = this;
  81126. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81127. this._ssaoCombinePostProcess.onApply = function (effect) {
  81128. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  81129. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  81130. };
  81131. };
  81132. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  81133. var size = 512;
  81134. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81135. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81136. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81137. var context = this._randomTexture.getContext();
  81138. var rand = function (min, max) {
  81139. return Math.random() * (max - min) + min;
  81140. };
  81141. var randVector = BABYLON.Vector3.Zero();
  81142. for (var x = 0; x < size; x++) {
  81143. for (var y = 0; y < size; y++) {
  81144. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  81145. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  81146. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  81147. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  81148. context.fillRect(x, y, 1, 1);
  81149. }
  81150. }
  81151. this._randomTexture.update(false);
  81152. };
  81153. __decorate([
  81154. BABYLON.serialize()
  81155. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  81156. __decorate([
  81157. BABYLON.serialize()
  81158. ], SSAORenderingPipeline.prototype, "radius", void 0);
  81159. __decorate([
  81160. BABYLON.serialize()
  81161. ], SSAORenderingPipeline.prototype, "area", void 0);
  81162. __decorate([
  81163. BABYLON.serialize()
  81164. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  81165. __decorate([
  81166. BABYLON.serialize()
  81167. ], SSAORenderingPipeline.prototype, "base", void 0);
  81168. return SSAORenderingPipeline;
  81169. }(BABYLON.PostProcessRenderPipeline));
  81170. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  81171. })(BABYLON || (BABYLON = {}));
  81172. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  81173. var BABYLON;
  81174. (function (BABYLON) {
  81175. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  81176. __extends(SSAO2RenderingPipeline, _super);
  81177. /**
  81178. * @constructor
  81179. * @param {string} name - The rendering pipeline name
  81180. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81181. * @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 }
  81182. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81183. */
  81184. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  81185. var _this = _super.call(this, scene.getEngine(), name) || this;
  81186. // Members
  81187. /**
  81188. * The PassPostProcess id in the pipeline that contains the original scene color
  81189. */
  81190. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  81191. /**
  81192. * The SSAO PostProcess id in the pipeline
  81193. */
  81194. _this.SSAORenderEffect = "SSAORenderEffect";
  81195. /**
  81196. * The horizontal blur PostProcess id in the pipeline
  81197. */
  81198. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  81199. /**
  81200. * The vertical blur PostProcess id in the pipeline
  81201. */
  81202. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  81203. /**
  81204. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  81205. */
  81206. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  81207. /**
  81208. * The output strength of the SSAO post-process. Default value is 1.0.
  81209. */
  81210. _this.totalStrength = 1.0;
  81211. /**
  81212. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  81213. */
  81214. _this.maxZ = 100.0;
  81215. /**
  81216. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  81217. */
  81218. _this.minZAspect = 0.2;
  81219. _this._samples = 8;
  81220. _this._textureSamples = 1;
  81221. /**
  81222. * Are we using bilateral blur ?
  81223. */
  81224. _this._expensiveBlur = true;
  81225. /**
  81226. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  81227. */
  81228. _this.radius = 2.0;
  81229. /**
  81230. * The base color of the SSAO post-process
  81231. * The final result is "base + ssao" between [0, 1]
  81232. */
  81233. _this.base = 0;
  81234. _this._firstUpdate = true;
  81235. _this._bits = new Uint32Array(1);
  81236. _this._scene = scene;
  81237. _this._ratio = ratio;
  81238. if (!_this.isSupported) {
  81239. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  81240. return _this;
  81241. }
  81242. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  81243. var blurRatio = _this._ratio.blurRatio || ratio;
  81244. // Set up assets
  81245. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  81246. _this._createRandomTexture();
  81247. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  81248. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  81249. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  81250. _this._originalColorPostProcess.samples = _this.textureSamples;
  81251. _this._createSSAOPostProcess(1.0);
  81252. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  81253. _this._createSSAOCombinePostProcess(blurRatio);
  81254. // Set up pipeline
  81255. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  81256. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  81257. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  81258. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  81259. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  81260. // Finish
  81261. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81262. if (cameras)
  81263. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81264. return _this;
  81265. }
  81266. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  81267. get: function () {
  81268. return this._samples;
  81269. },
  81270. /**
  81271. * Number of samples used for the SSAO calculations. Default value is 8
  81272. */
  81273. set: function (n) {
  81274. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  81275. this._samples = n;
  81276. this._sampleSphere = this._generateHemisphere();
  81277. this._firstUpdate = true;
  81278. },
  81279. enumerable: true,
  81280. configurable: true
  81281. });
  81282. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  81283. get: function () {
  81284. return this._textureSamples;
  81285. },
  81286. /**
  81287. * Number of samples to use for antialiasing
  81288. */
  81289. set: function (n) {
  81290. this._textureSamples = n;
  81291. this._originalColorPostProcess.samples = n;
  81292. this._blurHPostProcess.samples = n;
  81293. this._blurVPostProcess.samples = n;
  81294. this._ssaoPostProcess.samples = n;
  81295. this._ssaoCombinePostProcess.samples = n;
  81296. },
  81297. enumerable: true,
  81298. configurable: true
  81299. });
  81300. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  81301. get: function () {
  81302. return this._expensiveBlur;
  81303. },
  81304. set: function (b) {
  81305. 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"]);
  81306. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  81307. this._expensiveBlur = b;
  81308. this._firstUpdate = true;
  81309. },
  81310. enumerable: true,
  81311. configurable: true
  81312. });
  81313. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  81314. /**
  81315. * Support test.
  81316. */
  81317. get: function () {
  81318. var engine = BABYLON.Engine.LastCreatedEngine;
  81319. if (!engine) {
  81320. return false;
  81321. }
  81322. return engine.getCaps().drawBuffersExtension;
  81323. },
  81324. enumerable: true,
  81325. configurable: true
  81326. });
  81327. // Public Methods
  81328. /**
  81329. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  81330. */
  81331. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  81332. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  81333. for (var i = 0; i < this._scene.cameras.length; i++) {
  81334. var camera = this._scene.cameras[i];
  81335. this._originalColorPostProcess.dispose(camera);
  81336. this._ssaoPostProcess.dispose(camera);
  81337. this._blurHPostProcess.dispose(camera);
  81338. this._blurVPostProcess.dispose(camera);
  81339. this._ssaoCombinePostProcess.dispose(camera);
  81340. }
  81341. this._randomTexture.dispose();
  81342. if (disableGeometryBufferRenderer)
  81343. this._scene.disableGeometryBufferRenderer();
  81344. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81345. _super.prototype.dispose.call(this);
  81346. };
  81347. // Private Methods
  81348. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  81349. var _this = this;
  81350. this._samplerOffsets = [];
  81351. var expensive = this.expensiveBlur;
  81352. for (var i = -8; i < 8; i++) {
  81353. this._samplerOffsets.push(i * 2 + 0.5);
  81354. }
  81355. 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");
  81356. this._blurHPostProcess.onApply = function (effect) {
  81357. if (!_this._scene.activeCamera) {
  81358. return;
  81359. }
  81360. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  81361. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81362. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81363. effect.setFloat("radius", _this.radius);
  81364. effect.setTexture("depthSampler", _this._depthTexture);
  81365. if (_this._firstUpdate) {
  81366. effect.setArray("samplerOffsets", _this._samplerOffsets);
  81367. }
  81368. };
  81369. 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");
  81370. this._blurVPostProcess.onApply = function (effect) {
  81371. if (!_this._scene.activeCamera) {
  81372. return;
  81373. }
  81374. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  81375. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81376. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81377. effect.setFloat("radius", _this.radius);
  81378. effect.setTexture("depthSampler", _this._depthTexture);
  81379. if (_this._firstUpdate) {
  81380. effect.setArray("samplerOffsets", _this._samplerOffsets);
  81381. _this._firstUpdate = false;
  81382. }
  81383. };
  81384. this._blurHPostProcess.samples = this.textureSamples;
  81385. this._blurVPostProcess.samples = this.textureSamples;
  81386. };
  81387. /** @hidden */
  81388. SSAO2RenderingPipeline.prototype._rebuild = function () {
  81389. this._firstUpdate = true;
  81390. _super.prototype._rebuild.call(this);
  81391. };
  81392. //Van der Corput radical inverse
  81393. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  81394. this._bits[0] = i;
  81395. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  81396. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  81397. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  81398. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  81399. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  81400. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  81401. };
  81402. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  81403. return [i / n, this._radicalInverse_VdC(i)];
  81404. };
  81405. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  81406. var phi = v * 2.0 * Math.PI;
  81407. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  81408. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  81409. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  81410. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  81411. };
  81412. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  81413. var numSamples = this.samples;
  81414. var result = [];
  81415. var vector;
  81416. var i = 0;
  81417. while (i < numSamples) {
  81418. if (numSamples < 16) {
  81419. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  81420. }
  81421. else {
  81422. var rand = this._hammersley(i, numSamples);
  81423. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  81424. }
  81425. result.push(vector.x, vector.y, vector.z);
  81426. i++;
  81427. }
  81428. return result;
  81429. };
  81430. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  81431. var _this = this;
  81432. var numSamples = this.samples;
  81433. this._sampleSphere = this._generateHemisphere();
  81434. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  81435. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  81436. "base", "range", "projection", "near", "far", "texelSize",
  81437. "xViewport", "yViewport", "maxZ", "minZAspect"
  81438. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  81439. this._ssaoPostProcess.onApply = function (effect) {
  81440. if (_this._firstUpdate) {
  81441. effect.setArray3("sampleSphere", _this._sampleSphere);
  81442. effect.setFloat("randTextureTiles", 32.0);
  81443. }
  81444. if (!_this._scene.activeCamera) {
  81445. return;
  81446. }
  81447. effect.setFloat("samplesFactor", 1 / _this.samples);
  81448. effect.setFloat("totalStrength", _this.totalStrength);
  81449. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  81450. effect.setFloat("radius", _this.radius);
  81451. effect.setFloat("maxZ", _this.maxZ);
  81452. effect.setFloat("minZAspect", _this.minZAspect);
  81453. effect.setFloat("base", _this.base);
  81454. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81455. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81456. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  81457. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  81458. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  81459. effect.setTexture("textureSampler", _this._depthTexture);
  81460. effect.setTexture("normalSampler", _this._normalTexture);
  81461. effect.setTexture("randomSampler", _this._randomTexture);
  81462. };
  81463. this._ssaoPostProcess.samples = this.textureSamples;
  81464. };
  81465. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  81466. var _this = this;
  81467. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81468. this._ssaoCombinePostProcess.onApply = function (effect) {
  81469. var viewport = _this._scene.activeCamera.viewport;
  81470. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  81471. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  81472. };
  81473. this._ssaoCombinePostProcess.samples = this.textureSamples;
  81474. };
  81475. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  81476. var size = 128;
  81477. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81478. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81479. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81480. var context = this._randomTexture.getContext();
  81481. var rand = function (min, max) {
  81482. return Math.random() * (max - min) + min;
  81483. };
  81484. var randVector = BABYLON.Vector3.Zero();
  81485. for (var x = 0; x < size; x++) {
  81486. for (var y = 0; y < size; y++) {
  81487. randVector.x = rand(0.0, 1.0);
  81488. randVector.y = rand(0.0, 1.0);
  81489. randVector.z = 0.0;
  81490. randVector.normalize();
  81491. randVector.scaleInPlace(255);
  81492. randVector.x = Math.floor(randVector.x);
  81493. randVector.y = Math.floor(randVector.y);
  81494. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  81495. context.fillRect(x, y, 1, 1);
  81496. }
  81497. }
  81498. this._randomTexture.update(false);
  81499. };
  81500. /**
  81501. * Serialize the rendering pipeline (Used when exporting)
  81502. * @returns the serialized object
  81503. */
  81504. SSAO2RenderingPipeline.prototype.serialize = function () {
  81505. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81506. serializationObject.customType = "SSAO2RenderingPipeline";
  81507. return serializationObject;
  81508. };
  81509. /**
  81510. * Parse the serialized pipeline
  81511. * @param source Source pipeline.
  81512. * @param scene The scene to load the pipeline to.
  81513. * @param rootUrl The URL of the serialized pipeline.
  81514. * @returns An instantiated pipeline from the serialized object.
  81515. */
  81516. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  81517. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  81518. };
  81519. __decorate([
  81520. BABYLON.serialize()
  81521. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  81522. __decorate([
  81523. BABYLON.serialize()
  81524. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  81525. __decorate([
  81526. BABYLON.serialize()
  81527. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  81528. __decorate([
  81529. BABYLON.serialize("samples")
  81530. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  81531. __decorate([
  81532. BABYLON.serialize("textureSamples")
  81533. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  81534. __decorate([
  81535. BABYLON.serialize()
  81536. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  81537. __decorate([
  81538. BABYLON.serialize("expensiveBlur")
  81539. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  81540. __decorate([
  81541. BABYLON.serialize()
  81542. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  81543. __decorate([
  81544. BABYLON.serialize()
  81545. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  81546. return SSAO2RenderingPipeline;
  81547. }(BABYLON.PostProcessRenderPipeline));
  81548. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  81549. })(BABYLON || (BABYLON = {}));
  81550. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  81551. // BABYLON.JS Chromatic Aberration GLSL Shader
  81552. // Author: Olivier Guyot
  81553. // Separates very slightly R, G and B colors on the edges of the screen
  81554. // Inspired by Francois Tarlier & Martins Upitis
  81555. var BABYLON;
  81556. (function (BABYLON) {
  81557. var LensRenderingPipeline = /** @class */ (function (_super) {
  81558. __extends(LensRenderingPipeline, _super);
  81559. /**
  81560. * @constructor
  81561. *
  81562. * Effect parameters are as follow:
  81563. * {
  81564. * chromatic_aberration: number; // from 0 to x (1 for realism)
  81565. * edge_blur: number; // from 0 to x (1 for realism)
  81566. * distortion: number; // from 0 to x (1 for realism)
  81567. * grain_amount: number; // from 0 to 1
  81568. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  81569. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  81570. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  81571. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  81572. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  81573. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  81574. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  81575. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  81576. * }
  81577. * Note: if an effect parameter is unset, effect is disabled
  81578. *
  81579. * @param {string} name - The rendering pipeline name
  81580. * @param {object} parameters - An object containing all parameters (see above)
  81581. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81582. * @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)
  81583. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81584. */
  81585. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  81586. if (ratio === void 0) { ratio = 1.0; }
  81587. var _this = _super.call(this, scene.getEngine(), name) || this;
  81588. // Lens effects can be of the following:
  81589. // - chromatic aberration (slight shift of RGB colors)
  81590. // - blur on the edge of the lens
  81591. // - lens distortion
  81592. // - depth-of-field blur & highlights enhancing
  81593. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  81594. // - grain effect (noise or custom texture)
  81595. // Two additional texture samplers are needed:
  81596. // - depth map (for depth-of-field)
  81597. // - grain texture
  81598. /**
  81599. * The chromatic aberration PostProcess id in the pipeline
  81600. */
  81601. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  81602. /**
  81603. * The highlights enhancing PostProcess id in the pipeline
  81604. */
  81605. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  81606. /**
  81607. * The depth-of-field PostProcess id in the pipeline
  81608. */
  81609. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  81610. _this._scene = scene;
  81611. // Fetch texture samplers
  81612. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81613. if (parameters.grain_texture) {
  81614. _this._grainTexture = parameters.grain_texture;
  81615. }
  81616. else {
  81617. _this._createGrainTexture();
  81618. }
  81619. // save parameters
  81620. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  81621. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  81622. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  81623. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  81624. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  81625. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  81626. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  81627. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  81628. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  81629. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  81630. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  81631. // Create effects
  81632. _this._createChromaticAberrationPostProcess(ratio);
  81633. _this._createHighlightsPostProcess(ratio);
  81634. _this._createDepthOfFieldPostProcess(ratio / 4);
  81635. // Set up pipeline
  81636. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  81637. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  81638. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  81639. if (_this._highlightsGain === -1) {
  81640. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  81641. }
  81642. // Finish
  81643. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81644. if (cameras) {
  81645. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81646. }
  81647. return _this;
  81648. }
  81649. // public methods (self explanatory)
  81650. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  81651. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  81652. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  81653. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  81654. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  81655. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  81656. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  81657. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  81658. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  81659. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  81660. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  81661. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  81662. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  81663. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  81664. };
  81665. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  81666. this._highlightsPostProcess.updateEffect();
  81667. };
  81668. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  81669. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  81670. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  81671. this._highlightsGain = amount;
  81672. };
  81673. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  81674. if (this._highlightsGain === -1) {
  81675. this._highlightsGain = 1.0;
  81676. }
  81677. this._highlightsThreshold = amount;
  81678. };
  81679. LensRenderingPipeline.prototype.disableHighlights = function () {
  81680. this._highlightsGain = -1;
  81681. };
  81682. /**
  81683. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  81684. */
  81685. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  81686. if (disableDepthRender === void 0) { disableDepthRender = false; }
  81687. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81688. this._chromaticAberrationPostProcess = null;
  81689. this._highlightsPostProcess = null;
  81690. this._depthOfFieldPostProcess = null;
  81691. this._grainTexture.dispose();
  81692. if (disableDepthRender)
  81693. this._scene.disableDepthRenderer();
  81694. };
  81695. // colors shifting and distortion
  81696. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  81697. var _this = this;
  81698. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  81699. [], // samplers
  81700. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81701. this._chromaticAberrationPostProcess.onApply = function (effect) {
  81702. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  81703. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81704. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81705. effect.setFloat('radialIntensity', 1);
  81706. effect.setFloat2('direction', 17, 17);
  81707. effect.setFloat2('centerPosition', 0.5, 0.5);
  81708. };
  81709. };
  81710. // highlights enhancing
  81711. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  81712. var _this = this;
  81713. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  81714. [], // samplers
  81715. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  81716. this._highlightsPostProcess.onApply = function (effect) {
  81717. effect.setFloat('gain', _this._highlightsGain);
  81718. effect.setFloat('threshold', _this._highlightsThreshold);
  81719. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  81720. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81721. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81722. };
  81723. };
  81724. // colors shifting and distortion
  81725. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  81726. var _this = this;
  81727. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  81728. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  81729. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  81730. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81731. this._depthOfFieldPostProcess.onApply = function (effect) {
  81732. effect.setTexture("depthSampler", _this._depthTexture);
  81733. effect.setTexture("grainSampler", _this._grainTexture);
  81734. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  81735. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  81736. effect.setFloat('grain_amount', _this._grainAmount);
  81737. effect.setBool('blur_noise', _this._blurNoise);
  81738. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81739. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81740. effect.setFloat('distortion', _this._distortion);
  81741. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  81742. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  81743. effect.setFloat('aperture', _this._dofAperture);
  81744. effect.setFloat('darken', _this._dofDarken);
  81745. effect.setFloat('edge_blur', _this._edgeBlur);
  81746. effect.setBool('highlights', (_this._highlightsGain !== -1));
  81747. if (_this._scene.activeCamera) {
  81748. effect.setFloat('near', _this._scene.activeCamera.minZ);
  81749. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  81750. }
  81751. };
  81752. };
  81753. // creates a black and white random noise texture, 512x512
  81754. LensRenderingPipeline.prototype._createGrainTexture = function () {
  81755. var size = 512;
  81756. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81757. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81758. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81759. var context = this._grainTexture.getContext();
  81760. var rand = function (min, max) {
  81761. return Math.random() * (max - min) + min;
  81762. };
  81763. var value;
  81764. for (var x = 0; x < size; x++) {
  81765. for (var y = 0; y < size; y++) {
  81766. value = Math.floor(rand(0.42, 0.58) * 255);
  81767. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  81768. context.fillRect(x, y, 1, 1);
  81769. }
  81770. }
  81771. this._grainTexture.update(false);
  81772. };
  81773. return LensRenderingPipeline;
  81774. }(BABYLON.PostProcessRenderPipeline));
  81775. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  81776. })(BABYLON || (BABYLON = {}));
  81777. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  81778. var BABYLON;
  81779. (function (BABYLON) {
  81780. var StandardRenderingPipeline = /** @class */ (function (_super) {
  81781. __extends(StandardRenderingPipeline, _super);
  81782. /**
  81783. * @constructor
  81784. * @param {string} name - The rendering pipeline name
  81785. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81786. * @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)
  81787. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  81788. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81789. */
  81790. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  81791. if (originalPostProcess === void 0) { originalPostProcess = null; }
  81792. var _this = _super.call(this, scene.getEngine(), name) || this;
  81793. /**
  81794. * Post-process used to down scale an image x4
  81795. */
  81796. _this.downSampleX4PostProcess = null;
  81797. /**
  81798. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  81799. */
  81800. _this.brightPassPostProcess = null;
  81801. /**
  81802. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  81803. */
  81804. _this.blurHPostProcesses = [];
  81805. /**
  81806. * Post-process array storing all the vertical blur post-processes used by the pipeline
  81807. */
  81808. _this.blurVPostProcesses = [];
  81809. /**
  81810. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  81811. */
  81812. _this.textureAdderPostProcess = null;
  81813. /**
  81814. * Post-process used to create volumetric lighting effect
  81815. */
  81816. _this.volumetricLightPostProcess = null;
  81817. /**
  81818. * Post-process used to smooth the previous volumetric light post-process on the X axis
  81819. */
  81820. _this.volumetricLightSmoothXPostProcess = null;
  81821. /**
  81822. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  81823. */
  81824. _this.volumetricLightSmoothYPostProcess = null;
  81825. /**
  81826. * Post-process used to merge the volumetric light effect and the real scene color
  81827. */
  81828. _this.volumetricLightMergePostProces = null;
  81829. /**
  81830. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  81831. */
  81832. _this.volumetricLightFinalPostProcess = null;
  81833. /**
  81834. * Base post-process used to calculate the average luminance of the final image for HDR
  81835. */
  81836. _this.luminancePostProcess = null;
  81837. /**
  81838. * Post-processes used to create down sample post-processes in order to get
  81839. * the average luminance of the final image for HDR
  81840. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  81841. */
  81842. _this.luminanceDownSamplePostProcesses = [];
  81843. /**
  81844. * Post-process used to create a HDR effect (light adaptation)
  81845. */
  81846. _this.hdrPostProcess = null;
  81847. /**
  81848. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  81849. */
  81850. _this.textureAdderFinalPostProcess = null;
  81851. /**
  81852. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  81853. */
  81854. _this.lensFlareFinalPostProcess = null;
  81855. /**
  81856. * Post-process used to merge the final HDR post-process and the real scene color
  81857. */
  81858. _this.hdrFinalPostProcess = null;
  81859. /**
  81860. * Post-process used to create a lens flare effect
  81861. */
  81862. _this.lensFlarePostProcess = null;
  81863. /**
  81864. * Post-process that merges the result of the lens flare post-process and the real scene color
  81865. */
  81866. _this.lensFlareComposePostProcess = null;
  81867. /**
  81868. * Post-process used to create a motion blur effect
  81869. */
  81870. _this.motionBlurPostProcess = null;
  81871. /**
  81872. * Post-process used to create a depth of field effect
  81873. */
  81874. _this.depthOfFieldPostProcess = null;
  81875. /**
  81876. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  81877. */
  81878. _this.fxaaPostProcess = null;
  81879. // Values
  81880. /**
  81881. * Represents the brightness threshold in order to configure the illuminated surfaces
  81882. */
  81883. _this.brightThreshold = 1.0;
  81884. /**
  81885. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  81886. */
  81887. _this.blurWidth = 512.0;
  81888. /**
  81889. * Sets if the blur for highlighted surfaces must be only horizontal
  81890. */
  81891. _this.horizontalBlur = false;
  81892. /**
  81893. * Sets the overall exposure used by the pipeline
  81894. */
  81895. _this.exposure = 1.0;
  81896. /**
  81897. * Texture used typically to simulate "dirty" on camera lens
  81898. */
  81899. _this.lensTexture = null;
  81900. /**
  81901. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  81902. */
  81903. _this.volumetricLightCoefficient = 0.2;
  81904. /**
  81905. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  81906. */
  81907. _this.volumetricLightPower = 4.0;
  81908. /**
  81909. * Used the set the blur intensity to smooth the volumetric lights
  81910. */
  81911. _this.volumetricLightBlurScale = 64.0;
  81912. /**
  81913. * Light (spot or directional) used to generate the volumetric lights rays
  81914. * The source light must have a shadow generate so the pipeline can get its
  81915. * depth map
  81916. */
  81917. _this.sourceLight = null;
  81918. /**
  81919. * For eye adaptation, represents the minimum luminance the eye can see
  81920. */
  81921. _this.hdrMinimumLuminance = 1.0;
  81922. /**
  81923. * For eye adaptation, represents the decrease luminance speed
  81924. */
  81925. _this.hdrDecreaseRate = 0.5;
  81926. /**
  81927. * For eye adaptation, represents the increase luminance speed
  81928. */
  81929. _this.hdrIncreaseRate = 0.5;
  81930. /**
  81931. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  81932. */
  81933. _this.lensColorTexture = null;
  81934. /**
  81935. * The overall strengh for the lens flare effect
  81936. */
  81937. _this.lensFlareStrength = 20.0;
  81938. /**
  81939. * Dispersion coefficient for lens flare ghosts
  81940. */
  81941. _this.lensFlareGhostDispersal = 1.4;
  81942. /**
  81943. * Main lens flare halo width
  81944. */
  81945. _this.lensFlareHaloWidth = 0.7;
  81946. /**
  81947. * Based on the lens distortion effect, defines how much the lens flare result
  81948. * is distorted
  81949. */
  81950. _this.lensFlareDistortionStrength = 16.0;
  81951. /**
  81952. * Lens star texture must be used to simulate rays on the flares and is available
  81953. * in the documentation
  81954. */
  81955. _this.lensStarTexture = null;
  81956. /**
  81957. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  81958. * flare effect by taking account of the dirt texture
  81959. */
  81960. _this.lensFlareDirtTexture = null;
  81961. /**
  81962. * Represents the focal length for the depth of field effect
  81963. */
  81964. _this.depthOfFieldDistance = 10.0;
  81965. /**
  81966. * Represents the blur intensity for the blurred part of the depth of field effect
  81967. */
  81968. _this.depthOfFieldBlurWidth = 64.0;
  81969. /**
  81970. * For motion blur, defines how much the image is blurred by the movement
  81971. */
  81972. _this.motionStrength = 1.0;
  81973. /**
  81974. * List of animations for the pipeline (IAnimatable implementation)
  81975. */
  81976. _this.animations = [];
  81977. _this._currentDepthOfFieldSource = null;
  81978. _this._hdrCurrentLuminance = 1.0;
  81979. // Getters and setters
  81980. _this._bloomEnabled = false;
  81981. _this._depthOfFieldEnabled = false;
  81982. _this._vlsEnabled = false;
  81983. _this._lensFlareEnabled = false;
  81984. _this._hdrEnabled = false;
  81985. _this._motionBlurEnabled = false;
  81986. _this._fxaaEnabled = false;
  81987. _this._motionBlurSamples = 64.0;
  81988. _this._volumetricLightStepsCount = 50.0;
  81989. _this._samples = 1;
  81990. _this._cameras = cameras || [];
  81991. // Initialize
  81992. _this._scene = scene;
  81993. _this._basePostProcess = originalPostProcess;
  81994. _this._ratio = ratio;
  81995. // Misc
  81996. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81997. // Finish
  81998. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81999. _this._buildPipeline();
  82000. return _this;
  82001. }
  82002. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  82003. /**
  82004. * Specifies if the bloom pipeline is enabled
  82005. */
  82006. get: function () {
  82007. return this._bloomEnabled;
  82008. },
  82009. set: function (enabled) {
  82010. if (this._bloomEnabled === enabled) {
  82011. return;
  82012. }
  82013. this._bloomEnabled = enabled;
  82014. this._buildPipeline();
  82015. },
  82016. enumerable: true,
  82017. configurable: true
  82018. });
  82019. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  82020. /**
  82021. * Specifies if the depth of field pipeline is enabed
  82022. */
  82023. get: function () {
  82024. return this._depthOfFieldEnabled;
  82025. },
  82026. set: function (enabled) {
  82027. if (this._depthOfFieldEnabled === enabled) {
  82028. return;
  82029. }
  82030. this._depthOfFieldEnabled = enabled;
  82031. this._buildPipeline();
  82032. },
  82033. enumerable: true,
  82034. configurable: true
  82035. });
  82036. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  82037. /**
  82038. * Specifies if the lens flare pipeline is enabed
  82039. */
  82040. get: function () {
  82041. return this._lensFlareEnabled;
  82042. },
  82043. set: function (enabled) {
  82044. if (this._lensFlareEnabled === enabled) {
  82045. return;
  82046. }
  82047. this._lensFlareEnabled = enabled;
  82048. this._buildPipeline();
  82049. },
  82050. enumerable: true,
  82051. configurable: true
  82052. });
  82053. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  82054. /**
  82055. * Specifies if the HDR pipeline is enabled
  82056. */
  82057. get: function () {
  82058. return this._hdrEnabled;
  82059. },
  82060. set: function (enabled) {
  82061. if (this._hdrEnabled === enabled) {
  82062. return;
  82063. }
  82064. this._hdrEnabled = enabled;
  82065. this._buildPipeline();
  82066. },
  82067. enumerable: true,
  82068. configurable: true
  82069. });
  82070. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  82071. /**
  82072. * Specifies if the volumetric lights scattering effect is enabled
  82073. */
  82074. get: function () {
  82075. return this._vlsEnabled;
  82076. },
  82077. set: function (enabled) {
  82078. if (this._vlsEnabled === enabled) {
  82079. return;
  82080. }
  82081. if (enabled) {
  82082. var geometry = this._scene.enableGeometryBufferRenderer();
  82083. if (!geometry) {
  82084. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  82085. return;
  82086. }
  82087. }
  82088. this._vlsEnabled = enabled;
  82089. this._buildPipeline();
  82090. },
  82091. enumerable: true,
  82092. configurable: true
  82093. });
  82094. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  82095. /**
  82096. * Specifies if the motion blur effect is enabled
  82097. */
  82098. get: function () {
  82099. return this._motionBlurEnabled;
  82100. },
  82101. set: function (enabled) {
  82102. if (this._motionBlurEnabled === enabled) {
  82103. return;
  82104. }
  82105. this._motionBlurEnabled = enabled;
  82106. this._buildPipeline();
  82107. },
  82108. enumerable: true,
  82109. configurable: true
  82110. });
  82111. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  82112. /**
  82113. * Specifies if anti-aliasing is enabled
  82114. */
  82115. get: function () {
  82116. return this._fxaaEnabled;
  82117. },
  82118. set: function (enabled) {
  82119. if (this._fxaaEnabled === enabled) {
  82120. return;
  82121. }
  82122. this._fxaaEnabled = enabled;
  82123. this._buildPipeline();
  82124. },
  82125. enumerable: true,
  82126. configurable: true
  82127. });
  82128. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  82129. /**
  82130. * Specifies the number of steps used to calculate the volumetric lights
  82131. * Typically in interval [50, 200]
  82132. */
  82133. get: function () {
  82134. return this._volumetricLightStepsCount;
  82135. },
  82136. set: function (count) {
  82137. if (this.volumetricLightPostProcess) {
  82138. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  82139. }
  82140. this._volumetricLightStepsCount = count;
  82141. },
  82142. enumerable: true,
  82143. configurable: true
  82144. });
  82145. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  82146. /**
  82147. * Specifies the number of samples used for the motion blur effect
  82148. * Typically in interval [16, 64]
  82149. */
  82150. get: function () {
  82151. return this._motionBlurSamples;
  82152. },
  82153. set: function (samples) {
  82154. if (this.motionBlurPostProcess) {
  82155. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  82156. }
  82157. this._motionBlurSamples = samples;
  82158. },
  82159. enumerable: true,
  82160. configurable: true
  82161. });
  82162. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  82163. /**
  82164. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  82165. */
  82166. get: function () {
  82167. return this._samples;
  82168. },
  82169. set: function (sampleCount) {
  82170. if (this._samples === sampleCount) {
  82171. return;
  82172. }
  82173. this._samples = sampleCount;
  82174. this._buildPipeline();
  82175. },
  82176. enumerable: true,
  82177. configurable: true
  82178. });
  82179. StandardRenderingPipeline.prototype._buildPipeline = function () {
  82180. var _this = this;
  82181. var ratio = this._ratio;
  82182. var scene = this._scene;
  82183. this._disposePostProcesses();
  82184. this._reset();
  82185. // Create pass post-process
  82186. if (!this._basePostProcess) {
  82187. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  82188. this.originalPostProcess.onApply = function (effect) {
  82189. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  82190. };
  82191. }
  82192. else {
  82193. this.originalPostProcess = this._basePostProcess;
  82194. }
  82195. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  82196. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  82197. }
  82198. this._currentDepthOfFieldSource = this.originalPostProcess;
  82199. if (this._bloomEnabled) {
  82200. // Create down sample X4 post-process
  82201. this._createDownSampleX4PostProcess(scene, ratio / 2);
  82202. // Create bright pass post-process
  82203. this._createBrightPassPostProcess(scene, ratio / 2);
  82204. // Create gaussian blur post-processes (down sampling blurs)
  82205. this._createBlurPostProcesses(scene, ratio / 4, 1);
  82206. // Create texture adder post-process
  82207. this._createTextureAdderPostProcess(scene, ratio);
  82208. // Create depth-of-field source post-process
  82209. 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);
  82210. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  82211. }
  82212. if (this._vlsEnabled) {
  82213. // Create volumetric light
  82214. this._createVolumetricLightPostProcess(scene, ratio);
  82215. // Create volumetric light final post-process
  82216. 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);
  82217. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  82218. }
  82219. if (this._lensFlareEnabled) {
  82220. // Create lens flare post-process
  82221. this._createLensFlarePostProcess(scene, ratio);
  82222. // Create depth-of-field source post-process post lens-flare and disable it now
  82223. 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);
  82224. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  82225. }
  82226. if (this._hdrEnabled) {
  82227. // Create luminance
  82228. this._createLuminancePostProcesses(scene, this._floatTextureType);
  82229. // Create HDR
  82230. this._createHdrPostProcess(scene, ratio);
  82231. // Create depth-of-field source post-process post hdr and disable it now
  82232. 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);
  82233. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  82234. }
  82235. if (this._depthOfFieldEnabled) {
  82236. // Create gaussian blur used by depth-of-field
  82237. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  82238. // Create depth-of-field post-process
  82239. this._createDepthOfFieldPostProcess(scene, ratio);
  82240. }
  82241. if (this._motionBlurEnabled) {
  82242. // Create motion blur post-process
  82243. this._createMotionBlurPostProcess(scene, ratio);
  82244. }
  82245. if (this._fxaaEnabled) {
  82246. // Create fxaa post-process
  82247. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82248. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  82249. }
  82250. if (this._cameras !== null) {
  82251. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  82252. }
  82253. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  82254. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  82255. }
  82256. };
  82257. // Down Sample X4 Post-Processs
  82258. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  82259. var _this = this;
  82260. var downSampleX4Offsets = new Array(32);
  82261. 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);
  82262. this.downSampleX4PostProcess.onApply = function (effect) {
  82263. var id = 0;
  82264. var width = _this.downSampleX4PostProcess.width;
  82265. var height = _this.downSampleX4PostProcess.height;
  82266. for (var i = -2; i < 2; i++) {
  82267. for (var j = -2; j < 2; j++) {
  82268. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  82269. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  82270. id += 2;
  82271. }
  82272. }
  82273. effect.setArray2("dsOffsets", downSampleX4Offsets);
  82274. };
  82275. // Add to pipeline
  82276. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  82277. };
  82278. // Brightpass Post-Process
  82279. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  82280. var _this = this;
  82281. var brightOffsets = new Array(8);
  82282. 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);
  82283. this.brightPassPostProcess.onApply = function (effect) {
  82284. var sU = (1.0 / _this.brightPassPostProcess.width);
  82285. var sV = (1.0 / _this.brightPassPostProcess.height);
  82286. brightOffsets[0] = -0.5 * sU;
  82287. brightOffsets[1] = 0.5 * sV;
  82288. brightOffsets[2] = 0.5 * sU;
  82289. brightOffsets[3] = 0.5 * sV;
  82290. brightOffsets[4] = -0.5 * sU;
  82291. brightOffsets[5] = -0.5 * sV;
  82292. brightOffsets[6] = 0.5 * sU;
  82293. brightOffsets[7] = -0.5 * sV;
  82294. effect.setArray2("dsOffsets", brightOffsets);
  82295. effect.setFloat("brightThreshold", _this.brightThreshold);
  82296. };
  82297. // Add to pipeline
  82298. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  82299. };
  82300. // Create blur H&V post-processes
  82301. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  82302. var _this = this;
  82303. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  82304. var engine = scene.getEngine();
  82305. 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);
  82306. 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);
  82307. blurX.onActivateObservable.add(function () {
  82308. var dw = blurX.width / engine.getRenderWidth();
  82309. blurX.kernel = _this[blurWidthKey] * dw;
  82310. });
  82311. blurY.onActivateObservable.add(function () {
  82312. var dw = blurY.height / engine.getRenderHeight();
  82313. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  82314. });
  82315. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  82316. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  82317. this.blurHPostProcesses.push(blurX);
  82318. this.blurVPostProcesses.push(blurY);
  82319. };
  82320. // Create texture adder post-process
  82321. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  82322. var _this = this;
  82323. 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);
  82324. this.textureAdderPostProcess.onApply = function (effect) {
  82325. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  82326. effect.setTexture("lensSampler", _this.lensTexture);
  82327. effect.setFloat("exposure", _this.exposure);
  82328. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  82329. };
  82330. // Add to pipeline
  82331. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  82332. };
  82333. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  82334. var _this = this;
  82335. var geometryRenderer = scene.enableGeometryBufferRenderer();
  82336. geometryRenderer.enablePosition = true;
  82337. var geometry = geometryRenderer.getGBuffer();
  82338. // Base post-process
  82339. 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));
  82340. var depthValues = BABYLON.Vector2.Zero();
  82341. this.volumetricLightPostProcess.onApply = function (effect) {
  82342. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  82343. var generator = _this.sourceLight.getShadowGenerator();
  82344. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  82345. effect.setTexture("positionSampler", geometry.textures[2]);
  82346. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  82347. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  82348. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  82349. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  82350. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  82351. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  82352. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  82353. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  82354. effect.setVector2("depthValues", depthValues);
  82355. }
  82356. };
  82357. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  82358. // Smooth
  82359. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  82360. // Merge
  82361. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  82362. this.volumetricLightMergePostProces.onApply = function (effect) {
  82363. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  82364. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  82365. };
  82366. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  82367. };
  82368. // Create luminance
  82369. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  82370. var _this = this;
  82371. // Create luminance
  82372. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  82373. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  82374. var offsets = [];
  82375. this.luminancePostProcess.onApply = function (effect) {
  82376. var sU = (1.0 / _this.luminancePostProcess.width);
  82377. var sV = (1.0 / _this.luminancePostProcess.height);
  82378. offsets[0] = -0.5 * sU;
  82379. offsets[1] = 0.5 * sV;
  82380. offsets[2] = 0.5 * sU;
  82381. offsets[3] = 0.5 * sV;
  82382. offsets[4] = -0.5 * sU;
  82383. offsets[5] = -0.5 * sV;
  82384. offsets[6] = 0.5 * sU;
  82385. offsets[7] = -0.5 * sV;
  82386. effect.setArray2("lumOffsets", offsets);
  82387. };
  82388. // Add to pipeline
  82389. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  82390. // Create down sample luminance
  82391. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  82392. var size = Math.pow(3, i);
  82393. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  82394. if (i === 0) {
  82395. defines += "#define FINAL_DOWN_SAMPLER";
  82396. }
  82397. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  82398. this.luminanceDownSamplePostProcesses.push(postProcess);
  82399. }
  82400. // Create callbacks and add effects
  82401. var lastLuminance = this.luminancePostProcess;
  82402. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  82403. var downSampleOffsets = new Array(18);
  82404. pp.onApply = function (effect) {
  82405. if (!lastLuminance) {
  82406. return;
  82407. }
  82408. var id = 0;
  82409. for (var x = -1; x < 2; x++) {
  82410. for (var y = -1; y < 2; y++) {
  82411. downSampleOffsets[id] = x / lastLuminance.width;
  82412. downSampleOffsets[id + 1] = y / lastLuminance.height;
  82413. id += 2;
  82414. }
  82415. }
  82416. effect.setArray2("dsOffsets", downSampleOffsets);
  82417. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  82418. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  82419. lastLuminance = _this.luminancePostProcess;
  82420. }
  82421. else {
  82422. lastLuminance = pp;
  82423. }
  82424. };
  82425. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  82426. pp.onAfterRender = function (effect) {
  82427. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  82428. 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);
  82429. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  82430. };
  82431. }
  82432. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  82433. });
  82434. };
  82435. // Create HDR post-process
  82436. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  82437. var _this = this;
  82438. 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);
  82439. var outputLiminance = 1;
  82440. var time = 0;
  82441. var lastTime = 0;
  82442. this.hdrPostProcess.onApply = function (effect) {
  82443. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  82444. time += scene.getEngine().getDeltaTime();
  82445. if (outputLiminance < 0) {
  82446. outputLiminance = _this._hdrCurrentLuminance;
  82447. }
  82448. else {
  82449. var dt = (lastTime - time) / 1000.0;
  82450. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  82451. outputLiminance += _this.hdrDecreaseRate * dt;
  82452. }
  82453. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  82454. outputLiminance -= _this.hdrIncreaseRate * dt;
  82455. }
  82456. else {
  82457. outputLiminance = _this._hdrCurrentLuminance;
  82458. }
  82459. }
  82460. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  82461. effect.setFloat("averageLuminance", outputLiminance);
  82462. lastTime = time;
  82463. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  82464. };
  82465. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  82466. };
  82467. // Create lens flare post-process
  82468. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  82469. var _this = this;
  82470. 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);
  82471. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  82472. this._createBlurPostProcesses(scene, ratio / 4, 2);
  82473. 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);
  82474. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  82475. var resolution = new BABYLON.Vector2(0, 0);
  82476. // Lens flare
  82477. this.lensFlarePostProcess.onApply = function (effect) {
  82478. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  82479. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  82480. effect.setFloat("strength", _this.lensFlareStrength);
  82481. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  82482. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  82483. // Shift
  82484. resolution.x = _this.lensFlarePostProcess.width;
  82485. resolution.y = _this.lensFlarePostProcess.height;
  82486. effect.setVector2("resolution", resolution);
  82487. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  82488. };
  82489. // Compose
  82490. 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);
  82491. 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);
  82492. this.lensFlareComposePostProcess.onApply = function (effect) {
  82493. if (!_this._scene.activeCamera) {
  82494. return;
  82495. }
  82496. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82497. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  82498. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  82499. // Lens start rotation matrix
  82500. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  82501. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  82502. 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));
  82503. camRot *= 4.0;
  82504. 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);
  82505. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  82506. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  82507. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  82508. };
  82509. };
  82510. // Create depth-of-field post-process
  82511. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  82512. var _this = this;
  82513. 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);
  82514. this.depthOfFieldPostProcess.onApply = function (effect) {
  82515. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82516. effect.setTexture("depthSampler", _this._getDepthTexture());
  82517. effect.setFloat("distance", _this.depthOfFieldDistance);
  82518. };
  82519. // Add to pipeline
  82520. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  82521. };
  82522. // Create motion blur post-process
  82523. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  82524. var _this = this;
  82525. 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);
  82526. var motionScale = 0;
  82527. var prevViewProjection = BABYLON.Matrix.Identity();
  82528. var invViewProjection = BABYLON.Matrix.Identity();
  82529. var viewProjection = BABYLON.Matrix.Identity();
  82530. var screenSize = BABYLON.Vector2.Zero();
  82531. this.motionBlurPostProcess.onApply = function (effect) {
  82532. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  82533. viewProjection.invertToRef(invViewProjection);
  82534. effect.setMatrix("inverseViewProjection", invViewProjection);
  82535. effect.setMatrix("prevViewProjection", prevViewProjection);
  82536. prevViewProjection = viewProjection;
  82537. screenSize.x = _this.motionBlurPostProcess.width;
  82538. screenSize.y = _this.motionBlurPostProcess.height;
  82539. effect.setVector2("screenSize", screenSize);
  82540. motionScale = scene.getEngine().getFps() / 60.0;
  82541. effect.setFloat("motionScale", motionScale);
  82542. effect.setFloat("motionStrength", _this.motionStrength);
  82543. effect.setTexture("depthSampler", _this._getDepthTexture());
  82544. };
  82545. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  82546. };
  82547. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  82548. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  82549. var renderer = this._scene.enableGeometryBufferRenderer();
  82550. return renderer.getGBuffer().textures[0];
  82551. }
  82552. return this._scene.enableDepthRenderer().getDepthMap();
  82553. };
  82554. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  82555. for (var i = 0; i < this._cameras.length; i++) {
  82556. var camera = this._cameras[i];
  82557. if (this.originalPostProcess) {
  82558. this.originalPostProcess.dispose(camera);
  82559. }
  82560. if (this.downSampleX4PostProcess) {
  82561. this.downSampleX4PostProcess.dispose(camera);
  82562. }
  82563. if (this.brightPassPostProcess) {
  82564. this.brightPassPostProcess.dispose(camera);
  82565. }
  82566. if (this.textureAdderPostProcess) {
  82567. this.textureAdderPostProcess.dispose(camera);
  82568. }
  82569. if (this.textureAdderFinalPostProcess) {
  82570. this.textureAdderFinalPostProcess.dispose(camera);
  82571. }
  82572. if (this.volumetricLightPostProcess) {
  82573. this.volumetricLightPostProcess.dispose(camera);
  82574. }
  82575. if (this.volumetricLightSmoothXPostProcess) {
  82576. this.volumetricLightSmoothXPostProcess.dispose(camera);
  82577. }
  82578. if (this.volumetricLightSmoothYPostProcess) {
  82579. this.volumetricLightSmoothYPostProcess.dispose(camera);
  82580. }
  82581. if (this.volumetricLightMergePostProces) {
  82582. this.volumetricLightMergePostProces.dispose(camera);
  82583. }
  82584. if (this.volumetricLightFinalPostProcess) {
  82585. this.volumetricLightFinalPostProcess.dispose(camera);
  82586. }
  82587. if (this.lensFlarePostProcess) {
  82588. this.lensFlarePostProcess.dispose(camera);
  82589. }
  82590. if (this.lensFlareComposePostProcess) {
  82591. this.lensFlareComposePostProcess.dispose(camera);
  82592. }
  82593. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  82594. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  82595. }
  82596. if (this.luminancePostProcess) {
  82597. this.luminancePostProcess.dispose(camera);
  82598. }
  82599. if (this.hdrPostProcess) {
  82600. this.hdrPostProcess.dispose(camera);
  82601. }
  82602. if (this.hdrFinalPostProcess) {
  82603. this.hdrFinalPostProcess.dispose(camera);
  82604. }
  82605. if (this.depthOfFieldPostProcess) {
  82606. this.depthOfFieldPostProcess.dispose(camera);
  82607. }
  82608. if (this.motionBlurPostProcess) {
  82609. this.motionBlurPostProcess.dispose(camera);
  82610. }
  82611. if (this.fxaaPostProcess) {
  82612. this.fxaaPostProcess.dispose(camera);
  82613. }
  82614. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  82615. this.blurHPostProcesses[j].dispose(camera);
  82616. }
  82617. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  82618. this.blurVPostProcesses[j].dispose(camera);
  82619. }
  82620. }
  82621. this.originalPostProcess = null;
  82622. this.downSampleX4PostProcess = null;
  82623. this.brightPassPostProcess = null;
  82624. this.textureAdderPostProcess = null;
  82625. this.textureAdderFinalPostProcess = null;
  82626. this.volumetricLightPostProcess = null;
  82627. this.volumetricLightSmoothXPostProcess = null;
  82628. this.volumetricLightSmoothYPostProcess = null;
  82629. this.volumetricLightMergePostProces = null;
  82630. this.volumetricLightFinalPostProcess = null;
  82631. this.lensFlarePostProcess = null;
  82632. this.lensFlareComposePostProcess = null;
  82633. this.luminancePostProcess = null;
  82634. this.hdrPostProcess = null;
  82635. this.hdrFinalPostProcess = null;
  82636. this.depthOfFieldPostProcess = null;
  82637. this.motionBlurPostProcess = null;
  82638. this.fxaaPostProcess = null;
  82639. this.luminanceDownSamplePostProcesses = [];
  82640. this.blurHPostProcesses = [];
  82641. this.blurVPostProcesses = [];
  82642. };
  82643. /**
  82644. * Dispose of the pipeline and stop all post processes
  82645. */
  82646. StandardRenderingPipeline.prototype.dispose = function () {
  82647. this._disposePostProcesses();
  82648. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  82649. _super.prototype.dispose.call(this);
  82650. };
  82651. /**
  82652. * Serialize the rendering pipeline (Used when exporting)
  82653. * @returns the serialized object
  82654. */
  82655. StandardRenderingPipeline.prototype.serialize = function () {
  82656. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  82657. if (this.sourceLight) {
  82658. serializationObject.sourceLightId = this.sourceLight.id;
  82659. }
  82660. serializationObject.customType = "StandardRenderingPipeline";
  82661. return serializationObject;
  82662. };
  82663. /**
  82664. * Parse the serialized pipeline
  82665. * @param source Source pipeline.
  82666. * @param scene The scene to load the pipeline to.
  82667. * @param rootUrl The URL of the serialized pipeline.
  82668. * @returns An instantiated pipeline from the serialized object.
  82669. */
  82670. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  82671. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  82672. if (source.sourceLightId) {
  82673. p.sourceLight = scene.getLightByID(source.sourceLightId);
  82674. }
  82675. return p;
  82676. };
  82677. // Luminance steps
  82678. StandardRenderingPipeline.LuminanceSteps = 6;
  82679. __decorate([
  82680. BABYLON.serialize()
  82681. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  82682. __decorate([
  82683. BABYLON.serialize()
  82684. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  82685. __decorate([
  82686. BABYLON.serialize()
  82687. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  82688. __decorate([
  82689. BABYLON.serialize()
  82690. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  82691. __decorate([
  82692. BABYLON.serializeAsTexture("lensTexture")
  82693. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  82694. __decorate([
  82695. BABYLON.serialize()
  82696. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  82697. __decorate([
  82698. BABYLON.serialize()
  82699. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  82700. __decorate([
  82701. BABYLON.serialize()
  82702. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  82703. __decorate([
  82704. BABYLON.serialize()
  82705. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  82706. __decorate([
  82707. BABYLON.serialize()
  82708. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  82709. __decorate([
  82710. BABYLON.serialize()
  82711. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  82712. __decorate([
  82713. BABYLON.serializeAsTexture("lensColorTexture")
  82714. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  82715. __decorate([
  82716. BABYLON.serialize()
  82717. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  82718. __decorate([
  82719. BABYLON.serialize()
  82720. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  82721. __decorate([
  82722. BABYLON.serialize()
  82723. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  82724. __decorate([
  82725. BABYLON.serialize()
  82726. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  82727. __decorate([
  82728. BABYLON.serializeAsTexture("lensStarTexture")
  82729. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  82730. __decorate([
  82731. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  82732. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  82733. __decorate([
  82734. BABYLON.serialize()
  82735. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  82736. __decorate([
  82737. BABYLON.serialize()
  82738. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  82739. __decorate([
  82740. BABYLON.serialize()
  82741. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  82742. __decorate([
  82743. BABYLON.serialize()
  82744. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  82745. __decorate([
  82746. BABYLON.serialize()
  82747. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  82748. __decorate([
  82749. BABYLON.serialize()
  82750. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  82751. __decorate([
  82752. BABYLON.serialize()
  82753. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  82754. __decorate([
  82755. BABYLON.serialize()
  82756. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  82757. __decorate([
  82758. BABYLON.serialize()
  82759. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  82760. __decorate([
  82761. BABYLON.serialize()
  82762. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  82763. __decorate([
  82764. BABYLON.serialize()
  82765. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  82766. __decorate([
  82767. BABYLON.serialize()
  82768. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  82769. __decorate([
  82770. BABYLON.serialize()
  82771. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  82772. __decorate([
  82773. BABYLON.serialize()
  82774. ], StandardRenderingPipeline.prototype, "samples", null);
  82775. return StandardRenderingPipeline;
  82776. }(BABYLON.PostProcessRenderPipeline));
  82777. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  82778. })(BABYLON || (BABYLON = {}));
  82779. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  82780. var BABYLON;
  82781. (function (BABYLON) {
  82782. var FxaaPostProcess = /** @class */ (function (_super) {
  82783. __extends(FxaaPostProcess, _super);
  82784. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  82785. if (camera === void 0) { camera = null; }
  82786. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82787. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  82788. var defines = _this._getDefines();
  82789. _this.updateEffect(defines);
  82790. _this.onApplyObservable.add(function (effect) {
  82791. var texelSize = _this.texelSize;
  82792. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  82793. });
  82794. return _this;
  82795. }
  82796. FxaaPostProcess.prototype._getDefines = function () {
  82797. var engine = this.getEngine();
  82798. if (!engine) {
  82799. return null;
  82800. }
  82801. var glInfo = engine.getGlInfo();
  82802. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  82803. return "#define MALI 1\n";
  82804. }
  82805. return null;
  82806. };
  82807. return FxaaPostProcess;
  82808. }(BABYLON.PostProcess));
  82809. BABYLON.FxaaPostProcess = FxaaPostProcess;
  82810. })(BABYLON || (BABYLON = {}));
  82811. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  82812. var BABYLON;
  82813. (function (BABYLON) {
  82814. /**
  82815. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  82816. */
  82817. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  82818. __extends(ChromaticAberrationPostProcess, _super);
  82819. /**
  82820. * Creates a new instance ChromaticAberrationPostProcess
  82821. * @param name The name of the effect.
  82822. * @param screenWidth The width of the screen to apply the effect on.
  82823. * @param screenHeight The height of the screen to apply the effect on.
  82824. * @param options The required width/height ratio to downsize to before computing the render pass.
  82825. * @param camera The camera to apply the render pass to.
  82826. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82827. * @param engine The engine which the post process will be applied. (default: current engine)
  82828. * @param reusable If the post process can be reused on the same frame. (default: false)
  82829. * @param textureType Type of textures used when performing the post process. (default: 0)
  82830. * @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)
  82831. */
  82832. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82833. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82834. if (blockCompilation === void 0) { blockCompilation = false; }
  82835. 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;
  82836. /**
  82837. * The amount of seperation of rgb channels (default: 30)
  82838. */
  82839. _this.aberrationAmount = 30;
  82840. /**
  82841. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  82842. */
  82843. _this.radialIntensity = 0;
  82844. /**
  82845. * 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))
  82846. */
  82847. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  82848. /**
  82849. * 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))
  82850. */
  82851. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  82852. _this.onApplyObservable.add(function (effect) {
  82853. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  82854. effect.setFloat('screen_width', screenWidth);
  82855. effect.setFloat('screen_height', screenHeight);
  82856. effect.setFloat('radialIntensity', _this.radialIntensity);
  82857. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  82858. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  82859. });
  82860. return _this;
  82861. }
  82862. return ChromaticAberrationPostProcess;
  82863. }(BABYLON.PostProcess));
  82864. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  82865. })(BABYLON || (BABYLON = {}));
  82866. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  82867. var BABYLON;
  82868. (function (BABYLON) {
  82869. /**
  82870. * The GrainPostProcess adds noise to the image at mid luminance levels
  82871. */
  82872. var GrainPostProcess = /** @class */ (function (_super) {
  82873. __extends(GrainPostProcess, _super);
  82874. /**
  82875. * Creates a new instance of @see GrainPostProcess
  82876. * @param name The name of the effect.
  82877. * @param options The required width/height ratio to downsize to before computing the render pass.
  82878. * @param camera The camera to apply the render pass to.
  82879. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82880. * @param engine The engine which the post process will be applied. (default: current engine)
  82881. * @param reusable If the post process can be reused on the same frame. (default: false)
  82882. * @param textureType Type of textures used when performing the post process. (default: 0)
  82883. * @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)
  82884. */
  82885. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82886. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82887. if (blockCompilation === void 0) { blockCompilation = false; }
  82888. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82889. /**
  82890. * The intensity of the grain added (default: 30)
  82891. */
  82892. _this.intensity = 30;
  82893. /**
  82894. * If the grain should be randomized on every frame
  82895. */
  82896. _this.animated = false;
  82897. _this.onApplyObservable.add(function (effect) {
  82898. effect.setFloat('intensity', _this.intensity);
  82899. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  82900. });
  82901. return _this;
  82902. }
  82903. return GrainPostProcess;
  82904. }(BABYLON.PostProcess));
  82905. BABYLON.GrainPostProcess = GrainPostProcess;
  82906. })(BABYLON || (BABYLON = {}));
  82907. //# sourceMappingURL=babylon.grainPostProcess.js.map
  82908. var BABYLON;
  82909. (function (BABYLON) {
  82910. /**
  82911. * The SharpenPostProcess applies a sharpen kernel to every pixel
  82912. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  82913. */
  82914. var SharpenPostProcess = /** @class */ (function (_super) {
  82915. __extends(SharpenPostProcess, _super);
  82916. /**
  82917. * Creates a new instance ConvolutionPostProcess
  82918. * @param name The name of the effect.
  82919. * @param options The required width/height ratio to downsize to before computing the render pass.
  82920. * @param camera The camera to apply the render pass to.
  82921. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82922. * @param engine The engine which the post process will be applied. (default: current engine)
  82923. * @param reusable If the post process can be reused on the same frame. (default: false)
  82924. * @param textureType Type of textures used when performing the post process. (default: 0)
  82925. * @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)
  82926. */
  82927. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82928. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82929. if (blockCompilation === void 0) { blockCompilation = false; }
  82930. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82931. /**
  82932. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  82933. */
  82934. _this.colorAmount = 1.0;
  82935. /**
  82936. * How much sharpness should be applied (default: 0.3)
  82937. */
  82938. _this.edgeAmount = 0.3;
  82939. _this.onApply = function (effect) {
  82940. effect.setFloat2("screenSize", _this.width, _this.height);
  82941. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  82942. };
  82943. return _this;
  82944. }
  82945. return SharpenPostProcess;
  82946. }(BABYLON.PostProcess));
  82947. BABYLON.SharpenPostProcess = SharpenPostProcess;
  82948. })(BABYLON || (BABYLON = {}));
  82949. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  82950. var BABYLON;
  82951. (function (BABYLON) {
  82952. /**
  82953. * The Blur Post Process which blurs an image based on a kernel and direction.
  82954. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  82955. */
  82956. var BlurPostProcess = /** @class */ (function (_super) {
  82957. __extends(BlurPostProcess, _super);
  82958. /**
  82959. * Creates a new instance BlurPostProcess
  82960. * @param name The name of the effect.
  82961. * @param direction The direction in which to blur the image.
  82962. * @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.
  82963. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  82964. * @param camera The camera to apply the render pass to.
  82965. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82966. * @param engine The engine which the post process will be applied. (default: current engine)
  82967. * @param reusable If the post process can be reused on the same frame. (default: false)
  82968. * @param textureType Type of textures used when performing the post process. (default: 0)
  82969. * @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)
  82970. */
  82971. function BlurPostProcess(name,
  82972. /** The direction in which to blur the image. */
  82973. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  82974. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82975. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82976. if (defines === void 0) { defines = ""; }
  82977. if (blockCompilation === void 0) { blockCompilation = false; }
  82978. 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;
  82979. _this.direction = direction;
  82980. _this.blockCompilation = blockCompilation;
  82981. _this._packedFloat = false;
  82982. _this._staticDefines = "";
  82983. _this._staticDefines = defines;
  82984. _this.onApplyObservable.add(function (effect) {
  82985. if (_this._outputTexture) {
  82986. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  82987. }
  82988. else {
  82989. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  82990. }
  82991. });
  82992. _this.kernel = kernel;
  82993. return _this;
  82994. }
  82995. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  82996. /**
  82997. * Gets the length in pixels of the blur sample region
  82998. */
  82999. get: function () {
  83000. return this._idealKernel;
  83001. },
  83002. /**
  83003. * Sets the length in pixels of the blur sample region
  83004. */
  83005. set: function (v) {
  83006. if (this._idealKernel === v) {
  83007. return;
  83008. }
  83009. v = Math.max(v, 1);
  83010. this._idealKernel = v;
  83011. this._kernel = this._nearestBestKernel(v);
  83012. if (!this.blockCompilation) {
  83013. this._updateParameters();
  83014. }
  83015. },
  83016. enumerable: true,
  83017. configurable: true
  83018. });
  83019. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  83020. /**
  83021. * Gets wether or not the blur is unpacking/repacking floats
  83022. */
  83023. get: function () {
  83024. return this._packedFloat;
  83025. },
  83026. /**
  83027. * Sets wether or not the blur needs to unpack/repack floats
  83028. */
  83029. set: function (v) {
  83030. if (this._packedFloat === v) {
  83031. return;
  83032. }
  83033. this._packedFloat = v;
  83034. if (!this.blockCompilation) {
  83035. this._updateParameters();
  83036. }
  83037. },
  83038. enumerable: true,
  83039. configurable: true
  83040. });
  83041. /**
  83042. * Updates the effect with the current post process compile time values and recompiles the shader.
  83043. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  83044. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  83045. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  83046. * @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
  83047. * @param onCompiled Called when the shader has been compiled.
  83048. * @param onError Called if there is an error when compiling a shader.
  83049. */
  83050. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  83051. if (defines === void 0) { defines = null; }
  83052. if (uniforms === void 0) { uniforms = null; }
  83053. if (samplers === void 0) { samplers = null; }
  83054. this._updateParameters(onCompiled, onError);
  83055. };
  83056. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  83057. // Generate sampling offsets and weights
  83058. var N = this._kernel;
  83059. var centerIndex = (N - 1) / 2;
  83060. // Generate Gaussian sampling weights over kernel
  83061. var offsets = [];
  83062. var weights = [];
  83063. var totalWeight = 0;
  83064. for (var i = 0; i < N; i++) {
  83065. var u = i / (N - 1);
  83066. var w = this._gaussianWeight(u * 2.0 - 1);
  83067. offsets[i] = (i - centerIndex);
  83068. weights[i] = w;
  83069. totalWeight += w;
  83070. }
  83071. // Normalize weights
  83072. for (var i = 0; i < weights.length; i++) {
  83073. weights[i] /= totalWeight;
  83074. }
  83075. // Optimize: combine samples to take advantage of hardware linear sampling
  83076. // Walk from left to center, combining pairs (symmetrically)
  83077. var linearSamplingWeights = [];
  83078. var linearSamplingOffsets = [];
  83079. var linearSamplingMap = [];
  83080. for (var i = 0; i <= centerIndex; i += 2) {
  83081. var j = Math.min(i + 1, Math.floor(centerIndex));
  83082. var singleCenterSample = i === j;
  83083. if (singleCenterSample) {
  83084. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  83085. }
  83086. else {
  83087. var sharedCell = j === centerIndex;
  83088. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  83089. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  83090. if (offsetLinear === 0) {
  83091. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  83092. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  83093. }
  83094. else {
  83095. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  83096. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  83097. }
  83098. }
  83099. }
  83100. for (var i = 0; i < linearSamplingMap.length; i++) {
  83101. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  83102. linearSamplingWeights[i] = linearSamplingMap[i].w;
  83103. }
  83104. // Replace with optimized
  83105. offsets = linearSamplingOffsets;
  83106. weights = linearSamplingWeights;
  83107. // Generate shaders
  83108. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  83109. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  83110. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  83111. var defines = "";
  83112. defines += this._staticDefines;
  83113. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  83114. if (this._staticDefines.indexOf("DOF") != -1) {
  83115. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  83116. varyingCount--;
  83117. }
  83118. for (var i = 0; i < varyingCount; i++) {
  83119. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  83120. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  83121. }
  83122. var depCount = 0;
  83123. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  83124. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  83125. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  83126. depCount++;
  83127. }
  83128. if (this.packedFloat) {
  83129. defines += "#define PACKEDFLOAT 1";
  83130. }
  83131. this.blockCompilation = false;
  83132. _super.prototype.updateEffect.call(this, defines, null, null, {
  83133. varyingCount: varyingCount,
  83134. depCount: depCount
  83135. }, onCompiled, onError);
  83136. };
  83137. /**
  83138. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  83139. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  83140. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  83141. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  83142. * The gaps between physical kernels are compensated for in the weighting of the samples
  83143. * @param idealKernel Ideal blur kernel.
  83144. * @return Nearest best kernel.
  83145. */
  83146. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  83147. var v = Math.round(idealKernel);
  83148. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  83149. var k = _a[_i];
  83150. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  83151. return Math.max(k, 3);
  83152. }
  83153. }
  83154. return Math.max(v, 3);
  83155. };
  83156. /**
  83157. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  83158. * @param x The point on the Gaussian distribution to sample.
  83159. * @return the value of the Gaussian function at x.
  83160. */
  83161. BlurPostProcess.prototype._gaussianWeight = function (x) {
  83162. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  83163. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  83164. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  83165. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  83166. // truncated at around 1.3% of peak strength.
  83167. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  83168. var sigma = (1 / 3);
  83169. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  83170. var exponent = -((x * x) / (2.0 * sigma * sigma));
  83171. var weight = (1.0 / denominator) * Math.exp(exponent);
  83172. return weight;
  83173. };
  83174. /**
  83175. * Generates a string that can be used as a floating point number in GLSL.
  83176. * @param x Value to print.
  83177. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  83178. * @return GLSL float string.
  83179. */
  83180. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  83181. if (decimalFigures === void 0) { decimalFigures = 8; }
  83182. return x.toFixed(decimalFigures).replace(/0+$/, '');
  83183. };
  83184. return BlurPostProcess;
  83185. }(BABYLON.PostProcess));
  83186. BABYLON.BlurPostProcess = BlurPostProcess;
  83187. })(BABYLON || (BABYLON = {}));
  83188. //# sourceMappingURL=babylon.blurPostProcess.js.map
  83189. var BABYLON;
  83190. (function (BABYLON) {
  83191. /**
  83192. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  83193. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  83194. * based on samples that have a large difference in distance than the center pixel.
  83195. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  83196. */
  83197. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  83198. __extends(DepthOfFieldBlurPostProcess, _super);
  83199. /**
  83200. * Creates a new instance CircleOfConfusionPostProcess
  83201. * @param name The name of the effect.
  83202. * @param scene The scene the effect belongs to.
  83203. * @param direction The direction the blur should be applied.
  83204. * @param kernel The size of the kernel used to blur.
  83205. * @param options The required width/height ratio to downsize to before computing the render pass.
  83206. * @param camera The camera to apply the render pass to.
  83207. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  83208. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  83209. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83210. * @param engine The engine which the post process will be applied. (default: current engine)
  83211. * @param reusable If the post process can be reused on the same frame. (default: false)
  83212. * @param textureType Type of textures used when performing the post process. (default: 0)
  83213. * @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)
  83214. */
  83215. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  83216. if (imageToBlur === void 0) { imageToBlur = null; }
  83217. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83218. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83219. if (blockCompilation === void 0) { blockCompilation = false; }
  83220. 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;
  83221. _this.direction = direction;
  83222. _this.onApplyObservable.add(function (effect) {
  83223. if (imageToBlur != null) {
  83224. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  83225. }
  83226. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  83227. if (scene.activeCamera) {
  83228. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  83229. }
  83230. });
  83231. return _this;
  83232. }
  83233. return DepthOfFieldBlurPostProcess;
  83234. }(BABYLON.BlurPostProcess));
  83235. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  83236. })(BABYLON || (BABYLON = {}));
  83237. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  83238. var BABYLON;
  83239. (function (BABYLON) {
  83240. /**
  83241. * Options to be set when merging outputs from the default pipeline.
  83242. */
  83243. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  83244. function DepthOfFieldMergePostProcessOptions() {
  83245. }
  83246. return DepthOfFieldMergePostProcessOptions;
  83247. }());
  83248. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  83249. /**
  83250. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83251. */
  83252. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  83253. __extends(DepthOfFieldMergePostProcess, _super);
  83254. /**
  83255. * Creates a new instance of DepthOfFieldMergePostProcess
  83256. * @param name The name of the effect.
  83257. * @param originalFromInput Post process which's input will be used for the merge.
  83258. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  83259. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  83260. * @param options The required width/height ratio to downsize to before computing the render pass.
  83261. * @param camera The camera to apply the render pass to.
  83262. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83263. * @param engine The engine which the post process will be applied. (default: current engine)
  83264. * @param reusable If the post process can be reused on the same frame. (default: false)
  83265. * @param textureType Type of textures used when performing the post process. (default: 0)
  83266. * @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)
  83267. */
  83268. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83269. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83270. if (blockCompilation === void 0) { blockCompilation = false; }
  83271. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83272. _this.blurSteps = blurSteps;
  83273. _this.onApplyObservable.add(function (effect) {
  83274. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83275. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  83276. blurSteps.forEach(function (step, index) {
  83277. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  83278. });
  83279. });
  83280. if (!blockCompilation) {
  83281. _this.updateEffect();
  83282. }
  83283. return _this;
  83284. }
  83285. /**
  83286. * Updates the effect with the current post process compile time values and recompiles the shader.
  83287. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  83288. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  83289. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  83290. * @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
  83291. * @param onCompiled Called when the shader has been compiled.
  83292. * @param onError Called if there is an error when compiling a shader.
  83293. */
  83294. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  83295. if (defines === void 0) { defines = null; }
  83296. if (uniforms === void 0) { uniforms = null; }
  83297. if (samplers === void 0) { samplers = null; }
  83298. if (!defines) {
  83299. defines = "";
  83300. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  83301. }
  83302. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  83303. };
  83304. return DepthOfFieldMergePostProcess;
  83305. }(BABYLON.PostProcess));
  83306. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  83307. })(BABYLON || (BABYLON = {}));
  83308. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  83309. var BABYLON;
  83310. (function (BABYLON) {
  83311. /**
  83312. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  83313. */
  83314. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  83315. __extends(CircleOfConfusionPostProcess, _super);
  83316. /**
  83317. * Creates a new instance CircleOfConfusionPostProcess
  83318. * @param name The name of the effect.
  83319. * @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.
  83320. * @param options The required width/height ratio to downsize to before computing the render pass.
  83321. * @param camera The camera to apply the render pass to.
  83322. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83323. * @param engine The engine which the post process will be applied. (default: current engine)
  83324. * @param reusable If the post process can be reused on the same frame. (default: false)
  83325. * @param textureType Type of textures used when performing the post process. (default: 0)
  83326. * @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)
  83327. */
  83328. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83329. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83330. if (blockCompilation === void 0) { blockCompilation = false; }
  83331. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83332. /**
  83333. * 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.
  83334. */
  83335. _this.lensSize = 50;
  83336. /**
  83337. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  83338. */
  83339. _this.fStop = 1.4;
  83340. /**
  83341. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  83342. */
  83343. _this.focusDistance = 2000;
  83344. /**
  83345. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  83346. */
  83347. _this.focalLength = 50;
  83348. _this._depthTexture = null;
  83349. _this._depthTexture = depthTexture;
  83350. _this.onApplyObservable.add(function (effect) {
  83351. if (!_this._depthTexture) {
  83352. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  83353. return;
  83354. }
  83355. effect.setTexture("depthSampler", _this._depthTexture);
  83356. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  83357. var aperture = _this.lensSize / _this.fStop;
  83358. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  83359. effect.setFloat('focusDistance', _this.focusDistance);
  83360. effect.setFloat('cocPrecalculation', cocPrecalculation);
  83361. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  83362. });
  83363. return _this;
  83364. }
  83365. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  83366. /**
  83367. * 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.
  83368. */
  83369. set: function (value) {
  83370. this._depthTexture = value;
  83371. },
  83372. enumerable: true,
  83373. configurable: true
  83374. });
  83375. return CircleOfConfusionPostProcess;
  83376. }(BABYLON.PostProcess));
  83377. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  83378. })(BABYLON || (BABYLON = {}));
  83379. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  83380. var BABYLON;
  83381. (function (BABYLON) {
  83382. /**
  83383. * Specifies the level of max blur that should be applied when using the depth of field effect
  83384. */
  83385. var DepthOfFieldEffectBlurLevel;
  83386. (function (DepthOfFieldEffectBlurLevel) {
  83387. /**
  83388. * Subtle blur
  83389. */
  83390. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  83391. /**
  83392. * Medium blur
  83393. */
  83394. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  83395. /**
  83396. * Large blur
  83397. */
  83398. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  83399. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  83400. ;
  83401. /**
  83402. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  83403. */
  83404. var DepthOfFieldEffect = /** @class */ (function (_super) {
  83405. __extends(DepthOfFieldEffect, _super);
  83406. /**
  83407. * Creates a new instance DepthOfFieldEffect
  83408. * @param scene The scene the effect belongs to.
  83409. * @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.
  83410. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  83411. * @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)
  83412. */
  83413. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  83414. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  83415. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  83416. if (blockCompilation === void 0) { blockCompilation = false; }
  83417. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  83418. return _this._effects;
  83419. }, true) || this;
  83420. /**
  83421. * @hidden Internal post processes in depth of field effect
  83422. */
  83423. _this._effects = [];
  83424. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  83425. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83426. // 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)
  83427. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  83428. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  83429. _this._depthOfFieldBlurY = [];
  83430. _this._depthOfFieldBlurX = [];
  83431. var blurCount = 1;
  83432. var kernelSize = 15;
  83433. switch (blurLevel) {
  83434. case DepthOfFieldEffectBlurLevel.High: {
  83435. blurCount = 3;
  83436. kernelSize = 51;
  83437. break;
  83438. }
  83439. case DepthOfFieldEffectBlurLevel.Medium: {
  83440. blurCount = 2;
  83441. kernelSize = 31;
  83442. break;
  83443. }
  83444. default: {
  83445. kernelSize = 15;
  83446. blurCount = 1;
  83447. break;
  83448. }
  83449. }
  83450. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  83451. var ratio = 1.0;
  83452. for (var i = 0; i < blurCount; i++) {
  83453. 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);
  83454. blurY.autoClear = false;
  83455. ratio = 0.75 / Math.pow(2, i);
  83456. 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);
  83457. blurX.autoClear = false;
  83458. _this._depthOfFieldBlurY.push(blurY);
  83459. _this._depthOfFieldBlurX.push(blurX);
  83460. }
  83461. // Set all post processes on the effect.
  83462. _this._effects = [_this._circleOfConfusion];
  83463. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  83464. _this._effects.push(_this._depthOfFieldBlurY[i]);
  83465. _this._effects.push(_this._depthOfFieldBlurX[i]);
  83466. }
  83467. // Merge blurred images with original image based on circleOfConfusion
  83468. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83469. _this._dofMerge.autoClear = false;
  83470. _this._effects.push(_this._dofMerge);
  83471. return _this;
  83472. }
  83473. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  83474. get: function () {
  83475. return this._circleOfConfusion.focalLength;
  83476. },
  83477. /**
  83478. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  83479. */
  83480. set: function (value) {
  83481. this._circleOfConfusion.focalLength = value;
  83482. },
  83483. enumerable: true,
  83484. configurable: true
  83485. });
  83486. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  83487. get: function () {
  83488. return this._circleOfConfusion.fStop;
  83489. },
  83490. /**
  83491. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  83492. */
  83493. set: function (value) {
  83494. this._circleOfConfusion.fStop = value;
  83495. },
  83496. enumerable: true,
  83497. configurable: true
  83498. });
  83499. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  83500. get: function () {
  83501. return this._circleOfConfusion.focusDistance;
  83502. },
  83503. /**
  83504. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  83505. */
  83506. set: function (value) {
  83507. this._circleOfConfusion.focusDistance = value;
  83508. },
  83509. enumerable: true,
  83510. configurable: true
  83511. });
  83512. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  83513. get: function () {
  83514. return this._circleOfConfusion.lensSize;
  83515. },
  83516. /**
  83517. * 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.
  83518. */
  83519. set: function (value) {
  83520. this._circleOfConfusion.lensSize = value;
  83521. },
  83522. enumerable: true,
  83523. configurable: true
  83524. });
  83525. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  83526. /**
  83527. * 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.
  83528. */
  83529. set: function (value) {
  83530. this._circleOfConfusion.depthTexture = value;
  83531. },
  83532. enumerable: true,
  83533. configurable: true
  83534. });
  83535. /**
  83536. * Disposes each of the internal effects for a given camera.
  83537. * @param camera The camera to dispose the effect on.
  83538. */
  83539. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  83540. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83541. this._effects[effectIndex].dispose(camera);
  83542. }
  83543. };
  83544. /**
  83545. * @hidden Internal
  83546. */
  83547. DepthOfFieldEffect.prototype._updateEffects = function () {
  83548. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83549. this._effects[effectIndex].updateEffect();
  83550. }
  83551. };
  83552. /**
  83553. * Internal
  83554. * @returns if all the contained post processes are ready.
  83555. * @hidden
  83556. */
  83557. DepthOfFieldEffect.prototype._isReady = function () {
  83558. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83559. if (!this._effects[effectIndex].isReady()) {
  83560. return false;
  83561. }
  83562. }
  83563. return true;
  83564. };
  83565. return DepthOfFieldEffect;
  83566. }(BABYLON.PostProcessRenderEffect));
  83567. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  83568. })(BABYLON || (BABYLON = {}));
  83569. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  83570. var BABYLON;
  83571. (function (BABYLON) {
  83572. /**
  83573. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83574. */
  83575. var BloomMergePostProcess = /** @class */ (function (_super) {
  83576. __extends(BloomMergePostProcess, _super);
  83577. /**
  83578. * Creates a new instance of @see BloomMergePostProcess
  83579. * @param name The name of the effect.
  83580. * @param originalFromInput Post process which's input will be used for the merge.
  83581. * @param blurred Blurred highlights post process which's output will be used.
  83582. * @param weight Weight of the bloom to be added to the original input.
  83583. * @param options The required width/height ratio to downsize to before computing the render pass.
  83584. * @param camera The camera to apply the render pass to.
  83585. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83586. * @param engine The engine which the post process will be applied. (default: current engine)
  83587. * @param reusable If the post process can be reused on the same frame. (default: false)
  83588. * @param textureType Type of textures used when performing the post process. (default: 0)
  83589. * @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)
  83590. */
  83591. function BloomMergePostProcess(name, originalFromInput, blurred,
  83592. /** Weight of the bloom to be added to the original input. */
  83593. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83594. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83595. if (blockCompilation === void 0) { blockCompilation = false; }
  83596. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83597. _this.weight = weight;
  83598. _this.onApplyObservable.add(function (effect) {
  83599. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83600. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  83601. effect.setFloat("bloomWeight", _this.weight);
  83602. });
  83603. if (!blockCompilation) {
  83604. _this.updateEffect();
  83605. }
  83606. return _this;
  83607. }
  83608. return BloomMergePostProcess;
  83609. }(BABYLON.PostProcess));
  83610. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  83611. })(BABYLON || (BABYLON = {}));
  83612. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  83613. var BABYLON;
  83614. (function (BABYLON) {
  83615. /**
  83616. * 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.
  83617. */
  83618. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  83619. __extends(ExtractHighlightsPostProcess, _super);
  83620. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83621. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83622. if (blockCompilation === void 0) { blockCompilation = false; }
  83623. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83624. /**
  83625. * The luminance threshold, pixels below this value will be set to black.
  83626. */
  83627. _this.threshold = 0.9;
  83628. /** @hidden */
  83629. _this._exposure = 1;
  83630. /**
  83631. * Post process which has the input texture to be used when performing highlight extraction
  83632. * @hidden
  83633. */
  83634. _this._inputPostProcess = null;
  83635. _this.onApplyObservable.add(function (effect) {
  83636. if (_this._inputPostProcess) {
  83637. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  83638. }
  83639. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  83640. effect.setFloat('exposure', _this._exposure);
  83641. });
  83642. return _this;
  83643. }
  83644. return ExtractHighlightsPostProcess;
  83645. }(BABYLON.PostProcess));
  83646. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  83647. })(BABYLON || (BABYLON = {}));
  83648. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  83649. var BABYLON;
  83650. (function (BABYLON) {
  83651. /**
  83652. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  83653. */
  83654. var BloomEffect = /** @class */ (function (_super) {
  83655. __extends(BloomEffect, _super);
  83656. /**
  83657. * Creates a new instance of @see BloomEffect
  83658. * @param scene The scene the effect belongs to.
  83659. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  83660. * @param bloomKernel The size of the kernel to be used when applying the blur.
  83661. * @param bloomWeight The the strength of bloom.
  83662. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  83663. * @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)
  83664. */
  83665. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  83666. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  83667. if (blockCompilation === void 0) { blockCompilation = false; }
  83668. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  83669. return _this._effects;
  83670. }, true) || this;
  83671. _this.bloomScale = bloomScale;
  83672. /**
  83673. * @hidden Internal
  83674. */
  83675. _this._effects = [];
  83676. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83677. _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);
  83678. _this._blurX.alwaysForcePOT = true;
  83679. _this._blurX.autoClear = false;
  83680. _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);
  83681. _this._blurY.alwaysForcePOT = true;
  83682. _this._blurY.autoClear = false;
  83683. _this.kernel = bloomKernel;
  83684. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  83685. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83686. _this._merge.autoClear = false;
  83687. _this._effects.push(_this._merge);
  83688. return _this;
  83689. }
  83690. Object.defineProperty(BloomEffect.prototype, "threshold", {
  83691. /**
  83692. * The luminance threshold to find bright areas of the image to bloom.
  83693. */
  83694. get: function () {
  83695. return this._downscale.threshold;
  83696. },
  83697. set: function (value) {
  83698. this._downscale.threshold = value;
  83699. },
  83700. enumerable: true,
  83701. configurable: true
  83702. });
  83703. Object.defineProperty(BloomEffect.prototype, "weight", {
  83704. /**
  83705. * The strength of the bloom.
  83706. */
  83707. get: function () {
  83708. return this._merge.weight;
  83709. },
  83710. set: function (value) {
  83711. this._merge.weight = value;
  83712. },
  83713. enumerable: true,
  83714. configurable: true
  83715. });
  83716. Object.defineProperty(BloomEffect.prototype, "kernel", {
  83717. /**
  83718. * Specifies the size of the bloom blur kernel, relative to the final output size
  83719. */
  83720. get: function () {
  83721. return this._blurX.kernel / this.bloomScale;
  83722. },
  83723. set: function (value) {
  83724. this._blurX.kernel = value * this.bloomScale;
  83725. this._blurY.kernel = value * this.bloomScale;
  83726. },
  83727. enumerable: true,
  83728. configurable: true
  83729. });
  83730. /**
  83731. * Disposes each of the internal effects for a given camera.
  83732. * @param camera The camera to dispose the effect on.
  83733. */
  83734. BloomEffect.prototype.disposeEffects = function (camera) {
  83735. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83736. this._effects[effectIndex].dispose(camera);
  83737. }
  83738. };
  83739. /**
  83740. * @hidden Internal
  83741. */
  83742. BloomEffect.prototype._updateEffects = function () {
  83743. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83744. this._effects[effectIndex].updateEffect();
  83745. }
  83746. };
  83747. /**
  83748. * Internal
  83749. * @returns if all the contained post processes are ready.
  83750. * @hidden
  83751. */
  83752. BloomEffect.prototype._isReady = function () {
  83753. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83754. if (!this._effects[effectIndex].isReady()) {
  83755. return false;
  83756. }
  83757. }
  83758. return true;
  83759. };
  83760. return BloomEffect;
  83761. }(BABYLON.PostProcessRenderEffect));
  83762. BABYLON.BloomEffect = BloomEffect;
  83763. })(BABYLON || (BABYLON = {}));
  83764. //# sourceMappingURL=babylon.bloomEffect.js.map
  83765. var BABYLON;
  83766. (function (BABYLON) {
  83767. /**
  83768. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  83769. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  83770. */
  83771. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  83772. __extends(DefaultRenderingPipeline, _super);
  83773. /**
  83774. * @constructor
  83775. * @param {string} name - The rendering pipeline name (default: "")
  83776. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  83777. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  83778. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  83779. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  83780. */
  83781. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  83782. if (name === void 0) { name = ""; }
  83783. if (hdr === void 0) { hdr = true; }
  83784. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  83785. if (automaticBuild === void 0) { automaticBuild = true; }
  83786. var _this = _super.call(this, scene.getEngine(), name) || this;
  83787. _this._camerasToBeAttached = [];
  83788. /**
  83789. * ID of the sharpen post process,
  83790. */
  83791. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  83792. /**
  83793. * ID of the image processing post process;
  83794. */
  83795. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  83796. /**
  83797. * ID of the Fast Approximate Anti-Aliasing post process;
  83798. */
  83799. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  83800. /**
  83801. * ID of the chromatic aberration post process,
  83802. */
  83803. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  83804. /**
  83805. * ID of the grain post process
  83806. */
  83807. _this.GrainPostProcessId = "GrainPostProcessEffect";
  83808. /**
  83809. * Glow post process which adds a glow to emmisive areas of the image
  83810. */
  83811. _this._glowLayer = null;
  83812. /**
  83813. * Animations which can be used to tweak settings over a period of time
  83814. */
  83815. _this.animations = [];
  83816. _this._imageProcessingConfigurationObserver = null;
  83817. // Values
  83818. _this._sharpenEnabled = false;
  83819. _this._bloomEnabled = false;
  83820. _this._depthOfFieldEnabled = false;
  83821. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  83822. _this._fxaaEnabled = false;
  83823. _this._imageProcessingEnabled = true;
  83824. _this._bloomScale = 0.5;
  83825. _this._chromaticAberrationEnabled = false;
  83826. _this._grainEnabled = false;
  83827. _this._buildAllowed = true;
  83828. _this._resizeObserver = null;
  83829. _this._hardwareScaleLevel = 1.0;
  83830. _this._bloomKernel = 64;
  83831. /**
  83832. * Specifies the weight of the bloom in the final rendering
  83833. */
  83834. _this._bloomWeight = 0.15;
  83835. /**
  83836. * Specifies the luma threshold for the area that will be blurred by the bloom
  83837. */
  83838. _this._bloomThreshold = 0.9;
  83839. _this._samples = 1;
  83840. _this._hasCleared = false;
  83841. _this._prevPostProcess = null;
  83842. _this._prevPrevPostProcess = null;
  83843. _this._depthOfFieldSceneObserver = null;
  83844. _this._cameras = cameras || scene.cameras;
  83845. _this._cameras = _this._cameras.slice();
  83846. _this._camerasToBeAttached = _this._cameras.slice();
  83847. _this._buildAllowed = automaticBuild;
  83848. // Initialize
  83849. _this._scene = scene;
  83850. var caps = _this._scene.getEngine().getCaps();
  83851. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  83852. // Misc
  83853. if (_this._hdr) {
  83854. if (caps.textureHalfFloatRender) {
  83855. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83856. }
  83857. else if (caps.textureFloatRender) {
  83858. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83859. }
  83860. }
  83861. else {
  83862. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83863. }
  83864. // Attach
  83865. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83866. var engine = _this._scene.getEngine();
  83867. // Create post processes before hand so they can be modified before enabled.
  83868. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  83869. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83870. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  83871. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  83872. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  83873. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83874. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  83875. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83876. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  83877. _this._resizeObserver = engine.onResizeObservable.add(function () {
  83878. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  83879. _this.bloomKernel = _this.bloomKernel;
  83880. });
  83881. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  83882. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  83883. });
  83884. _this._buildPipeline();
  83885. return _this;
  83886. }
  83887. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  83888. get: function () {
  83889. return this._sharpenEnabled;
  83890. },
  83891. /**
  83892. * Enable or disable the sharpen process from the pipeline
  83893. */
  83894. set: function (enabled) {
  83895. if (this._sharpenEnabled === enabled) {
  83896. return;
  83897. }
  83898. this._sharpenEnabled = enabled;
  83899. this._buildPipeline();
  83900. },
  83901. enumerable: true,
  83902. configurable: true
  83903. });
  83904. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  83905. /**
  83906. * Specifies the size of the bloom blur kernel, relative to the final output size
  83907. */
  83908. get: function () {
  83909. return this._bloomKernel;
  83910. },
  83911. set: function (value) {
  83912. this._bloomKernel = value;
  83913. this.bloom.kernel = value / this._hardwareScaleLevel;
  83914. },
  83915. enumerable: true,
  83916. configurable: true
  83917. });
  83918. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  83919. get: function () {
  83920. return this._bloomWeight;
  83921. },
  83922. /**
  83923. * The strength of the bloom.
  83924. */
  83925. set: function (value) {
  83926. if (this._bloomWeight === value) {
  83927. return;
  83928. }
  83929. this.bloom.weight = value;
  83930. this._bloomWeight = value;
  83931. },
  83932. enumerable: true,
  83933. configurable: true
  83934. });
  83935. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  83936. get: function () {
  83937. return this._bloomThreshold;
  83938. },
  83939. /**
  83940. * The strength of the bloom.
  83941. */
  83942. set: function (value) {
  83943. if (this._bloomThreshold === value) {
  83944. return;
  83945. }
  83946. this.bloom.threshold = value;
  83947. this._bloomThreshold = value;
  83948. },
  83949. enumerable: true,
  83950. configurable: true
  83951. });
  83952. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  83953. get: function () {
  83954. return this._bloomScale;
  83955. },
  83956. /**
  83957. * The scale of the bloom, lower value will provide better performance.
  83958. */
  83959. set: function (value) {
  83960. if (this._bloomScale === value) {
  83961. return;
  83962. }
  83963. this._bloomScale = value;
  83964. // recreate bloom and dispose old as this setting is not dynamic
  83965. this._rebuildBloom();
  83966. this._buildPipeline();
  83967. },
  83968. enumerable: true,
  83969. configurable: true
  83970. });
  83971. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  83972. get: function () {
  83973. return this._bloomEnabled;
  83974. },
  83975. /**
  83976. * Enable or disable the bloom from the pipeline
  83977. */
  83978. set: function (enabled) {
  83979. if (this._bloomEnabled === enabled) {
  83980. return;
  83981. }
  83982. this._bloomEnabled = enabled;
  83983. this._buildPipeline();
  83984. },
  83985. enumerable: true,
  83986. configurable: true
  83987. });
  83988. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  83989. // recreate bloom and dispose old as this setting is not dynamic
  83990. var oldBloom = this.bloom;
  83991. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  83992. this.bloom.threshold = oldBloom.threshold;
  83993. for (var i = 0; i < this._cameras.length; i++) {
  83994. oldBloom.disposeEffects(this._cameras[i]);
  83995. }
  83996. };
  83997. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  83998. /**
  83999. * If the depth of field is enabled.
  84000. */
  84001. get: function () {
  84002. return this._depthOfFieldEnabled;
  84003. },
  84004. set: function (enabled) {
  84005. if (this._depthOfFieldEnabled === enabled) {
  84006. return;
  84007. }
  84008. this._depthOfFieldEnabled = enabled;
  84009. this._buildPipeline();
  84010. },
  84011. enumerable: true,
  84012. configurable: true
  84013. });
  84014. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  84015. /**
  84016. * Blur level of the depth of field effect. (Higher blur will effect performance)
  84017. */
  84018. get: function () {
  84019. return this._depthOfFieldBlurLevel;
  84020. },
  84021. set: function (value) {
  84022. if (this._depthOfFieldBlurLevel === value) {
  84023. return;
  84024. }
  84025. this._depthOfFieldBlurLevel = value;
  84026. // recreate dof and dispose old as this setting is not dynamic
  84027. var oldDof = this.depthOfField;
  84028. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  84029. this.depthOfField.focalLength = oldDof.focalLength;
  84030. this.depthOfField.focusDistance = oldDof.focusDistance;
  84031. this.depthOfField.fStop = oldDof.fStop;
  84032. this.depthOfField.lensSize = oldDof.lensSize;
  84033. for (var i = 0; i < this._cameras.length; i++) {
  84034. oldDof.disposeEffects(this._cameras[i]);
  84035. }
  84036. this._buildPipeline();
  84037. },
  84038. enumerable: true,
  84039. configurable: true
  84040. });
  84041. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  84042. get: function () {
  84043. return this._fxaaEnabled;
  84044. },
  84045. /**
  84046. * If the anti aliasing is enabled.
  84047. */
  84048. set: function (enabled) {
  84049. if (this._fxaaEnabled === enabled) {
  84050. return;
  84051. }
  84052. this._fxaaEnabled = enabled;
  84053. this._buildPipeline();
  84054. },
  84055. enumerable: true,
  84056. configurable: true
  84057. });
  84058. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  84059. get: function () {
  84060. return this._samples;
  84061. },
  84062. /**
  84063. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  84064. */
  84065. set: function (sampleCount) {
  84066. if (this._samples === sampleCount) {
  84067. return;
  84068. }
  84069. this._samples = sampleCount;
  84070. this._buildPipeline();
  84071. },
  84072. enumerable: true,
  84073. configurable: true
  84074. });
  84075. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  84076. get: function () {
  84077. return this._imageProcessingEnabled;
  84078. },
  84079. /**
  84080. * If image processing is enabled.
  84081. */
  84082. set: function (enabled) {
  84083. if (this._imageProcessingEnabled === enabled) {
  84084. return;
  84085. }
  84086. this._imageProcessingEnabled = enabled;
  84087. this._buildPipeline();
  84088. },
  84089. enumerable: true,
  84090. configurable: true
  84091. });
  84092. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  84093. get: function () {
  84094. return this._glowLayer == null;
  84095. },
  84096. /**
  84097. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  84098. */
  84099. set: function (enabled) {
  84100. if (enabled && !this._glowLayer) {
  84101. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  84102. }
  84103. else if (!enabled && this._glowLayer) {
  84104. this._glowLayer.dispose();
  84105. this._glowLayer = null;
  84106. }
  84107. },
  84108. enumerable: true,
  84109. configurable: true
  84110. });
  84111. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  84112. get: function () {
  84113. return this._chromaticAberrationEnabled;
  84114. },
  84115. /**
  84116. * Enable or disable the chromaticAberration process from the pipeline
  84117. */
  84118. set: function (enabled) {
  84119. if (this._chromaticAberrationEnabled === enabled) {
  84120. return;
  84121. }
  84122. this._chromaticAberrationEnabled = enabled;
  84123. this._buildPipeline();
  84124. },
  84125. enumerable: true,
  84126. configurable: true
  84127. });
  84128. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  84129. get: function () {
  84130. return this._grainEnabled;
  84131. },
  84132. /**
  84133. * Enable or disable the grain process from the pipeline
  84134. */
  84135. set: function (enabled) {
  84136. if (this._grainEnabled === enabled) {
  84137. return;
  84138. }
  84139. this._grainEnabled = enabled;
  84140. this._buildPipeline();
  84141. },
  84142. enumerable: true,
  84143. configurable: true
  84144. });
  84145. /**
  84146. * Force the compilation of the entire pipeline.
  84147. */
  84148. DefaultRenderingPipeline.prototype.prepare = function () {
  84149. var previousState = this._buildAllowed;
  84150. this._buildAllowed = true;
  84151. this._buildPipeline();
  84152. this._buildAllowed = previousState;
  84153. };
  84154. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  84155. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  84156. if (this._hasCleared) {
  84157. postProcess.autoClear = false;
  84158. }
  84159. else {
  84160. postProcess.autoClear = true;
  84161. this._scene.autoClear = false;
  84162. this._hasCleared = true;
  84163. }
  84164. if (!skipTextureSharing) {
  84165. if (this._prevPrevPostProcess) {
  84166. postProcess.shareOutputWith(this._prevPrevPostProcess);
  84167. }
  84168. else {
  84169. postProcess.useOwnOutput();
  84170. }
  84171. if (this._prevPostProcess) {
  84172. this._prevPrevPostProcess = this._prevPostProcess;
  84173. }
  84174. this._prevPostProcess = postProcess;
  84175. }
  84176. };
  84177. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  84178. var _this = this;
  84179. if (!this._buildAllowed) {
  84180. return;
  84181. }
  84182. this._scene.autoClear = true;
  84183. var engine = this._scene.getEngine();
  84184. this._disposePostProcesses();
  84185. if (this._cameras !== null) {
  84186. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84187. // get back cameras to be used to reattach pipeline
  84188. this._cameras = this._camerasToBeAttached.slice();
  84189. }
  84190. this._reset();
  84191. this._prevPostProcess = null;
  84192. this._prevPrevPostProcess = null;
  84193. this._hasCleared = false;
  84194. if (this.depthOfFieldEnabled) {
  84195. // Multi camera suport
  84196. if (this._cameras.length > 1) {
  84197. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  84198. var camera = _a[_i];
  84199. var depthRenderer = this._scene.enableDepthRenderer(camera);
  84200. depthRenderer.useOnlyInActiveCamera = true;
  84201. }
  84202. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  84203. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  84204. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  84205. }
  84206. });
  84207. }
  84208. else {
  84209. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84210. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  84211. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  84212. }
  84213. if (!this.depthOfField._isReady()) {
  84214. this.depthOfField._updateEffects();
  84215. }
  84216. this.addEffect(this.depthOfField);
  84217. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  84218. }
  84219. else {
  84220. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84221. }
  84222. if (this.bloomEnabled) {
  84223. if (!this.bloom._isReady()) {
  84224. this.bloom._updateEffects();
  84225. }
  84226. this.addEffect(this.bloom);
  84227. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  84228. }
  84229. if (this._imageProcessingEnabled) {
  84230. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  84231. if (this._hdr) {
  84232. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  84233. this._setAutoClearAndTextureSharing(this.imageProcessing);
  84234. }
  84235. else {
  84236. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  84237. }
  84238. }
  84239. if (this.sharpenEnabled) {
  84240. if (!this.sharpen.isReady()) {
  84241. this.sharpen.updateEffect();
  84242. }
  84243. this.addEffect(this._sharpenEffect);
  84244. this._setAutoClearAndTextureSharing(this.sharpen);
  84245. }
  84246. if (this.grainEnabled) {
  84247. if (!this.grain.isReady()) {
  84248. this.grain.updateEffect();
  84249. }
  84250. this.addEffect(this._grainEffect);
  84251. this._setAutoClearAndTextureSharing(this.grain);
  84252. }
  84253. if (this.chromaticAberrationEnabled) {
  84254. if (!this.chromaticAberration.isReady()) {
  84255. this.chromaticAberration.updateEffect();
  84256. }
  84257. this.addEffect(this._chromaticAberrationEffect);
  84258. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  84259. }
  84260. if (this.fxaaEnabled) {
  84261. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  84262. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  84263. this._setAutoClearAndTextureSharing(this.fxaa, true);
  84264. }
  84265. if (this._cameras !== null) {
  84266. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  84267. }
  84268. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  84269. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  84270. }
  84271. };
  84272. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  84273. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  84274. for (var i = 0; i < this._cameras.length; i++) {
  84275. var camera = this._cameras[i];
  84276. if (this.imageProcessing) {
  84277. this.imageProcessing.dispose(camera);
  84278. }
  84279. if (this.fxaa) {
  84280. this.fxaa.dispose(camera);
  84281. }
  84282. // These are created in the constructor and should not be disposed on every pipeline change
  84283. if (disposeNonRecreated) {
  84284. if (this.sharpen) {
  84285. this.sharpen.dispose(camera);
  84286. }
  84287. if (this.depthOfField) {
  84288. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84289. this.depthOfField.disposeEffects(camera);
  84290. }
  84291. if (this.bloom) {
  84292. this.bloom.disposeEffects(camera);
  84293. }
  84294. if (this.chromaticAberration) {
  84295. this.chromaticAberration.dispose(camera);
  84296. }
  84297. if (this.grain) {
  84298. this.grain.dispose(camera);
  84299. }
  84300. if (this._glowLayer) {
  84301. this._glowLayer.dispose();
  84302. }
  84303. }
  84304. }
  84305. this.imageProcessing = null;
  84306. this.fxaa = null;
  84307. if (disposeNonRecreated) {
  84308. this.sharpen = null;
  84309. this._sharpenEffect = null;
  84310. this.depthOfField = null;
  84311. this.bloom = null;
  84312. this.chromaticAberration = null;
  84313. this._chromaticAberrationEffect = null;
  84314. this.grain = null;
  84315. this._grainEffect = null;
  84316. this._glowLayer = null;
  84317. }
  84318. };
  84319. /**
  84320. * Adds a camera to the pipeline
  84321. * @param camera the camera to be added
  84322. */
  84323. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  84324. this._camerasToBeAttached.push(camera);
  84325. this._buildPipeline();
  84326. };
  84327. /**
  84328. * Removes a camera from the pipeline
  84329. * @param camera the camera to remove
  84330. */
  84331. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  84332. var index = this._camerasToBeAttached.indexOf(camera);
  84333. this._camerasToBeAttached.splice(index, 1);
  84334. this._buildPipeline();
  84335. };
  84336. /**
  84337. * Dispose of the pipeline and stop all post processes
  84338. */
  84339. DefaultRenderingPipeline.prototype.dispose = function () {
  84340. this._disposePostProcesses(true);
  84341. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84342. this._scene.autoClear = true;
  84343. if (this._resizeObserver) {
  84344. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  84345. this._resizeObserver = null;
  84346. }
  84347. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  84348. _super.prototype.dispose.call(this);
  84349. };
  84350. /**
  84351. * Serialize the rendering pipeline (Used when exporting)
  84352. * @returns the serialized object
  84353. */
  84354. DefaultRenderingPipeline.prototype.serialize = function () {
  84355. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84356. serializationObject.customType = "DefaultRenderingPipeline";
  84357. return serializationObject;
  84358. };
  84359. /**
  84360. * Parse the serialized pipeline
  84361. * @param source Source pipeline.
  84362. * @param scene The scene to load the pipeline to.
  84363. * @param rootUrl The URL of the serialized pipeline.
  84364. * @returns An instantiated pipeline from the serialized object.
  84365. */
  84366. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  84367. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  84368. };
  84369. __decorate([
  84370. BABYLON.serialize()
  84371. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  84372. __decorate([
  84373. BABYLON.serialize()
  84374. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  84375. __decorate([
  84376. BABYLON.serialize()
  84377. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  84378. __decorate([
  84379. BABYLON.serialize()
  84380. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  84381. __decorate([
  84382. BABYLON.serialize()
  84383. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  84384. __decorate([
  84385. BABYLON.serialize()
  84386. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  84387. __decorate([
  84388. BABYLON.serialize()
  84389. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  84390. __decorate([
  84391. BABYLON.serialize()
  84392. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  84393. __decorate([
  84394. BABYLON.serialize()
  84395. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  84396. __decorate([
  84397. BABYLON.serialize()
  84398. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  84399. __decorate([
  84400. BABYLON.serialize()
  84401. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  84402. __decorate([
  84403. BABYLON.serialize()
  84404. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  84405. __decorate([
  84406. BABYLON.serialize()
  84407. ], DefaultRenderingPipeline.prototype, "samples", null);
  84408. __decorate([
  84409. BABYLON.serialize()
  84410. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  84411. __decorate([
  84412. BABYLON.serialize()
  84413. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  84414. __decorate([
  84415. BABYLON.serialize()
  84416. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  84417. __decorate([
  84418. BABYLON.serialize()
  84419. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  84420. return DefaultRenderingPipeline;
  84421. }(BABYLON.PostProcessRenderPipeline));
  84422. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  84423. })(BABYLON || (BABYLON = {}));
  84424. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  84425. var BABYLON;
  84426. (function (BABYLON) {
  84427. /**
  84428. * @hidden
  84429. */
  84430. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  84431. __extends(ImageProcessingConfigurationDefines, _super);
  84432. function ImageProcessingConfigurationDefines() {
  84433. var _this = _super.call(this) || this;
  84434. _this.IMAGEPROCESSING = false;
  84435. _this.VIGNETTE = false;
  84436. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  84437. _this.VIGNETTEBLENDMODEOPAQUE = false;
  84438. _this.TONEMAPPING = false;
  84439. _this.TONEMAPPING_ACES = false;
  84440. _this.CONTRAST = false;
  84441. _this.COLORCURVES = false;
  84442. _this.COLORGRADING = false;
  84443. _this.COLORGRADING3D = false;
  84444. _this.SAMPLER3DGREENDEPTH = false;
  84445. _this.SAMPLER3DBGRMAP = false;
  84446. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  84447. _this.EXPOSURE = false;
  84448. _this.rebuild();
  84449. return _this;
  84450. }
  84451. return ImageProcessingConfigurationDefines;
  84452. }(BABYLON.MaterialDefines));
  84453. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  84454. /**
  84455. * This groups together the common properties used for image processing either in direct forward pass
  84456. * or through post processing effect depending on the use of the image processing pipeline in your scene
  84457. * or not.
  84458. */
  84459. var ImageProcessingConfiguration = /** @class */ (function () {
  84460. function ImageProcessingConfiguration() {
  84461. /**
  84462. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  84463. */
  84464. this.colorCurves = new BABYLON.ColorCurves();
  84465. this._colorCurvesEnabled = false;
  84466. this._colorGradingEnabled = false;
  84467. this._colorGradingWithGreenDepth = true;
  84468. this._colorGradingBGR = true;
  84469. /** @hidden */
  84470. this._exposure = 1.0;
  84471. this._toneMappingEnabled = false;
  84472. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  84473. this._contrast = 1.0;
  84474. /**
  84475. * Vignette stretch size.
  84476. */
  84477. this.vignetteStretch = 0;
  84478. /**
  84479. * Vignette centre X Offset.
  84480. */
  84481. this.vignetteCentreX = 0;
  84482. /**
  84483. * Vignette centre Y Offset.
  84484. */
  84485. this.vignetteCentreY = 0;
  84486. /**
  84487. * Vignette weight or intensity of the vignette effect.
  84488. */
  84489. this.vignetteWeight = 1.5;
  84490. /**
  84491. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84492. * if vignetteEnabled is set to true.
  84493. */
  84494. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  84495. /**
  84496. * Camera field of view used by the Vignette effect.
  84497. */
  84498. this.vignetteCameraFov = 0.5;
  84499. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  84500. this._vignetteEnabled = false;
  84501. this._applyByPostProcess = false;
  84502. this._isEnabled = true;
  84503. /**
  84504. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  84505. */
  84506. this.onUpdateParameters = new BABYLON.Observable();
  84507. }
  84508. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  84509. /**
  84510. * Gets wether the color curves effect is enabled.
  84511. */
  84512. get: function () {
  84513. return this._colorCurvesEnabled;
  84514. },
  84515. /**
  84516. * Sets wether the color curves effect is enabled.
  84517. */
  84518. set: function (value) {
  84519. if (this._colorCurvesEnabled === value) {
  84520. return;
  84521. }
  84522. this._colorCurvesEnabled = value;
  84523. this._updateParameters();
  84524. },
  84525. enumerable: true,
  84526. configurable: true
  84527. });
  84528. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  84529. /**
  84530. * Gets wether the color grading effect is enabled.
  84531. */
  84532. get: function () {
  84533. return this._colorGradingEnabled;
  84534. },
  84535. /**
  84536. * Sets wether the color grading effect is enabled.
  84537. */
  84538. set: function (value) {
  84539. if (this._colorGradingEnabled === value) {
  84540. return;
  84541. }
  84542. this._colorGradingEnabled = value;
  84543. this._updateParameters();
  84544. },
  84545. enumerable: true,
  84546. configurable: true
  84547. });
  84548. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  84549. /**
  84550. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  84551. */
  84552. get: function () {
  84553. return this._colorGradingWithGreenDepth;
  84554. },
  84555. /**
  84556. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  84557. */
  84558. set: function (value) {
  84559. if (this._colorGradingWithGreenDepth === value) {
  84560. return;
  84561. }
  84562. this._colorGradingWithGreenDepth = value;
  84563. this._updateParameters();
  84564. },
  84565. enumerable: true,
  84566. configurable: true
  84567. });
  84568. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  84569. /**
  84570. * Gets wether the color grading texture contains BGR values.
  84571. */
  84572. get: function () {
  84573. return this._colorGradingBGR;
  84574. },
  84575. /**
  84576. * Sets wether the color grading texture contains BGR values.
  84577. */
  84578. set: function (value) {
  84579. if (this._colorGradingBGR === value) {
  84580. return;
  84581. }
  84582. this._colorGradingBGR = value;
  84583. this._updateParameters();
  84584. },
  84585. enumerable: true,
  84586. configurable: true
  84587. });
  84588. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  84589. /**
  84590. * Gets the Exposure used in the effect.
  84591. */
  84592. get: function () {
  84593. return this._exposure;
  84594. },
  84595. /**
  84596. * Sets the Exposure used in the effect.
  84597. */
  84598. set: function (value) {
  84599. if (this._exposure === value) {
  84600. return;
  84601. }
  84602. this._exposure = value;
  84603. this._updateParameters();
  84604. },
  84605. enumerable: true,
  84606. configurable: true
  84607. });
  84608. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  84609. /**
  84610. * Gets wether the tone mapping effect is enabled.
  84611. */
  84612. get: function () {
  84613. return this._toneMappingEnabled;
  84614. },
  84615. /**
  84616. * Sets wether the tone mapping effect is enabled.
  84617. */
  84618. set: function (value) {
  84619. if (this._toneMappingEnabled === value) {
  84620. return;
  84621. }
  84622. this._toneMappingEnabled = value;
  84623. this._updateParameters();
  84624. },
  84625. enumerable: true,
  84626. configurable: true
  84627. });
  84628. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  84629. /**
  84630. * Gets the type of tone mapping effect.
  84631. */
  84632. get: function () {
  84633. return this._toneMappingType;
  84634. },
  84635. /**
  84636. * Sets the type of tone mapping effect used in BabylonJS.
  84637. */
  84638. set: function (value) {
  84639. if (this._toneMappingType === value) {
  84640. return;
  84641. }
  84642. this._toneMappingType = value;
  84643. this._updateParameters();
  84644. },
  84645. enumerable: true,
  84646. configurable: true
  84647. });
  84648. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  84649. /**
  84650. * Gets the contrast used in the effect.
  84651. */
  84652. get: function () {
  84653. return this._contrast;
  84654. },
  84655. /**
  84656. * Sets the contrast used in the effect.
  84657. */
  84658. set: function (value) {
  84659. if (this._contrast === value) {
  84660. return;
  84661. }
  84662. this._contrast = value;
  84663. this._updateParameters();
  84664. },
  84665. enumerable: true,
  84666. configurable: true
  84667. });
  84668. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  84669. /**
  84670. * Gets the vignette blend mode allowing different kind of effect.
  84671. */
  84672. get: function () {
  84673. return this._vignetteBlendMode;
  84674. },
  84675. /**
  84676. * Sets the vignette blend mode allowing different kind of effect.
  84677. */
  84678. set: function (value) {
  84679. if (this._vignetteBlendMode === value) {
  84680. return;
  84681. }
  84682. this._vignetteBlendMode = value;
  84683. this._updateParameters();
  84684. },
  84685. enumerable: true,
  84686. configurable: true
  84687. });
  84688. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  84689. /**
  84690. * Gets wether the vignette effect is enabled.
  84691. */
  84692. get: function () {
  84693. return this._vignetteEnabled;
  84694. },
  84695. /**
  84696. * Sets wether the vignette effect is enabled.
  84697. */
  84698. set: function (value) {
  84699. if (this._vignetteEnabled === value) {
  84700. return;
  84701. }
  84702. this._vignetteEnabled = value;
  84703. this._updateParameters();
  84704. },
  84705. enumerable: true,
  84706. configurable: true
  84707. });
  84708. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  84709. /**
  84710. * Gets wether the image processing is applied through a post process or not.
  84711. */
  84712. get: function () {
  84713. return this._applyByPostProcess;
  84714. },
  84715. /**
  84716. * Sets wether the image processing is applied through a post process or not.
  84717. */
  84718. set: function (value) {
  84719. if (this._applyByPostProcess === value) {
  84720. return;
  84721. }
  84722. this._applyByPostProcess = value;
  84723. this._updateParameters();
  84724. },
  84725. enumerable: true,
  84726. configurable: true
  84727. });
  84728. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  84729. /**
  84730. * Gets wether the image processing is enabled or not.
  84731. */
  84732. get: function () {
  84733. return this._isEnabled;
  84734. },
  84735. /**
  84736. * Sets wether the image processing is enabled or not.
  84737. */
  84738. set: function (value) {
  84739. if (this._isEnabled === value) {
  84740. return;
  84741. }
  84742. this._isEnabled = value;
  84743. this._updateParameters();
  84744. },
  84745. enumerable: true,
  84746. configurable: true
  84747. });
  84748. /**
  84749. * Method called each time the image processing information changes requires to recompile the effect.
  84750. */
  84751. ImageProcessingConfiguration.prototype._updateParameters = function () {
  84752. this.onUpdateParameters.notifyObservers(this);
  84753. };
  84754. ImageProcessingConfiguration.prototype.getClassName = function () {
  84755. return "ImageProcessingConfiguration";
  84756. };
  84757. /**
  84758. * Prepare the list of uniforms associated with the Image Processing effects.
  84759. * @param uniformsList The list of uniforms used in the effect
  84760. * @param defines the list of defines currently in use
  84761. */
  84762. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  84763. if (defines.EXPOSURE) {
  84764. uniforms.push("exposureLinear");
  84765. }
  84766. if (defines.CONTRAST) {
  84767. uniforms.push("contrast");
  84768. }
  84769. if (defines.COLORGRADING) {
  84770. uniforms.push("colorTransformSettings");
  84771. }
  84772. if (defines.VIGNETTE) {
  84773. uniforms.push("vInverseScreenSize");
  84774. uniforms.push("vignetteSettings1");
  84775. uniforms.push("vignetteSettings2");
  84776. }
  84777. if (defines.COLORCURVES) {
  84778. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  84779. }
  84780. };
  84781. /**
  84782. * Prepare the list of samplers associated with the Image Processing effects.
  84783. * @param uniformsList The list of uniforms used in the effect
  84784. * @param defines the list of defines currently in use
  84785. */
  84786. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  84787. if (defines.COLORGRADING) {
  84788. samplersList.push("txColorTransform");
  84789. }
  84790. };
  84791. /**
  84792. * Prepare the list of defines associated to the shader.
  84793. * @param defines the list of defines to complete
  84794. */
  84795. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  84796. if (forPostProcess === void 0) { forPostProcess = false; }
  84797. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  84798. defines.VIGNETTE = false;
  84799. defines.TONEMAPPING = false;
  84800. defines.TONEMAPPING_ACES = false;
  84801. defines.CONTRAST = false;
  84802. defines.EXPOSURE = false;
  84803. defines.COLORCURVES = false;
  84804. defines.COLORGRADING = false;
  84805. defines.COLORGRADING3D = false;
  84806. defines.IMAGEPROCESSING = false;
  84807. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  84808. return;
  84809. }
  84810. defines.VIGNETTE = this.vignetteEnabled;
  84811. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  84812. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  84813. defines.TONEMAPPING = this.toneMappingEnabled;
  84814. switch (this._toneMappingType) {
  84815. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  84816. defines.TONEMAPPING_ACES = true;
  84817. break;
  84818. }
  84819. defines.CONTRAST = (this.contrast !== 1.0);
  84820. defines.EXPOSURE = (this.exposure !== 1.0);
  84821. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  84822. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  84823. if (defines.COLORGRADING) {
  84824. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  84825. }
  84826. else {
  84827. defines.COLORGRADING3D = false;
  84828. }
  84829. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  84830. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  84831. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  84832. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  84833. };
  84834. /**
  84835. * Returns true if all the image processing information are ready.
  84836. */
  84837. ImageProcessingConfiguration.prototype.isReady = function () {
  84838. // Color Grading texure can not be none blocking.
  84839. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  84840. };
  84841. /**
  84842. * Binds the image processing to the shader.
  84843. * @param effect The effect to bind to
  84844. */
  84845. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  84846. if (aspectRatio === void 0) { aspectRatio = 1; }
  84847. // Color Curves
  84848. if (this._colorCurvesEnabled && this.colorCurves) {
  84849. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  84850. }
  84851. // Vignette
  84852. if (this._vignetteEnabled) {
  84853. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  84854. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  84855. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  84856. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  84857. var vignetteScaleX = vignetteScaleY * aspectRatio;
  84858. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  84859. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  84860. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  84861. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  84862. var vignettePower = -2.0 * this.vignetteWeight;
  84863. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  84864. }
  84865. // Exposure
  84866. effect.setFloat("exposureLinear", this.exposure);
  84867. // Contrast
  84868. effect.setFloat("contrast", this.contrast);
  84869. // Color transform settings
  84870. if (this.colorGradingTexture) {
  84871. effect.setTexture("txColorTransform", this.colorGradingTexture);
  84872. var textureSize = this.colorGradingTexture.getSize().height;
  84873. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  84874. 0.5 / textureSize, // textureOffset
  84875. textureSize, // textureSize
  84876. this.colorGradingTexture.level // weight
  84877. );
  84878. }
  84879. };
  84880. /**
  84881. * Clones the current image processing instance.
  84882. * @return The cloned image processing
  84883. */
  84884. ImageProcessingConfiguration.prototype.clone = function () {
  84885. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  84886. };
  84887. /**
  84888. * Serializes the current image processing instance to a json representation.
  84889. * @return a JSON representation
  84890. */
  84891. ImageProcessingConfiguration.prototype.serialize = function () {
  84892. return BABYLON.SerializationHelper.Serialize(this);
  84893. };
  84894. /**
  84895. * Parses the image processing from a json representation.
  84896. * @param source the JSON source to parse
  84897. * @return The parsed image processing
  84898. */
  84899. ImageProcessingConfiguration.Parse = function (source) {
  84900. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  84901. };
  84902. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  84903. /**
  84904. * Used to apply the vignette as a mix with the pixel color.
  84905. */
  84906. get: function () {
  84907. return this._VIGNETTEMODE_MULTIPLY;
  84908. },
  84909. enumerable: true,
  84910. configurable: true
  84911. });
  84912. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  84913. /**
  84914. * Used to apply the vignette as a replacement of the pixel color.
  84915. */
  84916. get: function () {
  84917. return this._VIGNETTEMODE_OPAQUE;
  84918. },
  84919. enumerable: true,
  84920. configurable: true
  84921. });
  84922. /**
  84923. * Default tone mapping applied in BabylonJS.
  84924. */
  84925. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  84926. /**
  84927. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  84928. * to other engines rendering to increase portability.
  84929. */
  84930. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  84931. // Static constants associated to the image processing.
  84932. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  84933. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  84934. __decorate([
  84935. BABYLON.serializeAsColorCurves()
  84936. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  84937. __decorate([
  84938. BABYLON.serialize()
  84939. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  84940. __decorate([
  84941. BABYLON.serializeAsTexture()
  84942. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  84943. __decorate([
  84944. BABYLON.serialize()
  84945. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  84946. __decorate([
  84947. BABYLON.serialize()
  84948. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  84949. __decorate([
  84950. BABYLON.serialize()
  84951. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  84952. __decorate([
  84953. BABYLON.serialize()
  84954. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  84955. __decorate([
  84956. BABYLON.serialize()
  84957. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  84958. __decorate([
  84959. BABYLON.serialize()
  84960. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  84961. __decorate([
  84962. BABYLON.serialize()
  84963. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  84964. __decorate([
  84965. BABYLON.serialize()
  84966. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  84967. __decorate([
  84968. BABYLON.serialize()
  84969. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  84970. __decorate([
  84971. BABYLON.serialize()
  84972. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  84973. __decorate([
  84974. BABYLON.serialize()
  84975. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  84976. __decorate([
  84977. BABYLON.serializeAsColor4()
  84978. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  84979. __decorate([
  84980. BABYLON.serialize()
  84981. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  84982. __decorate([
  84983. BABYLON.serialize()
  84984. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  84985. __decorate([
  84986. BABYLON.serialize()
  84987. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  84988. __decorate([
  84989. BABYLON.serialize()
  84990. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  84991. __decorate([
  84992. BABYLON.serialize()
  84993. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  84994. return ImageProcessingConfiguration;
  84995. }());
  84996. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  84997. })(BABYLON || (BABYLON = {}));
  84998. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  84999. var BABYLON;
  85000. (function (BABYLON) {
  85001. /**
  85002. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  85003. * It can help converting any input color in a desired output one. This can then be used to create effects
  85004. * from sepia, black and white to sixties or futuristic rendering...
  85005. *
  85006. * The only supported format is currently 3dl.
  85007. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  85008. */
  85009. var ColorGradingTexture = /** @class */ (function (_super) {
  85010. __extends(ColorGradingTexture, _super);
  85011. /**
  85012. * Instantiates a ColorGradingTexture from the following parameters.
  85013. *
  85014. * @param url The location of the color gradind data (currently only supporting 3dl)
  85015. * @param scene The scene the texture will be used in
  85016. */
  85017. function ColorGradingTexture(url, scene) {
  85018. var _this = _super.call(this, scene) || this;
  85019. if (!url) {
  85020. return _this;
  85021. }
  85022. _this._engine = scene.getEngine();
  85023. _this._textureMatrix = BABYLON.Matrix.Identity();
  85024. _this.name = url;
  85025. _this.url = url;
  85026. _this.hasAlpha = false;
  85027. _this.isCube = false;
  85028. _this.is3D = _this._engine.webGLVersion > 1;
  85029. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85030. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85031. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85032. _this.anisotropicFilteringLevel = 1;
  85033. _this._texture = _this._getFromCache(url, true);
  85034. if (!_this._texture) {
  85035. if (!scene.useDelayedTextureLoading) {
  85036. _this.loadTexture();
  85037. }
  85038. else {
  85039. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  85040. }
  85041. }
  85042. return _this;
  85043. }
  85044. /**
  85045. * Returns the texture matrix used in most of the material.
  85046. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  85047. */
  85048. ColorGradingTexture.prototype.getTextureMatrix = function () {
  85049. return this._textureMatrix;
  85050. };
  85051. /**
  85052. * Occurs when the file being loaded is a .3dl LUT file.
  85053. */
  85054. ColorGradingTexture.prototype.load3dlTexture = function () {
  85055. var engine = this._engine;
  85056. var texture;
  85057. if (engine.webGLVersion === 1) {
  85058. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85059. }
  85060. else {
  85061. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85062. }
  85063. this._texture = texture;
  85064. var callback = function (text) {
  85065. if (typeof text !== "string") {
  85066. return;
  85067. }
  85068. var data = null;
  85069. var tempData = null;
  85070. var line;
  85071. var lines = text.split('\n');
  85072. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  85073. var maxColor = 0;
  85074. for (var i = 0; i < lines.length; i++) {
  85075. line = lines[i];
  85076. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  85077. continue;
  85078. if (line.indexOf('#') === 0)
  85079. continue;
  85080. var words = line.split(" ");
  85081. if (size === 0) {
  85082. // Number of space + one
  85083. size = words.length;
  85084. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  85085. tempData = new Float32Array(size * size * size * 4);
  85086. continue;
  85087. }
  85088. if (size != 0) {
  85089. var r = Math.max(parseInt(words[0]), 0);
  85090. var g = Math.max(parseInt(words[1]), 0);
  85091. var b = Math.max(parseInt(words[2]), 0);
  85092. maxColor = Math.max(r, maxColor);
  85093. maxColor = Math.max(g, maxColor);
  85094. maxColor = Math.max(b, maxColor);
  85095. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  85096. if (tempData) {
  85097. tempData[pixelStorageIndex + 0] = r;
  85098. tempData[pixelStorageIndex + 1] = g;
  85099. tempData[pixelStorageIndex + 2] = b;
  85100. }
  85101. pixelIndexSlice++;
  85102. if (pixelIndexSlice % size == 0) {
  85103. pixelIndexH++;
  85104. pixelIndexSlice = 0;
  85105. if (pixelIndexH % size == 0) {
  85106. pixelIndexW++;
  85107. pixelIndexH = 0;
  85108. }
  85109. }
  85110. }
  85111. }
  85112. if (tempData && data) {
  85113. for (var i = 0; i < tempData.length; i++) {
  85114. if (i > 0 && (i + 1) % 4 === 0) {
  85115. data[i] = 255;
  85116. }
  85117. else {
  85118. var value = tempData[i];
  85119. data[i] = (value / maxColor * 255);
  85120. }
  85121. }
  85122. }
  85123. if (texture.is3D) {
  85124. texture.updateSize(size, size, size);
  85125. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  85126. }
  85127. else {
  85128. texture.updateSize(size * size, size);
  85129. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  85130. }
  85131. };
  85132. var scene = this.getScene();
  85133. if (scene) {
  85134. scene._loadFile(this.url, callback);
  85135. }
  85136. else {
  85137. this._engine._loadFile(this.url, callback);
  85138. }
  85139. return this._texture;
  85140. };
  85141. /**
  85142. * Starts the loading process of the texture.
  85143. */
  85144. ColorGradingTexture.prototype.loadTexture = function () {
  85145. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  85146. this.load3dlTexture();
  85147. }
  85148. };
  85149. /**
  85150. * Clones the color gradind texture.
  85151. */
  85152. ColorGradingTexture.prototype.clone = function () {
  85153. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  85154. // Base texture
  85155. newTexture.level = this.level;
  85156. return newTexture;
  85157. };
  85158. /**
  85159. * Called during delayed load for textures.
  85160. */
  85161. ColorGradingTexture.prototype.delayLoad = function () {
  85162. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85163. return;
  85164. }
  85165. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85166. this._texture = this._getFromCache(this.url, true);
  85167. if (!this._texture) {
  85168. this.loadTexture();
  85169. }
  85170. };
  85171. /**
  85172. * Parses a color grading texture serialized by Babylon.
  85173. * @param parsedTexture The texture information being parsedTexture
  85174. * @param scene The scene to load the texture in
  85175. * @param rootUrl The root url of the data assets to load
  85176. * @return A color gradind texture
  85177. */
  85178. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85179. var texture = null;
  85180. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85181. texture = new ColorGradingTexture(parsedTexture.name, scene);
  85182. texture.name = parsedTexture.name;
  85183. texture.level = parsedTexture.level;
  85184. }
  85185. return texture;
  85186. };
  85187. /**
  85188. * Serializes the LUT texture to json format.
  85189. */
  85190. ColorGradingTexture.prototype.serialize = function () {
  85191. if (!this.name) {
  85192. return null;
  85193. }
  85194. var serializationObject = {};
  85195. serializationObject.name = this.name;
  85196. serializationObject.level = this.level;
  85197. serializationObject.customType = "BABYLON.ColorGradingTexture";
  85198. return serializationObject;
  85199. };
  85200. /**
  85201. * Empty line regex stored for GC.
  85202. */
  85203. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  85204. return ColorGradingTexture;
  85205. }(BABYLON.BaseTexture));
  85206. BABYLON.ColorGradingTexture = ColorGradingTexture;
  85207. })(BABYLON || (BABYLON = {}));
  85208. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  85209. var BABYLON;
  85210. (function (BABYLON) {
  85211. /**
  85212. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  85213. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  85214. * 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;
  85215. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  85216. */
  85217. var ColorCurves = /** @class */ (function () {
  85218. function ColorCurves() {
  85219. this._dirty = true;
  85220. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  85221. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  85222. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  85223. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  85224. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  85225. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  85226. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  85227. this._globalHue = 30;
  85228. this._globalDensity = 0;
  85229. this._globalSaturation = 0;
  85230. this._globalExposure = 0;
  85231. this._highlightsHue = 30;
  85232. this._highlightsDensity = 0;
  85233. this._highlightsSaturation = 0;
  85234. this._highlightsExposure = 0;
  85235. this._midtonesHue = 30;
  85236. this._midtonesDensity = 0;
  85237. this._midtonesSaturation = 0;
  85238. this._midtonesExposure = 0;
  85239. this._shadowsHue = 30;
  85240. this._shadowsDensity = 0;
  85241. this._shadowsSaturation = 0;
  85242. this._shadowsExposure = 0;
  85243. }
  85244. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  85245. /**
  85246. * Gets the global Hue value.
  85247. * 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).
  85248. */
  85249. get: function () {
  85250. return this._globalHue;
  85251. },
  85252. /**
  85253. * Sets the global Hue value.
  85254. * 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).
  85255. */
  85256. set: function (value) {
  85257. this._globalHue = value;
  85258. this._dirty = true;
  85259. },
  85260. enumerable: true,
  85261. configurable: true
  85262. });
  85263. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  85264. /**
  85265. * Gets the global Density value.
  85266. * 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.
  85267. * Values less than zero provide a filter of opposite hue.
  85268. */
  85269. get: function () {
  85270. return this._globalDensity;
  85271. },
  85272. /**
  85273. * Sets the global Density value.
  85274. * 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.
  85275. * Values less than zero provide a filter of opposite hue.
  85276. */
  85277. set: function (value) {
  85278. this._globalDensity = value;
  85279. this._dirty = true;
  85280. },
  85281. enumerable: true,
  85282. configurable: true
  85283. });
  85284. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  85285. /**
  85286. * Gets the global Saturation value.
  85287. * 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.
  85288. */
  85289. get: function () {
  85290. return this._globalSaturation;
  85291. },
  85292. /**
  85293. * Sets the global Saturation value.
  85294. * 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.
  85295. */
  85296. set: function (value) {
  85297. this._globalSaturation = value;
  85298. this._dirty = true;
  85299. },
  85300. enumerable: true,
  85301. configurable: true
  85302. });
  85303. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  85304. /**
  85305. * Gets the global Exposure value.
  85306. * 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.
  85307. */
  85308. get: function () {
  85309. return this._globalExposure;
  85310. },
  85311. /**
  85312. * Sets the global Exposure value.
  85313. * 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.
  85314. */
  85315. set: function (value) {
  85316. this._globalExposure = value;
  85317. this._dirty = true;
  85318. },
  85319. enumerable: true,
  85320. configurable: true
  85321. });
  85322. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  85323. /**
  85324. * Gets the highlights Hue value.
  85325. * 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).
  85326. */
  85327. get: function () {
  85328. return this._highlightsHue;
  85329. },
  85330. /**
  85331. * Sets the highlights Hue value.
  85332. * 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).
  85333. */
  85334. set: function (value) {
  85335. this._highlightsHue = value;
  85336. this._dirty = true;
  85337. },
  85338. enumerable: true,
  85339. configurable: true
  85340. });
  85341. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  85342. /**
  85343. * Gets the highlights Density value.
  85344. * 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.
  85345. * Values less than zero provide a filter of opposite hue.
  85346. */
  85347. get: function () {
  85348. return this._highlightsDensity;
  85349. },
  85350. /**
  85351. * Sets the highlights Density value.
  85352. * 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.
  85353. * Values less than zero provide a filter of opposite hue.
  85354. */
  85355. set: function (value) {
  85356. this._highlightsDensity = value;
  85357. this._dirty = true;
  85358. },
  85359. enumerable: true,
  85360. configurable: true
  85361. });
  85362. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  85363. /**
  85364. * Gets the highlights Saturation value.
  85365. * 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.
  85366. */
  85367. get: function () {
  85368. return this._highlightsSaturation;
  85369. },
  85370. /**
  85371. * Sets the highlights Saturation value.
  85372. * 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.
  85373. */
  85374. set: function (value) {
  85375. this._highlightsSaturation = value;
  85376. this._dirty = true;
  85377. },
  85378. enumerable: true,
  85379. configurable: true
  85380. });
  85381. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  85382. /**
  85383. * Gets the highlights Exposure value.
  85384. * 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.
  85385. */
  85386. get: function () {
  85387. return this._highlightsExposure;
  85388. },
  85389. /**
  85390. * Sets the highlights Exposure value.
  85391. * 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.
  85392. */
  85393. set: function (value) {
  85394. this._highlightsExposure = value;
  85395. this._dirty = true;
  85396. },
  85397. enumerable: true,
  85398. configurable: true
  85399. });
  85400. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  85401. /**
  85402. * Gets the midtones Hue value.
  85403. * 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).
  85404. */
  85405. get: function () {
  85406. return this._midtonesHue;
  85407. },
  85408. /**
  85409. * Sets the midtones Hue value.
  85410. * 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).
  85411. */
  85412. set: function (value) {
  85413. this._midtonesHue = value;
  85414. this._dirty = true;
  85415. },
  85416. enumerable: true,
  85417. configurable: true
  85418. });
  85419. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  85420. /**
  85421. * Gets the midtones Density value.
  85422. * 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.
  85423. * Values less than zero provide a filter of opposite hue.
  85424. */
  85425. get: function () {
  85426. return this._midtonesDensity;
  85427. },
  85428. /**
  85429. * Sets the midtones Density value.
  85430. * 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.
  85431. * Values less than zero provide a filter of opposite hue.
  85432. */
  85433. set: function (value) {
  85434. this._midtonesDensity = value;
  85435. this._dirty = true;
  85436. },
  85437. enumerable: true,
  85438. configurable: true
  85439. });
  85440. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  85441. /**
  85442. * Gets the midtones Saturation value.
  85443. * 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.
  85444. */
  85445. get: function () {
  85446. return this._midtonesSaturation;
  85447. },
  85448. /**
  85449. * Sets the midtones Saturation value.
  85450. * 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.
  85451. */
  85452. set: function (value) {
  85453. this._midtonesSaturation = value;
  85454. this._dirty = true;
  85455. },
  85456. enumerable: true,
  85457. configurable: true
  85458. });
  85459. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  85460. /**
  85461. * Gets the midtones Exposure value.
  85462. * 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.
  85463. */
  85464. get: function () {
  85465. return this._midtonesExposure;
  85466. },
  85467. /**
  85468. * Sets the midtones Exposure value.
  85469. * 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.
  85470. */
  85471. set: function (value) {
  85472. this._midtonesExposure = value;
  85473. this._dirty = true;
  85474. },
  85475. enumerable: true,
  85476. configurable: true
  85477. });
  85478. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  85479. /**
  85480. * Gets the shadows Hue value.
  85481. * 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).
  85482. */
  85483. get: function () {
  85484. return this._shadowsHue;
  85485. },
  85486. /**
  85487. * Sets the shadows Hue value.
  85488. * 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).
  85489. */
  85490. set: function (value) {
  85491. this._shadowsHue = value;
  85492. this._dirty = true;
  85493. },
  85494. enumerable: true,
  85495. configurable: true
  85496. });
  85497. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  85498. /**
  85499. * Gets the shadows Density value.
  85500. * 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.
  85501. * Values less than zero provide a filter of opposite hue.
  85502. */
  85503. get: function () {
  85504. return this._shadowsDensity;
  85505. },
  85506. /**
  85507. * Sets the shadows Density value.
  85508. * 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.
  85509. * Values less than zero provide a filter of opposite hue.
  85510. */
  85511. set: function (value) {
  85512. this._shadowsDensity = value;
  85513. this._dirty = true;
  85514. },
  85515. enumerable: true,
  85516. configurable: true
  85517. });
  85518. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  85519. /**
  85520. * Gets the shadows Saturation value.
  85521. * 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.
  85522. */
  85523. get: function () {
  85524. return this._shadowsSaturation;
  85525. },
  85526. /**
  85527. * Sets the shadows Saturation value.
  85528. * 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.
  85529. */
  85530. set: function (value) {
  85531. this._shadowsSaturation = value;
  85532. this._dirty = true;
  85533. },
  85534. enumerable: true,
  85535. configurable: true
  85536. });
  85537. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  85538. /**
  85539. * Gets the shadows Exposure value.
  85540. * 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.
  85541. */
  85542. get: function () {
  85543. return this._shadowsExposure;
  85544. },
  85545. /**
  85546. * Sets the shadows Exposure value.
  85547. * 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.
  85548. */
  85549. set: function (value) {
  85550. this._shadowsExposure = value;
  85551. this._dirty = true;
  85552. },
  85553. enumerable: true,
  85554. configurable: true
  85555. });
  85556. ColorCurves.prototype.getClassName = function () {
  85557. return "ColorCurves";
  85558. };
  85559. /**
  85560. * Binds the color curves to the shader.
  85561. * @param colorCurves The color curve to bind
  85562. * @param effect The effect to bind to
  85563. */
  85564. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  85565. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  85566. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  85567. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  85568. if (colorCurves._dirty) {
  85569. colorCurves._dirty = false;
  85570. // Fill in global info.
  85571. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  85572. // Compute highlights info.
  85573. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  85574. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  85575. // Compute midtones info.
  85576. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  85577. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  85578. // Compute shadows info.
  85579. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  85580. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  85581. // Compute deltas (neutral is midtones).
  85582. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  85583. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  85584. }
  85585. if (effect) {
  85586. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  85587. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  85588. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  85589. }
  85590. };
  85591. /**
  85592. * Prepare the list of uniforms associated with the ColorCurves effects.
  85593. * @param uniformsList The list of uniforms used in the effect
  85594. */
  85595. ColorCurves.PrepareUniforms = function (uniformsList) {
  85596. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  85597. };
  85598. /**
  85599. * Returns color grading data based on a hue, density, saturation and exposure value.
  85600. * @param filterHue The hue of the color filter.
  85601. * @param filterDensity The density of the color filter.
  85602. * @param saturation The saturation.
  85603. * @param exposure The exposure.
  85604. * @param result The result data container.
  85605. */
  85606. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  85607. if (hue == null) {
  85608. return;
  85609. }
  85610. hue = ColorCurves.clamp(hue, 0, 360);
  85611. density = ColorCurves.clamp(density, -100, 100);
  85612. saturation = ColorCurves.clamp(saturation, -100, 100);
  85613. exposure = ColorCurves.clamp(exposure, -100, 100);
  85614. // Remap the slider/config filter density with non-linear mapping and also scale by half
  85615. // so that the maximum filter density is only 50% control. This provides fine control
  85616. // for small values and reasonable range.
  85617. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  85618. density *= 0.5;
  85619. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  85620. if (density < 0) {
  85621. density *= -1;
  85622. hue = (hue + 180) % 360;
  85623. }
  85624. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  85625. result.scaleToRef(2, result);
  85626. result.a = 1 + 0.01 * saturation;
  85627. };
  85628. /**
  85629. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  85630. * @param value The input slider value in range [-100,100].
  85631. * @returns Adjusted value.
  85632. */
  85633. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  85634. value /= 100;
  85635. var x = Math.abs(value);
  85636. x = Math.pow(x, 2);
  85637. if (value < 0) {
  85638. x *= -1;
  85639. }
  85640. x *= 100;
  85641. return x;
  85642. };
  85643. /**
  85644. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  85645. * @param hue The hue (H) input.
  85646. * @param saturation The saturation (S) input.
  85647. * @param brightness The brightness (B) input.
  85648. * @result An RGBA color represented as Vector4.
  85649. */
  85650. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  85651. var h = ColorCurves.clamp(hue, 0, 360);
  85652. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  85653. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  85654. if (s === 0) {
  85655. result.r = v;
  85656. result.g = v;
  85657. result.b = v;
  85658. }
  85659. else {
  85660. // sector 0 to 5
  85661. h /= 60;
  85662. var i = Math.floor(h);
  85663. // fractional part of h
  85664. var f = h - i;
  85665. var p = v * (1 - s);
  85666. var q = v * (1 - s * f);
  85667. var t = v * (1 - s * (1 - f));
  85668. switch (i) {
  85669. case 0:
  85670. result.r = v;
  85671. result.g = t;
  85672. result.b = p;
  85673. break;
  85674. case 1:
  85675. result.r = q;
  85676. result.g = v;
  85677. result.b = p;
  85678. break;
  85679. case 2:
  85680. result.r = p;
  85681. result.g = v;
  85682. result.b = t;
  85683. break;
  85684. case 3:
  85685. result.r = p;
  85686. result.g = q;
  85687. result.b = v;
  85688. break;
  85689. case 4:
  85690. result.r = t;
  85691. result.g = p;
  85692. result.b = v;
  85693. break;
  85694. default: // case 5:
  85695. result.r = v;
  85696. result.g = p;
  85697. result.b = q;
  85698. break;
  85699. }
  85700. }
  85701. result.a = 1;
  85702. };
  85703. /**
  85704. * Returns a value clamped between min and max
  85705. * @param value The value to clamp
  85706. * @param min The minimum of value
  85707. * @param max The maximum of value
  85708. * @returns The clamped value.
  85709. */
  85710. ColorCurves.clamp = function (value, min, max) {
  85711. return Math.min(Math.max(value, min), max);
  85712. };
  85713. /**
  85714. * Clones the current color curve instance.
  85715. * @return The cloned curves
  85716. */
  85717. ColorCurves.prototype.clone = function () {
  85718. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  85719. };
  85720. /**
  85721. * Serializes the current color curve instance to a json representation.
  85722. * @return a JSON representation
  85723. */
  85724. ColorCurves.prototype.serialize = function () {
  85725. return BABYLON.SerializationHelper.Serialize(this);
  85726. };
  85727. /**
  85728. * Parses the color curve from a json representation.
  85729. * @param source the JSON source to parse
  85730. * @return The parsed curves
  85731. */
  85732. ColorCurves.Parse = function (source) {
  85733. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  85734. };
  85735. __decorate([
  85736. BABYLON.serialize()
  85737. ], ColorCurves.prototype, "_globalHue", void 0);
  85738. __decorate([
  85739. BABYLON.serialize()
  85740. ], ColorCurves.prototype, "_globalDensity", void 0);
  85741. __decorate([
  85742. BABYLON.serialize()
  85743. ], ColorCurves.prototype, "_globalSaturation", void 0);
  85744. __decorate([
  85745. BABYLON.serialize()
  85746. ], ColorCurves.prototype, "_globalExposure", void 0);
  85747. __decorate([
  85748. BABYLON.serialize()
  85749. ], ColorCurves.prototype, "_highlightsHue", void 0);
  85750. __decorate([
  85751. BABYLON.serialize()
  85752. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  85753. __decorate([
  85754. BABYLON.serialize()
  85755. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  85756. __decorate([
  85757. BABYLON.serialize()
  85758. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  85759. __decorate([
  85760. BABYLON.serialize()
  85761. ], ColorCurves.prototype, "_midtonesHue", void 0);
  85762. __decorate([
  85763. BABYLON.serialize()
  85764. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  85765. __decorate([
  85766. BABYLON.serialize()
  85767. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  85768. __decorate([
  85769. BABYLON.serialize()
  85770. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  85771. return ColorCurves;
  85772. }());
  85773. BABYLON.ColorCurves = ColorCurves;
  85774. })(BABYLON || (BABYLON = {}));
  85775. //# sourceMappingURL=babylon.colorCurves.js.map
  85776. var BABYLON;
  85777. (function (BABYLON) {
  85778. var RefractionPostProcess = /** @class */ (function (_super) {
  85779. __extends(RefractionPostProcess, _super);
  85780. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  85781. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  85782. _this.color = color;
  85783. _this.depth = depth;
  85784. _this.colorLevel = colorLevel;
  85785. _this._ownRefractionTexture = true;
  85786. _this.onActivateObservable.add(function (cam) {
  85787. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  85788. });
  85789. _this.onApplyObservable.add(function (effect) {
  85790. effect.setColor3("baseColor", _this.color);
  85791. effect.setFloat("depth", _this.depth);
  85792. effect.setFloat("colorLevel", _this.colorLevel);
  85793. effect.setTexture("refractionSampler", _this._refTexture);
  85794. });
  85795. return _this;
  85796. }
  85797. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  85798. /**
  85799. * Gets or sets the refraction texture
  85800. * Please note that you are responsible for disposing the texture if you set it manually
  85801. */
  85802. get: function () {
  85803. return this._refTexture;
  85804. },
  85805. set: function (value) {
  85806. if (this._refTexture && this._ownRefractionTexture) {
  85807. this._refTexture.dispose();
  85808. }
  85809. this._refTexture = value;
  85810. this._ownRefractionTexture = false;
  85811. },
  85812. enumerable: true,
  85813. configurable: true
  85814. });
  85815. // Methods
  85816. RefractionPostProcess.prototype.dispose = function (camera) {
  85817. if (this._refTexture && this._ownRefractionTexture) {
  85818. this._refTexture.dispose();
  85819. this._refTexture = null;
  85820. }
  85821. _super.prototype.dispose.call(this, camera);
  85822. };
  85823. return RefractionPostProcess;
  85824. }(BABYLON.PostProcess));
  85825. BABYLON.RefractionPostProcess = RefractionPostProcess;
  85826. })(BABYLON || (BABYLON = {}));
  85827. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  85828. var BABYLON;
  85829. (function (BABYLON) {
  85830. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  85831. __extends(BlackAndWhitePostProcess, _super);
  85832. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  85833. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  85834. _this.degree = 1;
  85835. _this.onApplyObservable.add(function (effect) {
  85836. effect.setFloat("degree", _this.degree);
  85837. });
  85838. return _this;
  85839. }
  85840. return BlackAndWhitePostProcess;
  85841. }(BABYLON.PostProcess));
  85842. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  85843. })(BABYLON || (BABYLON = {}));
  85844. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  85845. var BABYLON;
  85846. (function (BABYLON) {
  85847. /**
  85848. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  85849. * input texture to perform effects such as edge detection or sharpening
  85850. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  85851. */
  85852. var ConvolutionPostProcess = /** @class */ (function (_super) {
  85853. __extends(ConvolutionPostProcess, _super);
  85854. /**
  85855. * Creates a new instance ConvolutionPostProcess
  85856. * @param name The name of the effect.
  85857. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  85858. * @param options The required width/height ratio to downsize to before computing the render pass.
  85859. * @param camera The camera to apply the render pass to.
  85860. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85861. * @param engine The engine which the post process will be applied. (default: current engine)
  85862. * @param reusable If the post process can be reused on the same frame. (default: false)
  85863. * @param textureType Type of textures used when performing the post process. (default: 0)
  85864. */
  85865. function ConvolutionPostProcess(name,
  85866. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  85867. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  85868. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85869. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  85870. _this.kernel = kernel;
  85871. _this.onApply = function (effect) {
  85872. effect.setFloat2("screenSize", _this.width, _this.height);
  85873. effect.setArray("kernel", _this.kernel);
  85874. };
  85875. return _this;
  85876. }
  85877. // Statics
  85878. /**
  85879. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85880. */
  85881. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  85882. /**
  85883. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85884. */
  85885. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  85886. /**
  85887. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85888. */
  85889. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  85890. /**
  85891. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85892. */
  85893. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  85894. /**
  85895. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85896. */
  85897. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  85898. /**
  85899. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85900. */
  85901. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  85902. return ConvolutionPostProcess;
  85903. }(BABYLON.PostProcess));
  85904. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  85905. })(BABYLON || (BABYLON = {}));
  85906. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  85907. var BABYLON;
  85908. (function (BABYLON) {
  85909. var FilterPostProcess = /** @class */ (function (_super) {
  85910. __extends(FilterPostProcess, _super);
  85911. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  85912. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  85913. _this.kernelMatrix = kernelMatrix;
  85914. _this.onApply = function (effect) {
  85915. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  85916. };
  85917. return _this;
  85918. }
  85919. return FilterPostProcess;
  85920. }(BABYLON.PostProcess));
  85921. BABYLON.FilterPostProcess = FilterPostProcess;
  85922. })(BABYLON || (BABYLON = {}));
  85923. //# sourceMappingURL=babylon.filterPostProcess.js.map
  85924. var BABYLON;
  85925. (function (BABYLON) {
  85926. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  85927. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  85928. __extends(VolumetricLightScatteringPostProcess, _super);
  85929. /**
  85930. * @constructor
  85931. * @param {string} name - The post-process name
  85932. * @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)
  85933. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  85934. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  85935. * @param {number} samples - The post-process quality, default 100
  85936. * @param {number} samplingMode - The post-process filtering mode
  85937. * @param {BABYLON.Engine} engine - The babylon engine
  85938. * @param {boolean} reusable - If the post-process is reusable
  85939. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  85940. */
  85941. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  85942. if (samples === void 0) { samples = 100; }
  85943. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85944. 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;
  85945. _this._screenCoordinates = BABYLON.Vector2.Zero();
  85946. /**
  85947. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  85948. */
  85949. _this.customMeshPosition = BABYLON.Vector3.Zero();
  85950. /**
  85951. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  85952. */
  85953. _this.useCustomMeshPosition = false;
  85954. /**
  85955. * If the post-process should inverse the light scattering direction
  85956. */
  85957. _this.invert = true;
  85958. /**
  85959. * Array containing the excluded meshes not rendered in the internal pass
  85960. */
  85961. _this.excludedMeshes = new Array();
  85962. /**
  85963. * Controls the overall intensity of the post-process
  85964. */
  85965. _this.exposure = 0.3;
  85966. /**
  85967. * Dissipates each sample's contribution in range [0, 1]
  85968. */
  85969. _this.decay = 0.96815;
  85970. /**
  85971. * Controls the overall intensity of each sample
  85972. */
  85973. _this.weight = 0.58767;
  85974. /**
  85975. * Controls the density of each sample
  85976. */
  85977. _this.density = 0.926;
  85978. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  85979. engine = scene.getEngine();
  85980. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  85981. // Configure mesh
  85982. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  85983. // Configure
  85984. _this._createPass(scene, ratio.passRatio || ratio);
  85985. _this.onActivate = function (camera) {
  85986. if (!_this.isSupported) {
  85987. _this.dispose(camera);
  85988. }
  85989. _this.onActivate = null;
  85990. };
  85991. _this.onApplyObservable.add(function (effect) {
  85992. _this._updateMeshScreenCoordinates(scene);
  85993. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  85994. effect.setFloat("exposure", _this.exposure);
  85995. effect.setFloat("decay", _this.decay);
  85996. effect.setFloat("weight", _this.weight);
  85997. effect.setFloat("density", _this.density);
  85998. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  85999. });
  86000. return _this;
  86001. }
  86002. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  86003. get: function () {
  86004. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  86005. return false;
  86006. },
  86007. set: function (useDiffuseColor) {
  86008. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  86009. },
  86010. enumerable: true,
  86011. configurable: true
  86012. });
  86013. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  86014. return "VolumetricLightScatteringPostProcess";
  86015. };
  86016. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  86017. var mesh = subMesh.getMesh();
  86018. // Render this.mesh as default
  86019. if (mesh === this.mesh && mesh.material) {
  86020. return mesh.material.isReady(mesh);
  86021. }
  86022. var defines = [];
  86023. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86024. var material = subMesh.getMaterial();
  86025. // Alpha test
  86026. if (material) {
  86027. if (material.needAlphaTesting()) {
  86028. defines.push("#define ALPHATEST");
  86029. }
  86030. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86031. attribs.push(BABYLON.VertexBuffer.UVKind);
  86032. defines.push("#define UV1");
  86033. }
  86034. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86035. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86036. defines.push("#define UV2");
  86037. }
  86038. }
  86039. // Bones
  86040. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86041. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86042. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86043. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86044. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86045. }
  86046. else {
  86047. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86048. }
  86049. // Instances
  86050. if (useInstances) {
  86051. defines.push("#define INSTANCES");
  86052. attribs.push("world0");
  86053. attribs.push("world1");
  86054. attribs.push("world2");
  86055. attribs.push("world3");
  86056. }
  86057. // Get correct effect
  86058. var join = defines.join("\n");
  86059. if (this._cachedDefines !== join) {
  86060. this._cachedDefines = join;
  86061. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  86062. }
  86063. return this._volumetricLightScatteringPass.isReady();
  86064. };
  86065. /**
  86066. * Sets the new light position for light scattering effect
  86067. * @param {BABYLON.Vector3} The new custom light position
  86068. */
  86069. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  86070. this.customMeshPosition = position;
  86071. };
  86072. /**
  86073. * Returns the light position for light scattering effect
  86074. * @return {BABYLON.Vector3} The custom light position
  86075. */
  86076. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  86077. return this.customMeshPosition;
  86078. };
  86079. /**
  86080. * Disposes the internal assets and detaches the post-process from the camera
  86081. */
  86082. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  86083. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  86084. if (rttIndex !== -1) {
  86085. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  86086. }
  86087. this._volumetricLightScatteringRTT.dispose();
  86088. _super.prototype.dispose.call(this, camera);
  86089. };
  86090. /**
  86091. * Returns the render target texture used by the post-process
  86092. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  86093. */
  86094. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  86095. return this._volumetricLightScatteringRTT;
  86096. };
  86097. // Private methods
  86098. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  86099. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  86100. return true;
  86101. }
  86102. return false;
  86103. };
  86104. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  86105. var _this = this;
  86106. var engine = scene.getEngine();
  86107. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86108. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86109. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86110. this._volumetricLightScatteringRTT.renderList = null;
  86111. this._volumetricLightScatteringRTT.renderParticles = false;
  86112. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  86113. var camera = this.getCamera();
  86114. if (camera) {
  86115. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  86116. }
  86117. else {
  86118. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  86119. }
  86120. // Custom render function for submeshes
  86121. var renderSubMesh = function (subMesh) {
  86122. var mesh = subMesh.getRenderingMesh();
  86123. if (_this._meshExcluded(mesh)) {
  86124. return;
  86125. }
  86126. var material = subMesh.getMaterial();
  86127. if (!material) {
  86128. return;
  86129. }
  86130. var scene = mesh.getScene();
  86131. var engine = scene.getEngine();
  86132. // Culling
  86133. engine.setState(material.backFaceCulling);
  86134. // Managing instances
  86135. var batch = mesh._getInstancesRenderList(subMesh._id);
  86136. if (batch.mustReturn) {
  86137. return;
  86138. }
  86139. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  86140. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  86141. var effect = _this._volumetricLightScatteringPass;
  86142. if (mesh === _this.mesh) {
  86143. if (subMesh.effect) {
  86144. effect = subMesh.effect;
  86145. }
  86146. else {
  86147. effect = material.getEffect();
  86148. }
  86149. }
  86150. engine.enableEffect(effect);
  86151. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  86152. if (mesh === _this.mesh) {
  86153. material.bind(mesh.getWorldMatrix(), mesh);
  86154. }
  86155. else {
  86156. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  86157. // Alpha test
  86158. if (material && material.needAlphaTesting()) {
  86159. var alphaTexture = material.getAlphaTestTexture();
  86160. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  86161. if (alphaTexture) {
  86162. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86163. }
  86164. }
  86165. // Bones
  86166. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86167. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86168. }
  86169. }
  86170. // Draw
  86171. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  86172. }
  86173. };
  86174. // Render target texture callbacks
  86175. var savedSceneClearColor;
  86176. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  86177. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  86178. savedSceneClearColor = scene.clearColor;
  86179. scene.clearColor = sceneClearColor;
  86180. });
  86181. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  86182. scene.clearColor = savedSceneClearColor;
  86183. });
  86184. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86185. var engine = scene.getEngine();
  86186. var index;
  86187. if (depthOnlySubMeshes.length) {
  86188. engine.setColorWrite(false);
  86189. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86190. renderSubMesh(depthOnlySubMeshes.data[index]);
  86191. }
  86192. engine.setColorWrite(true);
  86193. }
  86194. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86195. renderSubMesh(opaqueSubMeshes.data[index]);
  86196. }
  86197. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86198. renderSubMesh(alphaTestSubMeshes.data[index]);
  86199. }
  86200. if (transparentSubMeshes.length) {
  86201. // Sort sub meshes
  86202. for (index = 0; index < transparentSubMeshes.length; index++) {
  86203. var submesh = transparentSubMeshes.data[index];
  86204. var boundingInfo = submesh.getBoundingInfo();
  86205. if (boundingInfo && scene.activeCamera) {
  86206. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  86207. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  86208. }
  86209. }
  86210. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  86211. sortedArray.sort(function (a, b) {
  86212. // Alpha index first
  86213. if (a._alphaIndex > b._alphaIndex) {
  86214. return 1;
  86215. }
  86216. if (a._alphaIndex < b._alphaIndex) {
  86217. return -1;
  86218. }
  86219. // Then distance to camera
  86220. if (a._distanceToCamera < b._distanceToCamera) {
  86221. return 1;
  86222. }
  86223. if (a._distanceToCamera > b._distanceToCamera) {
  86224. return -1;
  86225. }
  86226. return 0;
  86227. });
  86228. // Render sub meshes
  86229. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  86230. for (index = 0; index < sortedArray.length; index++) {
  86231. renderSubMesh(sortedArray[index]);
  86232. }
  86233. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86234. }
  86235. };
  86236. };
  86237. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  86238. var transform = scene.getTransformMatrix();
  86239. var meshPosition;
  86240. if (this.useCustomMeshPosition) {
  86241. meshPosition = this.customMeshPosition;
  86242. }
  86243. else if (this.attachedNode) {
  86244. meshPosition = this.attachedNode.position;
  86245. }
  86246. else {
  86247. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  86248. }
  86249. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  86250. this._screenCoordinates.x = pos.x / this._viewPort.width;
  86251. this._screenCoordinates.y = pos.y / this._viewPort.height;
  86252. if (this.invert)
  86253. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  86254. };
  86255. // Static methods
  86256. /**
  86257. * Creates a default mesh for the Volumeric Light Scattering post-process
  86258. * @param {string} The mesh name
  86259. * @param {BABYLON.Scene} The scene where to create the mesh
  86260. * @return {BABYLON.Mesh} the default mesh
  86261. */
  86262. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  86263. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  86264. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  86265. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  86266. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  86267. mesh.material = material;
  86268. return mesh;
  86269. };
  86270. __decorate([
  86271. BABYLON.serializeAsVector3()
  86272. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  86273. __decorate([
  86274. BABYLON.serialize()
  86275. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  86276. __decorate([
  86277. BABYLON.serialize()
  86278. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  86279. __decorate([
  86280. BABYLON.serializeAsMeshReference()
  86281. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  86282. __decorate([
  86283. BABYLON.serialize()
  86284. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  86285. __decorate([
  86286. BABYLON.serialize()
  86287. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  86288. __decorate([
  86289. BABYLON.serialize()
  86290. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  86291. __decorate([
  86292. BABYLON.serialize()
  86293. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  86294. __decorate([
  86295. BABYLON.serialize()
  86296. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  86297. return VolumetricLightScatteringPostProcess;
  86298. }(BABYLON.PostProcess));
  86299. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  86300. })(BABYLON || (BABYLON = {}));
  86301. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  86302. //
  86303. // This post-process allows the modification of rendered colors by using
  86304. // a 'look-up table' (LUT). This effect is also called Color Grading.
  86305. //
  86306. // The object needs to be provided an url to a texture containing the color
  86307. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  86308. // Use an image editing software to tweak the LUT to match your needs.
  86309. //
  86310. // For an example of a color LUT, see here:
  86311. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  86312. // For explanations on color grading, see here:
  86313. // http://udn.epicgames.com/Three/ColorGrading.html
  86314. //
  86315. var BABYLON;
  86316. (function (BABYLON) {
  86317. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  86318. __extends(ColorCorrectionPostProcess, _super);
  86319. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  86320. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  86321. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86322. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  86323. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86324. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86325. _this.onApply = function (effect) {
  86326. effect.setTexture("colorTable", _this._colorTableTexture);
  86327. };
  86328. return _this;
  86329. }
  86330. return ColorCorrectionPostProcess;
  86331. }(BABYLON.PostProcess));
  86332. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  86333. })(BABYLON || (BABYLON = {}));
  86334. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  86335. var BABYLON;
  86336. (function (BABYLON) {
  86337. /** Defines operator used for tonemapping */
  86338. var TonemappingOperator;
  86339. (function (TonemappingOperator) {
  86340. /** Hable */
  86341. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  86342. /** Reinhard */
  86343. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  86344. /** HejiDawson */
  86345. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  86346. /** Photographic */
  86347. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  86348. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  86349. ;
  86350. /**
  86351. * Defines a post process to apply tone mapping
  86352. */
  86353. var TonemapPostProcess = /** @class */ (function (_super) {
  86354. __extends(TonemapPostProcess, _super);
  86355. /**
  86356. * Creates a new TonemapPostProcess
  86357. * @param name defines the name of the postprocess
  86358. * @param _operator defines the operator to use
  86359. * @param exposureAdjustment defines the required exposure adjustement
  86360. * @param camera defines the camera to use (can be null)
  86361. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  86362. * @param engine defines the hosting engine (can be ignore if camera is set)
  86363. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  86364. */
  86365. function TonemapPostProcess(name, _operator,
  86366. /** Defines the required exposure adjustement */
  86367. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  86368. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86369. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86370. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  86371. _this._operator = _operator;
  86372. _this.exposureAdjustment = exposureAdjustment;
  86373. var defines = "#define ";
  86374. if (_this._operator === TonemappingOperator.Hable)
  86375. defines += "HABLE_TONEMAPPING";
  86376. else if (_this._operator === TonemappingOperator.Reinhard)
  86377. defines += "REINHARD_TONEMAPPING";
  86378. else if (_this._operator === TonemappingOperator.HejiDawson)
  86379. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  86380. else if (_this._operator === TonemappingOperator.Photographic)
  86381. defines += "PHOTOGRAPHIC_TONEMAPPING";
  86382. //sadly a second call to create the effect.
  86383. _this.updateEffect(defines);
  86384. _this.onApply = function (effect) {
  86385. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  86386. };
  86387. return _this;
  86388. }
  86389. return TonemapPostProcess;
  86390. }(BABYLON.PostProcess));
  86391. BABYLON.TonemapPostProcess = TonemapPostProcess;
  86392. })(BABYLON || (BABYLON = {}));
  86393. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  86394. var BABYLON;
  86395. (function (BABYLON) {
  86396. var DisplayPassPostProcess = /** @class */ (function (_super) {
  86397. __extends(DisplayPassPostProcess, _super);
  86398. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  86399. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  86400. }
  86401. return DisplayPassPostProcess;
  86402. }(BABYLON.PostProcess));
  86403. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  86404. })(BABYLON || (BABYLON = {}));
  86405. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  86406. var BABYLON;
  86407. (function (BABYLON) {
  86408. var HighlightsPostProcess = /** @class */ (function (_super) {
  86409. __extends(HighlightsPostProcess, _super);
  86410. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  86411. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86412. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  86413. }
  86414. return HighlightsPostProcess;
  86415. }(BABYLON.PostProcess));
  86416. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  86417. })(BABYLON || (BABYLON = {}));
  86418. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  86419. var BABYLON;
  86420. (function (BABYLON) {
  86421. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  86422. __extends(ImageProcessingPostProcess, _super);
  86423. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  86424. if (camera === void 0) { camera = null; }
  86425. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86426. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  86427. _this._fromLinearSpace = true;
  86428. /**
  86429. * Defines cache preventing GC.
  86430. */
  86431. _this._defines = {
  86432. IMAGEPROCESSING: false,
  86433. VIGNETTE: false,
  86434. VIGNETTEBLENDMODEMULTIPLY: false,
  86435. VIGNETTEBLENDMODEOPAQUE: false,
  86436. TONEMAPPING: false,
  86437. TONEMAPPING_ACES: false,
  86438. CONTRAST: false,
  86439. COLORCURVES: false,
  86440. COLORGRADING: false,
  86441. COLORGRADING3D: false,
  86442. FROMLINEARSPACE: false,
  86443. SAMPLER3DGREENDEPTH: false,
  86444. SAMPLER3DBGRMAP: false,
  86445. IMAGEPROCESSINGPOSTPROCESS: false,
  86446. EXPOSURE: false,
  86447. };
  86448. // Setup the configuration as forced by the constructor. This would then not force the
  86449. // scene materials output in linear space and let untouched the default forward pass.
  86450. if (imageProcessingConfiguration) {
  86451. imageProcessingConfiguration.applyByPostProcess = true;
  86452. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  86453. // This will cause the shader to be compiled
  86454. _this.fromLinearSpace = false;
  86455. }
  86456. // Setup the default processing configuration to the scene.
  86457. else {
  86458. _this._attachImageProcessingConfiguration(null, true);
  86459. _this.imageProcessingConfiguration.applyByPostProcess = true;
  86460. }
  86461. _this.onApply = function (effect) {
  86462. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  86463. };
  86464. return _this;
  86465. }
  86466. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  86467. /**
  86468. * Gets the image processing configuration used either in this material.
  86469. */
  86470. get: function () {
  86471. return this._imageProcessingConfiguration;
  86472. },
  86473. /**
  86474. * Sets the Default image processing configuration used either in the this material.
  86475. *
  86476. * If sets to null, the scene one is in use.
  86477. */
  86478. set: function (value) {
  86479. this._attachImageProcessingConfiguration(value);
  86480. },
  86481. enumerable: true,
  86482. configurable: true
  86483. });
  86484. /**
  86485. * Attaches a new image processing configuration to the PBR Material.
  86486. * @param configuration
  86487. */
  86488. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  86489. var _this = this;
  86490. if (doNotBuild === void 0) { doNotBuild = false; }
  86491. if (configuration === this._imageProcessingConfiguration) {
  86492. return;
  86493. }
  86494. // Detaches observer.
  86495. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86496. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86497. }
  86498. // Pick the scene configuration if needed.
  86499. if (!configuration) {
  86500. var scene = null;
  86501. var engine = this.getEngine();
  86502. var camera = this.getCamera();
  86503. if (camera) {
  86504. scene = camera.getScene();
  86505. }
  86506. else if (engine && engine.scenes) {
  86507. var scenes = engine.scenes;
  86508. scene = scenes[scenes.length - 1];
  86509. }
  86510. else {
  86511. scene = BABYLON.Engine.LastCreatedScene;
  86512. }
  86513. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  86514. }
  86515. else {
  86516. this._imageProcessingConfiguration = configuration;
  86517. }
  86518. // Attaches observer.
  86519. if (this._imageProcessingConfiguration) {
  86520. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86521. _this._updateParameters();
  86522. });
  86523. }
  86524. // Ensure the effect will be rebuilt.
  86525. if (!doNotBuild) {
  86526. this._updateParameters();
  86527. }
  86528. };
  86529. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  86530. /**
  86531. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86532. */
  86533. get: function () {
  86534. return this.imageProcessingConfiguration.colorCurves;
  86535. },
  86536. /**
  86537. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86538. */
  86539. set: function (value) {
  86540. this.imageProcessingConfiguration.colorCurves = value;
  86541. },
  86542. enumerable: true,
  86543. configurable: true
  86544. });
  86545. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  86546. /**
  86547. * Gets wether the color curves effect is enabled.
  86548. */
  86549. get: function () {
  86550. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86551. },
  86552. /**
  86553. * Sets wether the color curves effect is enabled.
  86554. */
  86555. set: function (value) {
  86556. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86557. },
  86558. enumerable: true,
  86559. configurable: true
  86560. });
  86561. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  86562. /**
  86563. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86564. */
  86565. get: function () {
  86566. return this.imageProcessingConfiguration.colorGradingTexture;
  86567. },
  86568. /**
  86569. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86570. */
  86571. set: function (value) {
  86572. this.imageProcessingConfiguration.colorGradingTexture = value;
  86573. },
  86574. enumerable: true,
  86575. configurable: true
  86576. });
  86577. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  86578. /**
  86579. * Gets wether the color grading effect is enabled.
  86580. */
  86581. get: function () {
  86582. return this.imageProcessingConfiguration.colorGradingEnabled;
  86583. },
  86584. /**
  86585. * Gets wether the color grading effect is enabled.
  86586. */
  86587. set: function (value) {
  86588. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86589. },
  86590. enumerable: true,
  86591. configurable: true
  86592. });
  86593. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  86594. /**
  86595. * Gets exposure used in the effect.
  86596. */
  86597. get: function () {
  86598. return this.imageProcessingConfiguration.exposure;
  86599. },
  86600. /**
  86601. * Sets exposure used in the effect.
  86602. */
  86603. set: function (value) {
  86604. this.imageProcessingConfiguration.exposure = value;
  86605. },
  86606. enumerable: true,
  86607. configurable: true
  86608. });
  86609. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  86610. /**
  86611. * Gets wether tonemapping is enabled or not.
  86612. */
  86613. get: function () {
  86614. return this._imageProcessingConfiguration.toneMappingEnabled;
  86615. },
  86616. /**
  86617. * Sets wether tonemapping is enabled or not
  86618. */
  86619. set: function (value) {
  86620. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86621. },
  86622. enumerable: true,
  86623. configurable: true
  86624. });
  86625. ;
  86626. ;
  86627. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  86628. /**
  86629. * Gets contrast used in the effect.
  86630. */
  86631. get: function () {
  86632. return this.imageProcessingConfiguration.contrast;
  86633. },
  86634. /**
  86635. * Sets contrast used in the effect.
  86636. */
  86637. set: function (value) {
  86638. this.imageProcessingConfiguration.contrast = value;
  86639. },
  86640. enumerable: true,
  86641. configurable: true
  86642. });
  86643. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  86644. /**
  86645. * Gets Vignette stretch size.
  86646. */
  86647. get: function () {
  86648. return this.imageProcessingConfiguration.vignetteStretch;
  86649. },
  86650. /**
  86651. * Sets Vignette stretch size.
  86652. */
  86653. set: function (value) {
  86654. this.imageProcessingConfiguration.vignetteStretch = value;
  86655. },
  86656. enumerable: true,
  86657. configurable: true
  86658. });
  86659. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  86660. /**
  86661. * Gets Vignette centre X Offset.
  86662. */
  86663. get: function () {
  86664. return this.imageProcessingConfiguration.vignetteCentreX;
  86665. },
  86666. /**
  86667. * Sets Vignette centre X Offset.
  86668. */
  86669. set: function (value) {
  86670. this.imageProcessingConfiguration.vignetteCentreX = value;
  86671. },
  86672. enumerable: true,
  86673. configurable: true
  86674. });
  86675. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  86676. /**
  86677. * Gets Vignette centre Y Offset.
  86678. */
  86679. get: function () {
  86680. return this.imageProcessingConfiguration.vignetteCentreY;
  86681. },
  86682. /**
  86683. * Sets Vignette centre Y Offset.
  86684. */
  86685. set: function (value) {
  86686. this.imageProcessingConfiguration.vignetteCentreY = value;
  86687. },
  86688. enumerable: true,
  86689. configurable: true
  86690. });
  86691. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  86692. /**
  86693. * Gets Vignette weight or intensity of the vignette effect.
  86694. */
  86695. get: function () {
  86696. return this.imageProcessingConfiguration.vignetteWeight;
  86697. },
  86698. /**
  86699. * Sets Vignette weight or intensity of the vignette effect.
  86700. */
  86701. set: function (value) {
  86702. this.imageProcessingConfiguration.vignetteWeight = value;
  86703. },
  86704. enumerable: true,
  86705. configurable: true
  86706. });
  86707. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  86708. /**
  86709. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86710. * if vignetteEnabled is set to true.
  86711. */
  86712. get: function () {
  86713. return this.imageProcessingConfiguration.vignetteColor;
  86714. },
  86715. /**
  86716. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86717. * if vignetteEnabled is set to true.
  86718. */
  86719. set: function (value) {
  86720. this.imageProcessingConfiguration.vignetteColor = value;
  86721. },
  86722. enumerable: true,
  86723. configurable: true
  86724. });
  86725. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  86726. /**
  86727. * Gets Camera field of view used by the Vignette effect.
  86728. */
  86729. get: function () {
  86730. return this.imageProcessingConfiguration.vignetteCameraFov;
  86731. },
  86732. /**
  86733. * Sets Camera field of view used by the Vignette effect.
  86734. */
  86735. set: function (value) {
  86736. this.imageProcessingConfiguration.vignetteCameraFov = value;
  86737. },
  86738. enumerable: true,
  86739. configurable: true
  86740. });
  86741. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  86742. /**
  86743. * Gets the vignette blend mode allowing different kind of effect.
  86744. */
  86745. get: function () {
  86746. return this.imageProcessingConfiguration.vignetteBlendMode;
  86747. },
  86748. /**
  86749. * Sets the vignette blend mode allowing different kind of effect.
  86750. */
  86751. set: function (value) {
  86752. this.imageProcessingConfiguration.vignetteBlendMode = value;
  86753. },
  86754. enumerable: true,
  86755. configurable: true
  86756. });
  86757. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  86758. /**
  86759. * Gets wether the vignette effect is enabled.
  86760. */
  86761. get: function () {
  86762. return this.imageProcessingConfiguration.vignetteEnabled;
  86763. },
  86764. /**
  86765. * Sets wether the vignette effect is enabled.
  86766. */
  86767. set: function (value) {
  86768. this.imageProcessingConfiguration.vignetteEnabled = value;
  86769. },
  86770. enumerable: true,
  86771. configurable: true
  86772. });
  86773. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  86774. /**
  86775. * Gets wether the input of the processing is in Gamma or Linear Space.
  86776. */
  86777. get: function () {
  86778. return this._fromLinearSpace;
  86779. },
  86780. /**
  86781. * Sets wether the input of the processing is in Gamma or Linear Space.
  86782. */
  86783. set: function (value) {
  86784. if (this._fromLinearSpace === value) {
  86785. return;
  86786. }
  86787. this._fromLinearSpace = value;
  86788. this._updateParameters();
  86789. },
  86790. enumerable: true,
  86791. configurable: true
  86792. });
  86793. ImageProcessingPostProcess.prototype.getClassName = function () {
  86794. return "ImageProcessingPostProcess";
  86795. };
  86796. ImageProcessingPostProcess.prototype._updateParameters = function () {
  86797. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  86798. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  86799. var defines = "";
  86800. for (var define in this._defines) {
  86801. if (this._defines[define]) {
  86802. defines += "#define " + define + ";\r\n";
  86803. }
  86804. }
  86805. var samplers = ["textureSampler"];
  86806. var uniforms = ["scale"];
  86807. if (BABYLON.ImageProcessingConfiguration) {
  86808. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  86809. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  86810. }
  86811. this.updateEffect(defines, uniforms, samplers);
  86812. };
  86813. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  86814. _super.prototype.dispose.call(this, camera);
  86815. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86816. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86817. }
  86818. if (this._imageProcessingConfiguration) {
  86819. this.imageProcessingConfiguration.applyByPostProcess = false;
  86820. }
  86821. };
  86822. __decorate([
  86823. BABYLON.serialize()
  86824. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  86825. return ImageProcessingPostProcess;
  86826. }(BABYLON.PostProcess));
  86827. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  86828. })(BABYLON || (BABYLON = {}));
  86829. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  86830. var BABYLON;
  86831. (function (BABYLON) {
  86832. /**
  86833. * Class used to store bone information
  86834. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  86835. */
  86836. var Bone = /** @class */ (function (_super) {
  86837. __extends(Bone, _super);
  86838. /**
  86839. * Create a new bone
  86840. * @param name defines the bone name
  86841. * @param skeleton defines the parent skeleton
  86842. * @param parentBone defines the parent (can be null if the bone is the root)
  86843. * @param localMatrix defines the local matrix
  86844. * @param restPose defines the rest pose matrix
  86845. * @param baseMatrix defines the base matrix
  86846. * @param index defines index of the bone in the hiearchy
  86847. */
  86848. function Bone(
  86849. /**
  86850. * defines the bone name
  86851. */
  86852. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  86853. if (parentBone === void 0) { parentBone = null; }
  86854. if (localMatrix === void 0) { localMatrix = null; }
  86855. if (restPose === void 0) { restPose = null; }
  86856. if (baseMatrix === void 0) { baseMatrix = null; }
  86857. if (index === void 0) { index = null; }
  86858. var _this = _super.call(this, name, skeleton.getScene()) || this;
  86859. _this.name = name;
  86860. /**
  86861. * Gets the list of child bones
  86862. */
  86863. _this.children = new Array();
  86864. /** Gets the animations associated with this bone */
  86865. _this.animations = new Array();
  86866. /**
  86867. * @hidden Internal only
  86868. * Set this value to map this bone to a different index in the transform matrices
  86869. * Set this value to -1 to exclude the bone from the transform matrices
  86870. */
  86871. _this._index = null;
  86872. _this._absoluteTransform = new BABYLON.Matrix();
  86873. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  86874. _this._scalingDeterminant = 1;
  86875. _this._worldTransform = new BABYLON.Matrix();
  86876. _this._needToDecompose = true;
  86877. _this._needToCompose = false;
  86878. _this._skeleton = skeleton;
  86879. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  86880. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  86881. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  86882. _this._index = index;
  86883. skeleton.bones.push(_this);
  86884. _this.setParent(parentBone, false);
  86885. if (baseMatrix || localMatrix) {
  86886. _this._updateDifferenceMatrix();
  86887. }
  86888. return _this;
  86889. }
  86890. Object.defineProperty(Bone.prototype, "_matrix", {
  86891. /** @hidden */
  86892. get: function () {
  86893. this._compose();
  86894. return this._localMatrix;
  86895. },
  86896. /** @hidden */
  86897. set: function (value) {
  86898. this._localMatrix.copyFrom(value);
  86899. this._needToDecompose = true;
  86900. },
  86901. enumerable: true,
  86902. configurable: true
  86903. });
  86904. // Members
  86905. /**
  86906. * Gets the parent skeleton
  86907. * @returns a skeleton
  86908. */
  86909. Bone.prototype.getSkeleton = function () {
  86910. return this._skeleton;
  86911. };
  86912. /**
  86913. * Gets parent bone
  86914. * @returns a bone or null if the bone is the root of the bone hierarchy
  86915. */
  86916. Bone.prototype.getParent = function () {
  86917. return this._parent;
  86918. };
  86919. /**
  86920. * Sets the parent bone
  86921. * @param parent defines the parent (can be null if the bone is the root)
  86922. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  86923. */
  86924. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  86925. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  86926. if (this._parent === parent) {
  86927. return;
  86928. }
  86929. if (this._parent) {
  86930. var index = this._parent.children.indexOf(this);
  86931. if (index !== -1) {
  86932. this._parent.children.splice(index, 1);
  86933. }
  86934. }
  86935. this._parent = parent;
  86936. if (this._parent) {
  86937. this._parent.children.push(this);
  86938. }
  86939. if (updateDifferenceMatrix) {
  86940. this._updateDifferenceMatrix();
  86941. }
  86942. this.markAsDirty();
  86943. };
  86944. /**
  86945. * Gets the local matrix
  86946. * @returns a matrix
  86947. */
  86948. Bone.prototype.getLocalMatrix = function () {
  86949. this._compose();
  86950. return this._localMatrix;
  86951. };
  86952. /**
  86953. * Gets the base matrix (initial matrix which remains unchanged)
  86954. * @returns a matrix
  86955. */
  86956. Bone.prototype.getBaseMatrix = function () {
  86957. return this._baseMatrix;
  86958. };
  86959. /**
  86960. * Gets the rest pose matrix
  86961. * @returns a matrix
  86962. */
  86963. Bone.prototype.getRestPose = function () {
  86964. return this._restPose;
  86965. };
  86966. /**
  86967. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  86968. */
  86969. Bone.prototype.getWorldMatrix = function () {
  86970. return this._worldTransform;
  86971. };
  86972. /**
  86973. * Sets the local matrix to rest pose matrix
  86974. */
  86975. Bone.prototype.returnToRest = function () {
  86976. this.updateMatrix(this._restPose.clone());
  86977. };
  86978. /**
  86979. * Gets the inverse of the absolute transform matrix.
  86980. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  86981. * @returns a matrix
  86982. */
  86983. Bone.prototype.getInvertedAbsoluteTransform = function () {
  86984. return this._invertedAbsoluteTransform;
  86985. };
  86986. /**
  86987. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  86988. * @returns a matrix
  86989. */
  86990. Bone.prototype.getAbsoluteTransform = function () {
  86991. return this._absoluteTransform;
  86992. };
  86993. Object.defineProperty(Bone.prototype, "position", {
  86994. // Properties (matches AbstractMesh properties)
  86995. /** Gets or sets current position (in local space) */
  86996. get: function () {
  86997. this._decompose();
  86998. return this._localPosition;
  86999. },
  87000. set: function (newPosition) {
  87001. this._decompose();
  87002. this._localPosition.copyFrom(newPosition);
  87003. this._markAsDirtyAndCompose();
  87004. },
  87005. enumerable: true,
  87006. configurable: true
  87007. });
  87008. Object.defineProperty(Bone.prototype, "rotation", {
  87009. /** Gets or sets current rotation (in local space) */
  87010. get: function () {
  87011. return this.getRotation();
  87012. },
  87013. set: function (newRotation) {
  87014. this.setRotation(newRotation);
  87015. },
  87016. enumerable: true,
  87017. configurable: true
  87018. });
  87019. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  87020. /** Gets or sets current rotation quaternion (in local space) */
  87021. get: function () {
  87022. this._decompose();
  87023. return this._localRotation;
  87024. },
  87025. set: function (newRotation) {
  87026. this.setRotationQuaternion(newRotation);
  87027. },
  87028. enumerable: true,
  87029. configurable: true
  87030. });
  87031. Object.defineProperty(Bone.prototype, "scaling", {
  87032. /** Gets or sets current scaling (in local space) */
  87033. get: function () {
  87034. return this.getScale();
  87035. },
  87036. set: function (newScaling) {
  87037. this.setScale(newScaling);
  87038. },
  87039. enumerable: true,
  87040. configurable: true
  87041. });
  87042. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  87043. /**
  87044. * Gets the animation properties override
  87045. */
  87046. get: function () {
  87047. return this._skeleton.animationPropertiesOverride;
  87048. },
  87049. enumerable: true,
  87050. configurable: true
  87051. });
  87052. // Methods
  87053. Bone.prototype._decompose = function () {
  87054. if (!this._needToDecompose) {
  87055. return;
  87056. }
  87057. this._needToDecompose = false;
  87058. if (!this._localScaling) {
  87059. this._localScaling = BABYLON.Vector3.Zero();
  87060. this._localRotation = BABYLON.Quaternion.Zero();
  87061. this._localPosition = BABYLON.Vector3.Zero();
  87062. }
  87063. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  87064. };
  87065. Bone.prototype._compose = function () {
  87066. if (!this._needToCompose) {
  87067. return;
  87068. }
  87069. this._needToCompose = false;
  87070. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  87071. };
  87072. /**
  87073. * Update the base and local matrices
  87074. * @param matrix defines the new base or local matrix
  87075. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  87076. * @param updateLocalMatrix defines if the local matrix should be updated
  87077. */
  87078. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  87079. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  87080. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  87081. this._baseMatrix.copyFrom(matrix);
  87082. if (updateDifferenceMatrix) {
  87083. this._updateDifferenceMatrix();
  87084. }
  87085. if (updateLocalMatrix) {
  87086. this._localMatrix.copyFrom(matrix);
  87087. this._markAsDirtyAndDecompose();
  87088. }
  87089. else {
  87090. this.markAsDirty();
  87091. }
  87092. };
  87093. /** @hidden */
  87094. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  87095. if (updateChildren === void 0) { updateChildren = true; }
  87096. if (!rootMatrix) {
  87097. rootMatrix = this._baseMatrix;
  87098. }
  87099. if (this._parent) {
  87100. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87101. }
  87102. else {
  87103. this._absoluteTransform.copyFrom(rootMatrix);
  87104. }
  87105. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  87106. if (updateChildren) {
  87107. for (var index = 0; index < this.children.length; index++) {
  87108. this.children[index]._updateDifferenceMatrix();
  87109. }
  87110. }
  87111. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  87112. };
  87113. /**
  87114. * Flag the bone as dirty (Forcing it to update everything)
  87115. */
  87116. Bone.prototype.markAsDirty = function () {
  87117. this._currentRenderId++;
  87118. this._childRenderId++;
  87119. this._skeleton._markAsDirty();
  87120. };
  87121. Bone.prototype._markAsDirtyAndCompose = function () {
  87122. this.markAsDirty();
  87123. this._needToCompose = true;
  87124. };
  87125. Bone.prototype._markAsDirtyAndDecompose = function () {
  87126. this.markAsDirty();
  87127. this._needToDecompose = true;
  87128. };
  87129. /**
  87130. * Copy an animation range from another bone
  87131. * @param source defines the source bone
  87132. * @param rangeName defines the range name to copy
  87133. * @param frameOffset defines the frame offset
  87134. * @param rescaleAsRequired defines if rescaling must be applied if required
  87135. * @param skelDimensionsRatio defines the scaling ratio
  87136. * @returns true if operation was successful
  87137. */
  87138. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  87139. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  87140. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  87141. // all animation may be coming from a library skeleton, so may need to create animation
  87142. if (this.animations.length === 0) {
  87143. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  87144. this.animations[0].setKeys([]);
  87145. }
  87146. // get animation info / verify there is such a range from the source bone
  87147. var sourceRange = source.animations[0].getRange(rangeName);
  87148. if (!sourceRange) {
  87149. return false;
  87150. }
  87151. var from = sourceRange.from;
  87152. var to = sourceRange.to;
  87153. var sourceKeys = source.animations[0].getKeys();
  87154. // rescaling prep
  87155. var sourceBoneLength = source.length;
  87156. var sourceParent = source.getParent();
  87157. var parent = this.getParent();
  87158. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  87159. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  87160. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  87161. var destKeys = this.animations[0].getKeys();
  87162. // loop vars declaration
  87163. var orig;
  87164. var origTranslation;
  87165. var mat;
  87166. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  87167. orig = sourceKeys[key];
  87168. if (orig.frame >= from && orig.frame <= to) {
  87169. if (rescaleAsRequired) {
  87170. mat = orig.value.clone();
  87171. // scale based on parent ratio, when bone has parent
  87172. if (parentScalingReqd) {
  87173. origTranslation = mat.getTranslation();
  87174. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  87175. // scale based on skeleton dimension ratio when root bone, and value is passed
  87176. }
  87177. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  87178. origTranslation = mat.getTranslation();
  87179. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  87180. // use original when root bone, and no data for skelDimensionsRatio
  87181. }
  87182. else {
  87183. mat = orig.value;
  87184. }
  87185. }
  87186. else {
  87187. mat = orig.value;
  87188. }
  87189. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  87190. }
  87191. }
  87192. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  87193. return true;
  87194. };
  87195. /**
  87196. * Translate the bone in local or world space
  87197. * @param vec The amount to translate the bone
  87198. * @param space The space that the translation is in
  87199. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87200. */
  87201. Bone.prototype.translate = function (vec, space, mesh) {
  87202. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87203. var lm = this.getLocalMatrix();
  87204. if (space == BABYLON.Space.LOCAL) {
  87205. lm.m[12] += vec.x;
  87206. lm.m[13] += vec.y;
  87207. lm.m[14] += vec.z;
  87208. }
  87209. else {
  87210. var wm = null;
  87211. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87212. if (mesh) {
  87213. wm = mesh.getWorldMatrix();
  87214. }
  87215. this._skeleton.computeAbsoluteTransforms();
  87216. var tmat = Bone._tmpMats[0];
  87217. var tvec = Bone._tmpVecs[0];
  87218. if (this._parent) {
  87219. if (mesh && wm) {
  87220. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87221. tmat.multiplyToRef(wm, tmat);
  87222. }
  87223. else {
  87224. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87225. }
  87226. }
  87227. tmat.m[12] = 0;
  87228. tmat.m[13] = 0;
  87229. tmat.m[14] = 0;
  87230. tmat.invert();
  87231. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  87232. lm.m[12] += tvec.x;
  87233. lm.m[13] += tvec.y;
  87234. lm.m[14] += tvec.z;
  87235. }
  87236. this._markAsDirtyAndDecompose();
  87237. };
  87238. /**
  87239. * Set the postion of the bone in local or world space
  87240. * @param position The position to set the bone
  87241. * @param space The space that the position is in
  87242. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87243. */
  87244. Bone.prototype.setPosition = function (position, space, mesh) {
  87245. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87246. var lm = this.getLocalMatrix();
  87247. if (space == BABYLON.Space.LOCAL) {
  87248. lm.m[12] = position.x;
  87249. lm.m[13] = position.y;
  87250. lm.m[14] = position.z;
  87251. }
  87252. else {
  87253. var wm = null;
  87254. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87255. if (mesh) {
  87256. wm = mesh.getWorldMatrix();
  87257. }
  87258. this._skeleton.computeAbsoluteTransforms();
  87259. var tmat = Bone._tmpMats[0];
  87260. var vec = Bone._tmpVecs[0];
  87261. if (this._parent) {
  87262. if (mesh && wm) {
  87263. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87264. tmat.multiplyToRef(wm, tmat);
  87265. }
  87266. else {
  87267. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87268. }
  87269. }
  87270. tmat.invert();
  87271. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  87272. lm.m[12] = vec.x;
  87273. lm.m[13] = vec.y;
  87274. lm.m[14] = vec.z;
  87275. }
  87276. this._markAsDirtyAndDecompose();
  87277. };
  87278. /**
  87279. * Set the absolute position of the bone (world space)
  87280. * @param position The position to set the bone
  87281. * @param mesh The mesh that this bone is attached to
  87282. */
  87283. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  87284. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  87285. };
  87286. /**
  87287. * Scale the bone on the x, y and z axes (in local space)
  87288. * @param x The amount to scale the bone on the x axis
  87289. * @param y The amount to scale the bone on the y axis
  87290. * @param z The amount to scale the bone on the z axis
  87291. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  87292. */
  87293. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  87294. if (scaleChildren === void 0) { scaleChildren = false; }
  87295. var locMat = this.getLocalMatrix();
  87296. // Apply new scaling on top of current local matrix
  87297. var scaleMat = Bone._tmpMats[0];
  87298. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  87299. scaleMat.multiplyToRef(locMat, locMat);
  87300. // Invert scaling matrix and apply the inverse to all children
  87301. scaleMat.invert();
  87302. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  87303. var child = _a[_i];
  87304. var cm = child.getLocalMatrix();
  87305. cm.multiplyToRef(scaleMat, cm);
  87306. cm.m[12] *= x;
  87307. cm.m[13] *= y;
  87308. cm.m[14] *= z;
  87309. child._markAsDirtyAndDecompose();
  87310. }
  87311. this._markAsDirtyAndDecompose();
  87312. if (scaleChildren) {
  87313. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  87314. var child = _c[_b];
  87315. child.scale(x, y, z, scaleChildren);
  87316. }
  87317. }
  87318. };
  87319. /**
  87320. * Set the bone scaling in local space
  87321. * @param scale defines the scaling vector
  87322. */
  87323. Bone.prototype.setScale = function (scale) {
  87324. this._decompose();
  87325. this._localScaling.copyFrom(scale);
  87326. this._markAsDirtyAndCompose();
  87327. };
  87328. /**
  87329. * Gets the current scaling in local space
  87330. * @returns the current scaling vector
  87331. */
  87332. Bone.prototype.getScale = function () {
  87333. this._decompose();
  87334. return this._localScaling;
  87335. };
  87336. /**
  87337. * Gets the current scaling in local space and stores it in a target vector
  87338. * @param result defines the target vector
  87339. */
  87340. Bone.prototype.getScaleToRef = function (result) {
  87341. this._decompose();
  87342. result.copyFrom(this._localScaling);
  87343. };
  87344. /**
  87345. * Set the yaw, pitch, and roll of the bone in local or world space
  87346. * @param yaw The rotation of the bone on the y axis
  87347. * @param pitch The rotation of the bone on the x axis
  87348. * @param roll The rotation of the bone on the z axis
  87349. * @param space The space that the axes of rotation are in
  87350. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87351. */
  87352. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  87353. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87354. if (space === BABYLON.Space.LOCAL) {
  87355. var quat = Bone._tmpQuat;
  87356. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  87357. this.setRotationQuaternion(quat, space, mesh);
  87358. return;
  87359. }
  87360. var rotMatInv = Bone._tmpMats[0];
  87361. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87362. return;
  87363. }
  87364. var rotMat = Bone._tmpMats[1];
  87365. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  87366. rotMatInv.multiplyToRef(rotMat, rotMat);
  87367. this._rotateWithMatrix(rotMat, space, mesh);
  87368. };
  87369. /**
  87370. * Add a rotation to the bone on an axis in local or world space
  87371. * @param axis The axis to rotate the bone on
  87372. * @param amount The amount to rotate the bone
  87373. * @param space The space that the axis is in
  87374. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87375. */
  87376. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  87377. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87378. var rmat = Bone._tmpMats[0];
  87379. rmat.m[12] = 0;
  87380. rmat.m[13] = 0;
  87381. rmat.m[14] = 0;
  87382. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  87383. this._rotateWithMatrix(rmat, space, mesh);
  87384. };
  87385. /**
  87386. * Set the rotation of the bone to a particular axis angle in local or world space
  87387. * @param axis The axis to rotate the bone on
  87388. * @param angle The angle that the bone should be rotated to
  87389. * @param space The space that the axis is in
  87390. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87391. */
  87392. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  87393. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87394. if (space === BABYLON.Space.LOCAL) {
  87395. var quat = Bone._tmpQuat;
  87396. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  87397. this.setRotationQuaternion(quat, space, mesh);
  87398. return;
  87399. }
  87400. var rotMatInv = Bone._tmpMats[0];
  87401. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87402. return;
  87403. }
  87404. var rotMat = Bone._tmpMats[1];
  87405. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  87406. rotMatInv.multiplyToRef(rotMat, rotMat);
  87407. this._rotateWithMatrix(rotMat, space, mesh);
  87408. };
  87409. /**
  87410. * Set the euler rotation of the bone in local of world space
  87411. * @param rotation The euler rotation that the bone should be set to
  87412. * @param space The space that the rotation is in
  87413. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87414. */
  87415. Bone.prototype.setRotation = function (rotation, space, mesh) {
  87416. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87417. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  87418. };
  87419. /**
  87420. * Set the quaternion rotation of the bone in local of world space
  87421. * @param quat The quaternion rotation that the bone should be set to
  87422. * @param space The space that the rotation is in
  87423. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87424. */
  87425. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  87426. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87427. if (space === BABYLON.Space.LOCAL) {
  87428. this._decompose();
  87429. this._localRotation.copyFrom(quat);
  87430. this._markAsDirtyAndCompose();
  87431. return;
  87432. }
  87433. var rotMatInv = Bone._tmpMats[0];
  87434. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87435. return;
  87436. }
  87437. var rotMat = Bone._tmpMats[1];
  87438. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  87439. rotMatInv.multiplyToRef(rotMat, rotMat);
  87440. this._rotateWithMatrix(rotMat, space, mesh);
  87441. };
  87442. /**
  87443. * Set the rotation matrix of the bone in local of world space
  87444. * @param rotMat The rotation matrix that the bone should be set to
  87445. * @param space The space that the rotation is in
  87446. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87447. */
  87448. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  87449. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87450. if (space === BABYLON.Space.LOCAL) {
  87451. var quat = Bone._tmpQuat;
  87452. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  87453. this.setRotationQuaternion(quat, space, mesh);
  87454. return;
  87455. }
  87456. var rotMatInv = Bone._tmpMats[0];
  87457. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87458. return;
  87459. }
  87460. var rotMat2 = Bone._tmpMats[1];
  87461. rotMat2.copyFrom(rotMat);
  87462. rotMatInv.multiplyToRef(rotMat, rotMat2);
  87463. this._rotateWithMatrix(rotMat2, space, mesh);
  87464. };
  87465. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  87466. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87467. var lmat = this.getLocalMatrix();
  87468. var lx = lmat.m[12];
  87469. var ly = lmat.m[13];
  87470. var lz = lmat.m[14];
  87471. var parent = this.getParent();
  87472. var parentScale = Bone._tmpMats[3];
  87473. var parentScaleInv = Bone._tmpMats[4];
  87474. if (parent && space == BABYLON.Space.WORLD) {
  87475. if (mesh) {
  87476. parentScale.copyFrom(mesh.getWorldMatrix());
  87477. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  87478. }
  87479. else {
  87480. parentScale.copyFrom(parent.getAbsoluteTransform());
  87481. }
  87482. parentScaleInv.copyFrom(parentScale);
  87483. parentScaleInv.invert();
  87484. lmat.multiplyToRef(parentScale, lmat);
  87485. lmat.multiplyToRef(rmat, lmat);
  87486. lmat.multiplyToRef(parentScaleInv, lmat);
  87487. }
  87488. else {
  87489. if (space == BABYLON.Space.WORLD && mesh) {
  87490. parentScale.copyFrom(mesh.getWorldMatrix());
  87491. parentScaleInv.copyFrom(parentScale);
  87492. parentScaleInv.invert();
  87493. lmat.multiplyToRef(parentScale, lmat);
  87494. lmat.multiplyToRef(rmat, lmat);
  87495. lmat.multiplyToRef(parentScaleInv, lmat);
  87496. }
  87497. else {
  87498. lmat.multiplyToRef(rmat, lmat);
  87499. }
  87500. }
  87501. lmat.m[12] = lx;
  87502. lmat.m[13] = ly;
  87503. lmat.m[14] = lz;
  87504. this.computeAbsoluteTransforms();
  87505. this._markAsDirtyAndDecompose();
  87506. };
  87507. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  87508. var scaleMatrix = Bone._tmpMats[2];
  87509. rotMatInv.copyFrom(this.getAbsoluteTransform());
  87510. if (mesh) {
  87511. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  87512. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  87513. }
  87514. rotMatInv.invert();
  87515. if (isNaN(rotMatInv.m[0])) {
  87516. // Matrix failed to invert.
  87517. // This can happen if scale is zero for example.
  87518. return false;
  87519. }
  87520. scaleMatrix.m[0] *= this._scalingDeterminant;
  87521. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  87522. return true;
  87523. };
  87524. /**
  87525. * Get the position of the bone in local or world space
  87526. * @param space The space that the returned position is in
  87527. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87528. * @returns The position of the bone
  87529. */
  87530. Bone.prototype.getPosition = function (space, mesh) {
  87531. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87532. if (mesh === void 0) { mesh = null; }
  87533. var pos = BABYLON.Vector3.Zero();
  87534. this.getPositionToRef(space, mesh, pos);
  87535. return pos;
  87536. };
  87537. /**
  87538. * Copy the position of the bone to a vector3 in local or world space
  87539. * @param space The space that the returned position is in
  87540. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87541. * @param result The vector3 to copy the position to
  87542. */
  87543. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  87544. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87545. if (space == BABYLON.Space.LOCAL) {
  87546. var lm = this.getLocalMatrix();
  87547. result.x = lm.m[12];
  87548. result.y = lm.m[13];
  87549. result.z = lm.m[14];
  87550. }
  87551. else {
  87552. var wm = null;
  87553. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87554. if (mesh) {
  87555. wm = mesh.getWorldMatrix();
  87556. }
  87557. this._skeleton.computeAbsoluteTransforms();
  87558. var tmat = Bone._tmpMats[0];
  87559. if (mesh && wm) {
  87560. tmat.copyFrom(this.getAbsoluteTransform());
  87561. tmat.multiplyToRef(wm, tmat);
  87562. }
  87563. else {
  87564. tmat = this.getAbsoluteTransform();
  87565. }
  87566. result.x = tmat.m[12];
  87567. result.y = tmat.m[13];
  87568. result.z = tmat.m[14];
  87569. }
  87570. };
  87571. /**
  87572. * Get the absolute position of the bone (world space)
  87573. * @param mesh The mesh that this bone is attached to
  87574. * @returns The absolute position of the bone
  87575. */
  87576. Bone.prototype.getAbsolutePosition = function (mesh) {
  87577. if (mesh === void 0) { mesh = null; }
  87578. var pos = BABYLON.Vector3.Zero();
  87579. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  87580. return pos;
  87581. };
  87582. /**
  87583. * Copy the absolute position of the bone (world space) to the result param
  87584. * @param mesh The mesh that this bone is attached to
  87585. * @param result The vector3 to copy the absolute position to
  87586. */
  87587. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  87588. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  87589. };
  87590. /**
  87591. * Compute the absolute transforms of this bone and its children
  87592. */
  87593. Bone.prototype.computeAbsoluteTransforms = function () {
  87594. this._compose();
  87595. if (this._parent) {
  87596. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87597. }
  87598. else {
  87599. this._absoluteTransform.copyFrom(this._localMatrix);
  87600. var poseMatrix = this._skeleton.getPoseMatrix();
  87601. if (poseMatrix) {
  87602. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  87603. }
  87604. }
  87605. var children = this.children;
  87606. var len = children.length;
  87607. for (var i = 0; i < len; i++) {
  87608. children[i].computeAbsoluteTransforms();
  87609. }
  87610. };
  87611. /**
  87612. * Get the world direction from an axis that is in the local space of the bone
  87613. * @param localAxis The local direction that is used to compute the world direction
  87614. * @param mesh The mesh that this bone is attached to
  87615. * @returns The world direction
  87616. */
  87617. Bone.prototype.getDirection = function (localAxis, mesh) {
  87618. if (mesh === void 0) { mesh = null; }
  87619. var result = BABYLON.Vector3.Zero();
  87620. this.getDirectionToRef(localAxis, mesh, result);
  87621. return result;
  87622. };
  87623. /**
  87624. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  87625. * @param localAxis The local direction that is used to compute the world direction
  87626. * @param mesh The mesh that this bone is attached to
  87627. * @param result The vector3 that the world direction will be copied to
  87628. */
  87629. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  87630. if (mesh === void 0) { mesh = null; }
  87631. var wm = null;
  87632. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87633. if (mesh) {
  87634. wm = mesh.getWorldMatrix();
  87635. }
  87636. this._skeleton.computeAbsoluteTransforms();
  87637. var mat = Bone._tmpMats[0];
  87638. mat.copyFrom(this.getAbsoluteTransform());
  87639. if (mesh && wm) {
  87640. mat.multiplyToRef(wm, mat);
  87641. }
  87642. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  87643. result.normalize();
  87644. };
  87645. /**
  87646. * Get the euler rotation of the bone in local or world space
  87647. * @param space The space that the rotation should be in
  87648. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87649. * @returns The euler rotation
  87650. */
  87651. Bone.prototype.getRotation = function (space, mesh) {
  87652. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87653. if (mesh === void 0) { mesh = null; }
  87654. var result = BABYLON.Vector3.Zero();
  87655. this.getRotationToRef(space, mesh, result);
  87656. return result;
  87657. };
  87658. /**
  87659. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  87660. * @param space The space that the rotation should be in
  87661. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87662. * @param result The vector3 that the rotation should be copied to
  87663. */
  87664. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  87665. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87666. if (mesh === void 0) { mesh = null; }
  87667. var quat = Bone._tmpQuat;
  87668. this.getRotationQuaternionToRef(space, mesh, quat);
  87669. quat.toEulerAnglesToRef(result);
  87670. };
  87671. /**
  87672. * Get the quaternion rotation of the bone in either local or world space
  87673. * @param space The space that the rotation should be in
  87674. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87675. * @returns The quaternion rotation
  87676. */
  87677. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  87678. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87679. if (mesh === void 0) { mesh = null; }
  87680. var result = BABYLON.Quaternion.Identity();
  87681. this.getRotationQuaternionToRef(space, mesh, result);
  87682. return result;
  87683. };
  87684. /**
  87685. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  87686. * @param space The space that the rotation should be in
  87687. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87688. * @param result The quaternion that the rotation should be copied to
  87689. */
  87690. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  87691. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87692. if (mesh === void 0) { mesh = null; }
  87693. if (space == BABYLON.Space.LOCAL) {
  87694. this._decompose();
  87695. result.copyFrom(this._localRotation);
  87696. }
  87697. else {
  87698. var mat = Bone._tmpMats[0];
  87699. var amat = this.getAbsoluteTransform();
  87700. if (mesh) {
  87701. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  87702. }
  87703. else {
  87704. mat.copyFrom(amat);
  87705. }
  87706. mat.m[0] *= this._scalingDeterminant;
  87707. mat.m[1] *= this._scalingDeterminant;
  87708. mat.m[2] *= this._scalingDeterminant;
  87709. mat.decompose(undefined, result, undefined);
  87710. }
  87711. };
  87712. /**
  87713. * Get the rotation matrix of the bone in local or world space
  87714. * @param space The space that the rotation should be in
  87715. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87716. * @returns The rotation matrix
  87717. */
  87718. Bone.prototype.getRotationMatrix = function (space, mesh) {
  87719. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87720. var result = BABYLON.Matrix.Identity();
  87721. this.getRotationMatrixToRef(space, mesh, result);
  87722. return result;
  87723. };
  87724. /**
  87725. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  87726. * @param space The space that the rotation should be in
  87727. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87728. * @param result The quaternion that the rotation should be copied to
  87729. */
  87730. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  87731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87732. if (space == BABYLON.Space.LOCAL) {
  87733. this.getLocalMatrix().getRotationMatrixToRef(result);
  87734. }
  87735. else {
  87736. var mat = Bone._tmpMats[0];
  87737. var amat = this.getAbsoluteTransform();
  87738. if (mesh) {
  87739. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  87740. }
  87741. else {
  87742. mat.copyFrom(amat);
  87743. }
  87744. mat.m[0] *= this._scalingDeterminant;
  87745. mat.m[1] *= this._scalingDeterminant;
  87746. mat.m[2] *= this._scalingDeterminant;
  87747. mat.getRotationMatrixToRef(result);
  87748. }
  87749. };
  87750. /**
  87751. * Get the world position of a point that is in the local space of the bone
  87752. * @param position The local position
  87753. * @param mesh The mesh that this bone is attached to
  87754. * @returns The world position
  87755. */
  87756. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  87757. if (mesh === void 0) { mesh = null; }
  87758. var result = BABYLON.Vector3.Zero();
  87759. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  87760. return result;
  87761. };
  87762. /**
  87763. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  87764. * @param position The local position
  87765. * @param mesh The mesh that this bone is attached to
  87766. * @param result The vector3 that the world position should be copied to
  87767. */
  87768. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  87769. if (mesh === void 0) { mesh = null; }
  87770. var wm = null;
  87771. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87772. if (mesh) {
  87773. wm = mesh.getWorldMatrix();
  87774. }
  87775. this._skeleton.computeAbsoluteTransforms();
  87776. var tmat = Bone._tmpMats[0];
  87777. if (mesh && wm) {
  87778. tmat.copyFrom(this.getAbsoluteTransform());
  87779. tmat.multiplyToRef(wm, tmat);
  87780. }
  87781. else {
  87782. tmat = this.getAbsoluteTransform();
  87783. }
  87784. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  87785. };
  87786. /**
  87787. * Get the local position of a point that is in world space
  87788. * @param position The world position
  87789. * @param mesh The mesh that this bone is attached to
  87790. * @returns The local position
  87791. */
  87792. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  87793. if (mesh === void 0) { mesh = null; }
  87794. var result = BABYLON.Vector3.Zero();
  87795. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  87796. return result;
  87797. };
  87798. /**
  87799. * Get the local position of a point that is in world space and copy it to the result param
  87800. * @param position The world position
  87801. * @param mesh The mesh that this bone is attached to
  87802. * @param result The vector3 that the local position should be copied to
  87803. */
  87804. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  87805. if (mesh === void 0) { mesh = null; }
  87806. var wm = null;
  87807. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87808. if (mesh) {
  87809. wm = mesh.getWorldMatrix();
  87810. }
  87811. this._skeleton.computeAbsoluteTransforms();
  87812. var tmat = Bone._tmpMats[0];
  87813. tmat.copyFrom(this.getAbsoluteTransform());
  87814. if (mesh && wm) {
  87815. tmat.multiplyToRef(wm, tmat);
  87816. }
  87817. tmat.invert();
  87818. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  87819. };
  87820. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87821. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  87822. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87823. return Bone;
  87824. }(BABYLON.Node));
  87825. BABYLON.Bone = Bone;
  87826. })(BABYLON || (BABYLON = {}));
  87827. //# sourceMappingURL=babylon.bone.js.map
  87828. var BABYLON;
  87829. (function (BABYLON) {
  87830. /**
  87831. * Class used to apply inverse kinematics to bones
  87832. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  87833. */
  87834. var BoneIKController = /** @class */ (function () {
  87835. /**
  87836. * Creates a new BoneIKController
  87837. * @param mesh defines the mesh to control
  87838. * @param bone defines the bone to control
  87839. * @param options defines options to set up the controller
  87840. */
  87841. function BoneIKController(mesh, bone, options) {
  87842. /**
  87843. * Gets or sets the target position
  87844. */
  87845. this.targetPosition = BABYLON.Vector3.Zero();
  87846. /**
  87847. * Gets or sets the pole target position
  87848. */
  87849. this.poleTargetPosition = BABYLON.Vector3.Zero();
  87850. /**
  87851. * Gets or sets the pole target local offset
  87852. */
  87853. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  87854. /**
  87855. * Gets or sets the pole angle
  87856. */
  87857. this.poleAngle = 0;
  87858. /**
  87859. * 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)
  87860. */
  87861. this.slerpAmount = 1;
  87862. this._bone1Quat = BABYLON.Quaternion.Identity();
  87863. this._bone1Mat = BABYLON.Matrix.Identity();
  87864. this._bone2Ang = Math.PI;
  87865. this._maxAngle = Math.PI;
  87866. this._rightHandedSystem = false;
  87867. this._bendAxis = BABYLON.Vector3.Right();
  87868. this._slerping = false;
  87869. this._adjustRoll = 0;
  87870. this._bone2 = bone;
  87871. this._bone1 = bone.getParent();
  87872. if (!this._bone1) {
  87873. return;
  87874. }
  87875. this.mesh = mesh;
  87876. var bonePos = bone.getPosition();
  87877. if (bone.getAbsoluteTransform().determinant() > 0) {
  87878. this._rightHandedSystem = true;
  87879. this._bendAxis.x = 0;
  87880. this._bendAxis.y = 0;
  87881. this._bendAxis.z = -1;
  87882. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  87883. this._adjustRoll = Math.PI * .5;
  87884. this._bendAxis.z = 1;
  87885. }
  87886. }
  87887. if (this._bone1.length) {
  87888. var boneScale1 = this._bone1.getScale();
  87889. var boneScale2 = this._bone2.getScale();
  87890. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  87891. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  87892. }
  87893. else if (this._bone1.children[0]) {
  87894. mesh.computeWorldMatrix(true);
  87895. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  87896. var pos2 = this._bone2.getAbsolutePosition(mesh);
  87897. var pos3 = this._bone1.getAbsolutePosition(mesh);
  87898. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  87899. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  87900. }
  87901. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  87902. this.maxAngle = Math.PI;
  87903. if (options) {
  87904. if (options.targetMesh) {
  87905. this.targetMesh = options.targetMesh;
  87906. this.targetMesh.computeWorldMatrix(true);
  87907. }
  87908. if (options.poleTargetMesh) {
  87909. this.poleTargetMesh = options.poleTargetMesh;
  87910. this.poleTargetMesh.computeWorldMatrix(true);
  87911. }
  87912. else if (options.poleTargetBone) {
  87913. this.poleTargetBone = options.poleTargetBone;
  87914. }
  87915. else if (this._bone1.getParent()) {
  87916. this.poleTargetBone = this._bone1.getParent();
  87917. }
  87918. if (options.poleTargetLocalOffset) {
  87919. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  87920. }
  87921. if (options.poleAngle) {
  87922. this.poleAngle = options.poleAngle;
  87923. }
  87924. if (options.bendAxis) {
  87925. this._bendAxis.copyFrom(options.bendAxis);
  87926. }
  87927. if (options.maxAngle) {
  87928. this.maxAngle = options.maxAngle;
  87929. }
  87930. if (options.slerpAmount) {
  87931. this.slerpAmount = options.slerpAmount;
  87932. }
  87933. }
  87934. }
  87935. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  87936. /**
  87937. * Gets or sets maximum allowed angle
  87938. */
  87939. get: function () {
  87940. return this._maxAngle;
  87941. },
  87942. set: function (value) {
  87943. this._setMaxAngle(value);
  87944. },
  87945. enumerable: true,
  87946. configurable: true
  87947. });
  87948. BoneIKController.prototype._setMaxAngle = function (ang) {
  87949. if (ang < 0) {
  87950. ang = 0;
  87951. }
  87952. if (ang > Math.PI || ang == undefined) {
  87953. ang = Math.PI;
  87954. }
  87955. this._maxAngle = ang;
  87956. var a = this._bone1Length;
  87957. var b = this._bone2Length;
  87958. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  87959. };
  87960. /**
  87961. * Force the controller to update the bones
  87962. */
  87963. BoneIKController.prototype.update = function () {
  87964. var bone1 = this._bone1;
  87965. if (!bone1) {
  87966. return;
  87967. }
  87968. var target = this.targetPosition;
  87969. var poleTarget = this.poleTargetPosition;
  87970. var mat1 = BoneIKController._tmpMats[0];
  87971. var mat2 = BoneIKController._tmpMats[1];
  87972. if (this.targetMesh) {
  87973. target.copyFrom(this.targetMesh.getAbsolutePosition());
  87974. }
  87975. if (this.poleTargetBone) {
  87976. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  87977. }
  87978. else if (this.poleTargetMesh) {
  87979. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  87980. }
  87981. var bonePos = BoneIKController._tmpVecs[0];
  87982. var zaxis = BoneIKController._tmpVecs[1];
  87983. var xaxis = BoneIKController._tmpVecs[2];
  87984. var yaxis = BoneIKController._tmpVecs[3];
  87985. var upAxis = BoneIKController._tmpVecs[4];
  87986. var _tmpQuat = BoneIKController._tmpQuat;
  87987. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  87988. poleTarget.subtractToRef(bonePos, upAxis);
  87989. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  87990. upAxis.y = 1;
  87991. }
  87992. else {
  87993. upAxis.normalize();
  87994. }
  87995. target.subtractToRef(bonePos, yaxis);
  87996. yaxis.normalize();
  87997. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  87998. zaxis.normalize();
  87999. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  88000. xaxis.normalize();
  88001. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  88002. var a = this._bone1Length;
  88003. var b = this._bone2Length;
  88004. var c = BABYLON.Vector3.Distance(bonePos, target);
  88005. if (this._maxReach > 0) {
  88006. c = Math.min(this._maxReach, c);
  88007. }
  88008. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  88009. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  88010. if (acosa > 1) {
  88011. acosa = 1;
  88012. }
  88013. if (acosb > 1) {
  88014. acosb = 1;
  88015. }
  88016. if (acosa < -1) {
  88017. acosa = -1;
  88018. }
  88019. if (acosb < -1) {
  88020. acosb = -1;
  88021. }
  88022. var angA = Math.acos(acosa);
  88023. var angB = Math.acos(acosb);
  88024. var angC = -angA - angB;
  88025. if (this._rightHandedSystem) {
  88026. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  88027. mat2.multiplyToRef(mat1, mat1);
  88028. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  88029. mat2.multiplyToRef(mat1, mat1);
  88030. }
  88031. else {
  88032. var _tmpVec = BoneIKController._tmpVecs[5];
  88033. _tmpVec.copyFrom(this._bendAxis);
  88034. _tmpVec.x *= -1;
  88035. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  88036. mat2.multiplyToRef(mat1, mat1);
  88037. }
  88038. if (this.poleAngle) {
  88039. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  88040. mat1.multiplyToRef(mat2, mat1);
  88041. }
  88042. if (this._bone1) {
  88043. if (this.slerpAmount < 1) {
  88044. if (!this._slerping) {
  88045. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  88046. }
  88047. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  88048. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  88049. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  88050. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  88051. this._slerping = true;
  88052. }
  88053. else {
  88054. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  88055. this._bone1Mat.copyFrom(mat1);
  88056. this._slerping = false;
  88057. }
  88058. }
  88059. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  88060. this._bone2Ang = angC;
  88061. };
  88062. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88063. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  88064. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88065. return BoneIKController;
  88066. }());
  88067. BABYLON.BoneIKController = BoneIKController;
  88068. })(BABYLON || (BABYLON = {}));
  88069. //# sourceMappingURL=babylon.boneIKController.js.map
  88070. var BABYLON;
  88071. (function (BABYLON) {
  88072. /**
  88073. * Class used to make a bone look toward a point in space
  88074. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  88075. */
  88076. var BoneLookController = /** @class */ (function () {
  88077. /**
  88078. * Create a BoneLookController
  88079. * @param mesh the mesh that the bone belongs to
  88080. * @param bone the bone that will be looking to the target
  88081. * @param target the target Vector3 to look at
  88082. * @param settings optional settings:
  88083. * * maxYaw: the maximum angle the bone will yaw to
  88084. * * minYaw: the minimum angle the bone will yaw to
  88085. * * maxPitch: the maximum angle the bone will pitch to
  88086. * * minPitch: the minimum angle the bone will yaw to
  88087. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  88088. * * upAxis: the up axis of the coordinate system
  88089. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  88090. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  88091. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  88092. * * adjustYaw: used to make an adjustment to the yaw of the bone
  88093. * * adjustPitch: used to make an adjustment to the pitch of the bone
  88094. * * adjustRoll: used to make an adjustment to the roll of the bone
  88095. **/
  88096. function BoneLookController(mesh, bone, target, options) {
  88097. /**
  88098. * The up axis of the coordinate system that is used when the bone is rotated
  88099. */
  88100. this.upAxis = BABYLON.Vector3.Up();
  88101. /**
  88102. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  88103. */
  88104. this.upAxisSpace = BABYLON.Space.LOCAL;
  88105. /**
  88106. * Used to make an adjustment to the yaw of the bone
  88107. */
  88108. this.adjustYaw = 0;
  88109. /**
  88110. * Used to make an adjustment to the pitch of the bone
  88111. */
  88112. this.adjustPitch = 0;
  88113. /**
  88114. * Used to make an adjustment to the roll of the bone
  88115. */
  88116. this.adjustRoll = 0;
  88117. /**
  88118. * 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)
  88119. */
  88120. this.slerpAmount = 1;
  88121. this._boneQuat = BABYLON.Quaternion.Identity();
  88122. this._slerping = false;
  88123. this._firstFrameSkipped = false;
  88124. this._fowardAxis = BABYLON.Vector3.Forward();
  88125. this.mesh = mesh;
  88126. this.bone = bone;
  88127. this.target = target;
  88128. if (options) {
  88129. if (options.adjustYaw) {
  88130. this.adjustYaw = options.adjustYaw;
  88131. }
  88132. if (options.adjustPitch) {
  88133. this.adjustPitch = options.adjustPitch;
  88134. }
  88135. if (options.adjustRoll) {
  88136. this.adjustRoll = options.adjustRoll;
  88137. }
  88138. if (options.maxYaw != null) {
  88139. this.maxYaw = options.maxYaw;
  88140. }
  88141. else {
  88142. this.maxYaw = Math.PI;
  88143. }
  88144. if (options.minYaw != null) {
  88145. this.minYaw = options.minYaw;
  88146. }
  88147. else {
  88148. this.minYaw = -Math.PI;
  88149. }
  88150. if (options.maxPitch != null) {
  88151. this.maxPitch = options.maxPitch;
  88152. }
  88153. else {
  88154. this.maxPitch = Math.PI;
  88155. }
  88156. if (options.minPitch != null) {
  88157. this.minPitch = options.minPitch;
  88158. }
  88159. else {
  88160. this.minPitch = -Math.PI;
  88161. }
  88162. if (options.slerpAmount != null) {
  88163. this.slerpAmount = options.slerpAmount;
  88164. }
  88165. if (options.upAxis != null) {
  88166. this.upAxis = options.upAxis;
  88167. }
  88168. if (options.upAxisSpace != null) {
  88169. this.upAxisSpace = options.upAxisSpace;
  88170. }
  88171. if (options.yawAxis != null || options.pitchAxis != null) {
  88172. var newYawAxis = BABYLON.Axis.Y;
  88173. var newPitchAxis = BABYLON.Axis.X;
  88174. if (options.yawAxis != null) {
  88175. newYawAxis = options.yawAxis.clone();
  88176. newYawAxis.normalize();
  88177. }
  88178. if (options.pitchAxis != null) {
  88179. newPitchAxis = options.pitchAxis.clone();
  88180. newPitchAxis.normalize();
  88181. }
  88182. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  88183. this._transformYawPitch = BABYLON.Matrix.Identity();
  88184. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  88185. this._transformYawPitchInv = this._transformYawPitch.clone();
  88186. this._transformYawPitch.invert();
  88187. }
  88188. }
  88189. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  88190. this.upAxisSpace = BABYLON.Space.LOCAL;
  88191. }
  88192. }
  88193. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  88194. /**
  88195. * Gets or sets the minimum yaw angle that the bone can look to
  88196. */
  88197. get: function () {
  88198. return this._minYaw;
  88199. },
  88200. set: function (value) {
  88201. this._minYaw = value;
  88202. this._minYawSin = Math.sin(value);
  88203. this._minYawCos = Math.cos(value);
  88204. if (this._maxYaw != null) {
  88205. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  88206. this._yawRange = this._maxYaw - this._minYaw;
  88207. }
  88208. },
  88209. enumerable: true,
  88210. configurable: true
  88211. });
  88212. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  88213. /**
  88214. * Gets or sets the maximum yaw angle that the bone can look to
  88215. */
  88216. get: function () {
  88217. return this._maxYaw;
  88218. },
  88219. set: function (value) {
  88220. this._maxYaw = value;
  88221. this._maxYawSin = Math.sin(value);
  88222. this._maxYawCos = Math.cos(value);
  88223. if (this._minYaw != null) {
  88224. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  88225. this._yawRange = this._maxYaw - this._minYaw;
  88226. }
  88227. },
  88228. enumerable: true,
  88229. configurable: true
  88230. });
  88231. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  88232. /**
  88233. * Gets or sets the minimum pitch angle that the bone can look to
  88234. */
  88235. get: function () {
  88236. return this._minPitch;
  88237. },
  88238. set: function (value) {
  88239. this._minPitch = value;
  88240. this._minPitchTan = Math.tan(value);
  88241. },
  88242. enumerable: true,
  88243. configurable: true
  88244. });
  88245. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  88246. /**
  88247. * Gets or sets the maximum pitch angle that the bone can look to
  88248. */
  88249. get: function () {
  88250. return this._maxPitch;
  88251. },
  88252. set: function (value) {
  88253. this._maxPitch = value;
  88254. this._maxPitchTan = Math.tan(value);
  88255. },
  88256. enumerable: true,
  88257. configurable: true
  88258. });
  88259. /**
  88260. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  88261. */
  88262. BoneLookController.prototype.update = function () {
  88263. //skip the first frame when slerping so that the mesh rotation is correct
  88264. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  88265. this._firstFrameSkipped = true;
  88266. return;
  88267. }
  88268. var bone = this.bone;
  88269. var bonePos = BoneLookController._tmpVecs[0];
  88270. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  88271. var target = this.target;
  88272. var _tmpMat1 = BoneLookController._tmpMats[0];
  88273. var _tmpMat2 = BoneLookController._tmpMats[1];
  88274. var mesh = this.mesh;
  88275. var parentBone = bone.getParent();
  88276. var upAxis = BoneLookController._tmpVecs[1];
  88277. upAxis.copyFrom(this.upAxis);
  88278. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  88279. if (this._transformYawPitch) {
  88280. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  88281. }
  88282. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  88283. }
  88284. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  88285. mesh.getDirectionToRef(upAxis, upAxis);
  88286. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  88287. upAxis.normalize();
  88288. }
  88289. }
  88290. var checkYaw = false;
  88291. var checkPitch = false;
  88292. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  88293. checkYaw = true;
  88294. }
  88295. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  88296. checkPitch = true;
  88297. }
  88298. if (checkYaw || checkPitch) {
  88299. var spaceMat = BoneLookController._tmpMats[2];
  88300. var spaceMatInv = BoneLookController._tmpMats[3];
  88301. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  88302. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  88303. }
  88304. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  88305. spaceMat.copyFrom(mesh.getWorldMatrix());
  88306. }
  88307. else {
  88308. var forwardAxis = BoneLookController._tmpVecs[2];
  88309. forwardAxis.copyFrom(this._fowardAxis);
  88310. if (this._transformYawPitch) {
  88311. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  88312. }
  88313. if (parentBone) {
  88314. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  88315. }
  88316. else {
  88317. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  88318. }
  88319. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  88320. rightAxis.normalize();
  88321. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  88322. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  88323. }
  88324. spaceMat.invertToRef(spaceMatInv);
  88325. var xzlen = null;
  88326. if (checkPitch) {
  88327. var localTarget = BoneLookController._tmpVecs[3];
  88328. target.subtractToRef(bonePos, localTarget);
  88329. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  88330. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88331. var pitch = Math.atan2(localTarget.y, xzlen);
  88332. var newPitch = pitch;
  88333. if (pitch > this._maxPitch) {
  88334. localTarget.y = this._maxPitchTan * xzlen;
  88335. newPitch = this._maxPitch;
  88336. }
  88337. else if (pitch < this._minPitch) {
  88338. localTarget.y = this._minPitchTan * xzlen;
  88339. newPitch = this._minPitch;
  88340. }
  88341. if (pitch != newPitch) {
  88342. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  88343. localTarget.addInPlace(bonePos);
  88344. target = localTarget;
  88345. }
  88346. }
  88347. if (checkYaw) {
  88348. var localTarget = BoneLookController._tmpVecs[4];
  88349. target.subtractToRef(bonePos, localTarget);
  88350. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  88351. var yaw = Math.atan2(localTarget.x, localTarget.z);
  88352. var newYaw = yaw;
  88353. if (yaw > this._maxYaw || yaw < this._minYaw) {
  88354. if (xzlen == null) {
  88355. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88356. }
  88357. if (this._yawRange > Math.PI) {
  88358. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  88359. localTarget.z = this._maxYawCos * xzlen;
  88360. localTarget.x = this._maxYawSin * xzlen;
  88361. newYaw = this._maxYaw;
  88362. }
  88363. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  88364. localTarget.z = this._minYawCos * xzlen;
  88365. localTarget.x = this._minYawSin * xzlen;
  88366. newYaw = this._minYaw;
  88367. }
  88368. }
  88369. else {
  88370. if (yaw > this._maxYaw) {
  88371. localTarget.z = this._maxYawCos * xzlen;
  88372. localTarget.x = this._maxYawSin * xzlen;
  88373. newYaw = this._maxYaw;
  88374. }
  88375. else if (yaw < this._minYaw) {
  88376. localTarget.z = this._minYawCos * xzlen;
  88377. localTarget.x = this._minYawSin * xzlen;
  88378. newYaw = this._minYaw;
  88379. }
  88380. }
  88381. }
  88382. if (this._slerping && this._yawRange > Math.PI) {
  88383. //are we going to be crossing into the min/max region?
  88384. var boneFwd = BoneLookController._tmpVecs[8];
  88385. boneFwd.copyFrom(BABYLON.Axis.Z);
  88386. if (this._transformYawPitch) {
  88387. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  88388. }
  88389. var boneRotMat = BoneLookController._tmpMats[4];
  88390. this._boneQuat.toRotationMatrix(boneRotMat);
  88391. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  88392. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  88393. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  88394. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  88395. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  88396. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  88397. if (angBtwTar > angBtwMidYaw) {
  88398. if (xzlen == null) {
  88399. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88400. }
  88401. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  88402. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  88403. if (angBtwMin < angBtwMax) {
  88404. newYaw = boneYaw + Math.PI * .75;
  88405. localTarget.z = Math.cos(newYaw) * xzlen;
  88406. localTarget.x = Math.sin(newYaw) * xzlen;
  88407. }
  88408. else {
  88409. newYaw = boneYaw - Math.PI * .75;
  88410. localTarget.z = Math.cos(newYaw) * xzlen;
  88411. localTarget.x = Math.sin(newYaw) * xzlen;
  88412. }
  88413. }
  88414. }
  88415. if (yaw != newYaw) {
  88416. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  88417. localTarget.addInPlace(bonePos);
  88418. target = localTarget;
  88419. }
  88420. }
  88421. }
  88422. var zaxis = BoneLookController._tmpVecs[5];
  88423. var xaxis = BoneLookController._tmpVecs[6];
  88424. var yaxis = BoneLookController._tmpVecs[7];
  88425. var _tmpQuat = BoneLookController._tmpQuat;
  88426. target.subtractToRef(bonePos, zaxis);
  88427. zaxis.normalize();
  88428. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  88429. xaxis.normalize();
  88430. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  88431. yaxis.normalize();
  88432. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  88433. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  88434. return;
  88435. }
  88436. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  88437. return;
  88438. }
  88439. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  88440. return;
  88441. }
  88442. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  88443. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  88444. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  88445. }
  88446. if (this.slerpAmount < 1) {
  88447. if (!this._slerping) {
  88448. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  88449. }
  88450. if (this._transformYawPitch) {
  88451. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  88452. }
  88453. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  88454. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  88455. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  88456. this._slerping = true;
  88457. }
  88458. else {
  88459. if (this._transformYawPitch) {
  88460. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  88461. }
  88462. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  88463. this._slerping = false;
  88464. }
  88465. };
  88466. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  88467. var angDiff = ang2 - ang1;
  88468. angDiff %= Math.PI * 2;
  88469. if (angDiff > Math.PI) {
  88470. angDiff -= Math.PI * 2;
  88471. }
  88472. else if (angDiff < -Math.PI) {
  88473. angDiff += Math.PI * 2;
  88474. }
  88475. return angDiff;
  88476. };
  88477. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  88478. ang1 %= (2 * Math.PI);
  88479. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  88480. ang2 %= (2 * Math.PI);
  88481. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  88482. var ab = 0;
  88483. if (ang1 < ang2) {
  88484. ab = ang2 - ang1;
  88485. }
  88486. else {
  88487. ab = ang1 - ang2;
  88488. }
  88489. if (ab > Math.PI) {
  88490. ab = Math.PI * 2 - ab;
  88491. }
  88492. return ab;
  88493. };
  88494. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  88495. ang %= (2 * Math.PI);
  88496. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  88497. ang1 %= (2 * Math.PI);
  88498. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  88499. ang2 %= (2 * Math.PI);
  88500. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  88501. if (ang1 < ang2) {
  88502. if (ang > ang1 && ang < ang2) {
  88503. return true;
  88504. }
  88505. }
  88506. else {
  88507. if (ang > ang2 && ang < ang1) {
  88508. return true;
  88509. }
  88510. }
  88511. return false;
  88512. };
  88513. 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()];
  88514. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  88515. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88516. return BoneLookController;
  88517. }());
  88518. BABYLON.BoneLookController = BoneLookController;
  88519. })(BABYLON || (BABYLON = {}));
  88520. //# sourceMappingURL=babylon.boneLookController.js.map
  88521. var BABYLON;
  88522. (function (BABYLON) {
  88523. /**
  88524. * Class used to handle skinning animations
  88525. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  88526. */
  88527. var Skeleton = /** @class */ (function () {
  88528. /**
  88529. * Creates a new skeleton
  88530. * @param name defines the skeleton name
  88531. * @param id defines the skeleton Id
  88532. * @param scene defines the hosting scene
  88533. */
  88534. function Skeleton(
  88535. /** defines the skeleton name */
  88536. name,
  88537. /** defines the skeleton Id */
  88538. id, scene) {
  88539. this.name = name;
  88540. this.id = id;
  88541. /**
  88542. * Gets the list of child bones
  88543. */
  88544. this.bones = new Array();
  88545. /**
  88546. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  88547. */
  88548. this.needInitialSkinMatrix = false;
  88549. this._isDirty = true;
  88550. this._meshesWithPoseMatrix = new Array();
  88551. this._identity = BABYLON.Matrix.Identity();
  88552. this._ranges = {};
  88553. this._lastAbsoluteTransformsUpdateId = -1;
  88554. /**
  88555. * Specifies if the skeleton should be serialized
  88556. */
  88557. this.doNotSerialize = false;
  88558. this._animationPropertiesOverride = null;
  88559. // Events
  88560. /**
  88561. * An observable triggered before computing the skeleton's matrices
  88562. */
  88563. this.onBeforeComputeObservable = new BABYLON.Observable();
  88564. this.bones = [];
  88565. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88566. scene.skeletons.push(this);
  88567. //make sure it will recalculate the matrix next time prepare is called.
  88568. this._isDirty = true;
  88569. }
  88570. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  88571. /**
  88572. * Gets or sets the animation properties override
  88573. */
  88574. get: function () {
  88575. if (!this._animationPropertiesOverride) {
  88576. return this._scene.animationPropertiesOverride;
  88577. }
  88578. return this._animationPropertiesOverride;
  88579. },
  88580. set: function (value) {
  88581. this._animationPropertiesOverride = value;
  88582. },
  88583. enumerable: true,
  88584. configurable: true
  88585. });
  88586. // Members
  88587. /**
  88588. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  88589. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  88590. * @returns a Float32Array containing matrices data
  88591. */
  88592. Skeleton.prototype.getTransformMatrices = function (mesh) {
  88593. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  88594. return mesh._bonesTransformMatrices;
  88595. }
  88596. if (!this._transformMatrices) {
  88597. this.prepare();
  88598. }
  88599. return this._transformMatrices;
  88600. };
  88601. /**
  88602. * Gets the current hosting scene
  88603. * @returns a scene object
  88604. */
  88605. Skeleton.prototype.getScene = function () {
  88606. return this._scene;
  88607. };
  88608. // Methods
  88609. /**
  88610. * Gets a string representing the current skeleton data
  88611. * @param fullDetails defines a boolean indicating if we want a verbose version
  88612. * @returns a string representing the current skeleton data
  88613. */
  88614. Skeleton.prototype.toString = function (fullDetails) {
  88615. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  88616. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  88617. if (fullDetails) {
  88618. ret += ", Ranges: {";
  88619. var first = true;
  88620. for (var name_1 in this._ranges) {
  88621. if (first) {
  88622. ret += ", ";
  88623. first = false;
  88624. }
  88625. ret += name_1;
  88626. }
  88627. ret += "}";
  88628. }
  88629. return ret;
  88630. };
  88631. /**
  88632. * Get bone's index searching by name
  88633. * @param name defines bone's name to search for
  88634. * @return the indice of the bone. Returns -1 if not found
  88635. */
  88636. Skeleton.prototype.getBoneIndexByName = function (name) {
  88637. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  88638. if (this.bones[boneIndex].name === name) {
  88639. return boneIndex;
  88640. }
  88641. }
  88642. return -1;
  88643. };
  88644. /**
  88645. * Creater a new animation range
  88646. * @param name defines the name of the range
  88647. * @param from defines the start key
  88648. * @param to defines the end key
  88649. */
  88650. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  88651. // check name not already in use
  88652. if (!this._ranges[name]) {
  88653. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  88654. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88655. if (this.bones[i].animations[0]) {
  88656. this.bones[i].animations[0].createRange(name, from, to);
  88657. }
  88658. }
  88659. }
  88660. };
  88661. /**
  88662. * Delete a specific animation range
  88663. * @param name defines the name of the range
  88664. * @param deleteFrames defines if frames must be removed as well
  88665. */
  88666. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  88667. if (deleteFrames === void 0) { deleteFrames = true; }
  88668. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88669. if (this.bones[i].animations[0]) {
  88670. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  88671. }
  88672. }
  88673. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  88674. };
  88675. /**
  88676. * Gets a specific animation range
  88677. * @param name defines the name of the range to look for
  88678. * @returns the requested animation range or null if not found
  88679. */
  88680. Skeleton.prototype.getAnimationRange = function (name) {
  88681. return this._ranges[name];
  88682. };
  88683. /**
  88684. * Gets the list of all animation ranges defined on this skeleton
  88685. * @returns an array
  88686. */
  88687. Skeleton.prototype.getAnimationRanges = function () {
  88688. var animationRanges = [];
  88689. var name;
  88690. var i = 0;
  88691. for (name in this._ranges) {
  88692. animationRanges[i] = this._ranges[name];
  88693. i++;
  88694. }
  88695. return animationRanges;
  88696. };
  88697. /**
  88698. * Copy animation range from a source skeleton.
  88699. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  88700. * @param source defines the source skeleton
  88701. * @param name defines the name of the range to copy
  88702. * @param rescaleAsRequired defines if rescaling must be applied if required
  88703. * @returns true if operation was successful
  88704. */
  88705. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  88706. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  88707. if (this._ranges[name] || !source.getAnimationRange(name)) {
  88708. return false;
  88709. }
  88710. var ret = true;
  88711. var frameOffset = this._getHighestAnimationFrame() + 1;
  88712. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  88713. var boneDict = {};
  88714. var sourceBones = source.bones;
  88715. var nBones;
  88716. var i;
  88717. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  88718. boneDict[sourceBones[i].name] = sourceBones[i];
  88719. }
  88720. if (this.bones.length !== sourceBones.length) {
  88721. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  88722. ret = false;
  88723. }
  88724. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  88725. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  88726. var boneName = this.bones[i].name;
  88727. var sourceBone = boneDict[boneName];
  88728. if (sourceBone) {
  88729. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  88730. }
  88731. else {
  88732. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  88733. ret = false;
  88734. }
  88735. }
  88736. // do not call createAnimationRange(), since it also is done to bones, which was already done
  88737. var range = source.getAnimationRange(name);
  88738. if (range) {
  88739. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  88740. }
  88741. return ret;
  88742. };
  88743. /**
  88744. * Forces the skeleton to go to rest pose
  88745. */
  88746. Skeleton.prototype.returnToRest = function () {
  88747. for (var index = 0; index < this.bones.length; index++) {
  88748. this.bones[index].returnToRest();
  88749. }
  88750. };
  88751. Skeleton.prototype._getHighestAnimationFrame = function () {
  88752. var ret = 0;
  88753. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88754. if (this.bones[i].animations[0]) {
  88755. var highest = this.bones[i].animations[0].getHighestFrame();
  88756. if (ret < highest) {
  88757. ret = highest;
  88758. }
  88759. }
  88760. }
  88761. return ret;
  88762. };
  88763. /**
  88764. * Begin a specific animation range
  88765. * @param name defines the name of the range to start
  88766. * @param loop defines if looping must be turned on (false by default)
  88767. * @param speedRatio defines the speed ratio to apply (1 by default)
  88768. * @param onAnimationEnd defines a callback which will be called when animation will end
  88769. * @returns a new animatable
  88770. */
  88771. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  88772. var range = this.getAnimationRange(name);
  88773. if (!range) {
  88774. return null;
  88775. }
  88776. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  88777. };
  88778. /** @hidden */
  88779. Skeleton.prototype._markAsDirty = function () {
  88780. this._isDirty = true;
  88781. };
  88782. /** @hidden */
  88783. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  88784. this._meshesWithPoseMatrix.push(mesh);
  88785. };
  88786. /** @hidden */
  88787. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  88788. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  88789. if (index > -1) {
  88790. this._meshesWithPoseMatrix.splice(index, 1);
  88791. }
  88792. };
  88793. /** @hidden */
  88794. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  88795. this.onBeforeComputeObservable.notifyObservers(this);
  88796. for (var index = 0; index < this.bones.length; index++) {
  88797. var bone = this.bones[index];
  88798. var parentBone = bone.getParent();
  88799. if (parentBone) {
  88800. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  88801. }
  88802. else {
  88803. if (initialSkinMatrix) {
  88804. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  88805. }
  88806. else {
  88807. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  88808. }
  88809. }
  88810. if (bone._index !== -1) {
  88811. var mappedIndex = bone._index === null ? index : bone._index;
  88812. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  88813. }
  88814. }
  88815. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  88816. };
  88817. /**
  88818. * Build all resources required to render a skeleton
  88819. */
  88820. Skeleton.prototype.prepare = function () {
  88821. if (!this._isDirty) {
  88822. return;
  88823. }
  88824. if (this.needInitialSkinMatrix) {
  88825. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  88826. var mesh = this._meshesWithPoseMatrix[index];
  88827. var poseMatrix = mesh.getPoseMatrix();
  88828. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  88829. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  88830. }
  88831. if (this._synchronizedWithMesh !== mesh) {
  88832. this._synchronizedWithMesh = mesh;
  88833. // Prepare bones
  88834. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  88835. var bone = this.bones[boneIndex];
  88836. if (!bone.getParent()) {
  88837. var matrix = bone.getBaseMatrix();
  88838. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  88839. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  88840. }
  88841. }
  88842. }
  88843. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  88844. }
  88845. }
  88846. else {
  88847. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  88848. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  88849. }
  88850. this._computeTransformMatrices(this._transformMatrices, null);
  88851. }
  88852. this._isDirty = false;
  88853. this._scene._activeBones.addCount(this.bones.length, false);
  88854. };
  88855. /**
  88856. * Gets the list of animatables currently running for this skeleton
  88857. * @returns an array of animatables
  88858. */
  88859. Skeleton.prototype.getAnimatables = function () {
  88860. if (!this._animatables || this._animatables.length !== this.bones.length) {
  88861. this._animatables = [];
  88862. for (var index = 0; index < this.bones.length; index++) {
  88863. this._animatables.push(this.bones[index]);
  88864. }
  88865. }
  88866. return this._animatables;
  88867. };
  88868. /**
  88869. * Clone the current skeleton
  88870. * @param name defines the name of the new skeleton
  88871. * @param id defines the id of the enw skeleton
  88872. * @returns the new skeleton
  88873. */
  88874. Skeleton.prototype.clone = function (name, id) {
  88875. var result = new Skeleton(name, id || name, this._scene);
  88876. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88877. for (var index = 0; index < this.bones.length; index++) {
  88878. var source = this.bones[index];
  88879. var parentBone = null;
  88880. var parent_1 = source.getParent();
  88881. if (parent_1) {
  88882. var parentIndex = this.bones.indexOf(parent_1);
  88883. parentBone = result.bones[parentIndex];
  88884. }
  88885. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  88886. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  88887. }
  88888. if (this._ranges) {
  88889. result._ranges = {};
  88890. for (var rangeName in this._ranges) {
  88891. var range = this._ranges[rangeName];
  88892. if (range) {
  88893. result._ranges[rangeName] = range.clone();
  88894. }
  88895. }
  88896. }
  88897. this._isDirty = true;
  88898. return result;
  88899. };
  88900. /**
  88901. * Enable animation blending for this skeleton
  88902. * @param blendingSpeed defines the blending speed to apply
  88903. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  88904. */
  88905. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  88906. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  88907. this.bones.forEach(function (bone) {
  88908. bone.animations.forEach(function (animation) {
  88909. animation.enableBlending = true;
  88910. animation.blendingSpeed = blendingSpeed;
  88911. });
  88912. });
  88913. };
  88914. /**
  88915. * Releases all resources associated with the current skeleton
  88916. */
  88917. Skeleton.prototype.dispose = function () {
  88918. this._meshesWithPoseMatrix = [];
  88919. // Animations
  88920. this.getScene().stopAnimation(this);
  88921. // Remove from scene
  88922. this.getScene().removeSkeleton(this);
  88923. };
  88924. /**
  88925. * Serialize the skeleton in a JSON object
  88926. * @returns a JSON object
  88927. */
  88928. Skeleton.prototype.serialize = function () {
  88929. var serializationObject = {};
  88930. serializationObject.name = this.name;
  88931. serializationObject.id = this.id;
  88932. if (this.dimensionsAtRest) {
  88933. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  88934. }
  88935. serializationObject.bones = [];
  88936. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88937. for (var index = 0; index < this.bones.length; index++) {
  88938. var bone = this.bones[index];
  88939. var parent_2 = bone.getParent();
  88940. var serializedBone = {
  88941. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  88942. name: bone.name,
  88943. matrix: bone.getBaseMatrix().toArray(),
  88944. rest: bone.getRestPose().toArray()
  88945. };
  88946. serializationObject.bones.push(serializedBone);
  88947. if (bone.length) {
  88948. serializedBone.length = bone.length;
  88949. }
  88950. if (bone.metadata) {
  88951. serializedBone.metadata = bone.metadata;
  88952. }
  88953. if (bone.animations && bone.animations.length > 0) {
  88954. serializedBone.animation = bone.animations[0].serialize();
  88955. }
  88956. serializationObject.ranges = [];
  88957. for (var name in this._ranges) {
  88958. var source = this._ranges[name];
  88959. if (!source) {
  88960. continue;
  88961. }
  88962. var range = {};
  88963. range.name = name;
  88964. range.from = source.from;
  88965. range.to = source.to;
  88966. serializationObject.ranges.push(range);
  88967. }
  88968. }
  88969. return serializationObject;
  88970. };
  88971. /**
  88972. * Creates a new skeleton from serialized data
  88973. * @param parsedSkeleton defines the serialized data
  88974. * @param scene defines the hosting scene
  88975. * @returns a new skeleton
  88976. */
  88977. Skeleton.Parse = function (parsedSkeleton, scene) {
  88978. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  88979. if (parsedSkeleton.dimensionsAtRest) {
  88980. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  88981. }
  88982. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  88983. var index;
  88984. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  88985. var parsedBone = parsedSkeleton.bones[index];
  88986. var parentBone = null;
  88987. if (parsedBone.parentBoneIndex > -1) {
  88988. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  88989. }
  88990. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  88991. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  88992. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  88993. bone.id = parsedBone.id;
  88994. }
  88995. if (parsedBone.length) {
  88996. bone.length = parsedBone.length;
  88997. }
  88998. if (parsedBone.metadata) {
  88999. bone.metadata = parsedBone.metadata;
  89000. }
  89001. if (parsedBone.animation) {
  89002. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  89003. }
  89004. }
  89005. // placed after bones, so createAnimationRange can cascade down
  89006. if (parsedSkeleton.ranges) {
  89007. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  89008. var data = parsedSkeleton.ranges[index];
  89009. skeleton.createAnimationRange(data.name, data.from, data.to);
  89010. }
  89011. }
  89012. return skeleton;
  89013. };
  89014. /**
  89015. * Compute all node absolute transforms
  89016. * @param forceUpdate defines if computation must be done even if cache is up to date
  89017. */
  89018. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  89019. if (forceUpdate === void 0) { forceUpdate = false; }
  89020. var renderId = this._scene.getRenderId();
  89021. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  89022. this.bones[0].computeAbsoluteTransforms();
  89023. this._lastAbsoluteTransformsUpdateId = renderId;
  89024. }
  89025. };
  89026. /**
  89027. * Gets the root pose matrix
  89028. * @returns a matrix
  89029. */
  89030. Skeleton.prototype.getPoseMatrix = function () {
  89031. var poseMatrix = null;
  89032. if (this._meshesWithPoseMatrix.length > 0) {
  89033. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  89034. }
  89035. return poseMatrix;
  89036. };
  89037. /**
  89038. * Sorts bones per internal index
  89039. */
  89040. Skeleton.prototype.sortBones = function () {
  89041. var bones = new Array();
  89042. var visited = new Array(this.bones.length);
  89043. for (var index = 0; index < this.bones.length; index++) {
  89044. this._sortBones(index, bones, visited);
  89045. }
  89046. this.bones = bones;
  89047. };
  89048. Skeleton.prototype._sortBones = function (index, bones, visited) {
  89049. if (visited[index]) {
  89050. return;
  89051. }
  89052. visited[index] = true;
  89053. var bone = this.bones[index];
  89054. if (bone._index === undefined) {
  89055. bone._index = index;
  89056. }
  89057. var parentBone = bone.getParent();
  89058. if (parentBone) {
  89059. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  89060. }
  89061. bones.push(bone);
  89062. };
  89063. return Skeleton;
  89064. }());
  89065. BABYLON.Skeleton = Skeleton;
  89066. })(BABYLON || (BABYLON = {}));
  89067. //# sourceMappingURL=babylon.skeleton.js.map
  89068. var BABYLON;
  89069. (function (BABYLON) {
  89070. ;
  89071. /**
  89072. * This groups tools to convert HDR texture to native colors array.
  89073. */
  89074. var HDRTools = /** @class */ (function () {
  89075. function HDRTools() {
  89076. }
  89077. HDRTools.Ldexp = function (mantissa, exponent) {
  89078. if (exponent > 1023) {
  89079. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  89080. }
  89081. if (exponent < -1074) {
  89082. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  89083. }
  89084. return mantissa * Math.pow(2, exponent);
  89085. };
  89086. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  89087. if (exponent > 0) { /*nonzero pixel*/
  89088. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  89089. float32array[index + 0] = red * exponent;
  89090. float32array[index + 1] = green * exponent;
  89091. float32array[index + 2] = blue * exponent;
  89092. }
  89093. else {
  89094. float32array[index + 0] = 0;
  89095. float32array[index + 1] = 0;
  89096. float32array[index + 2] = 0;
  89097. }
  89098. };
  89099. HDRTools.readStringLine = function (uint8array, startIndex) {
  89100. var line = "";
  89101. var character = "";
  89102. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  89103. character = String.fromCharCode(uint8array[i]);
  89104. if (character == "\n") {
  89105. break;
  89106. }
  89107. line += character;
  89108. }
  89109. return line;
  89110. };
  89111. /**
  89112. * Reads header information from an RGBE texture stored in a native array.
  89113. * More information on this format are available here:
  89114. * https://en.wikipedia.org/wiki/RGBE_image_format
  89115. *
  89116. * @param uint8array The binary file stored in native array.
  89117. * @return The header information.
  89118. */
  89119. HDRTools.RGBE_ReadHeader = function (uint8array) {
  89120. var height = 0;
  89121. var width = 0;
  89122. var line = this.readStringLine(uint8array, 0);
  89123. if (line[0] != '#' || line[1] != '?') {
  89124. throw "Bad HDR Format.";
  89125. }
  89126. var endOfHeader = false;
  89127. var findFormat = false;
  89128. var lineIndex = 0;
  89129. do {
  89130. lineIndex += (line.length + 1);
  89131. line = this.readStringLine(uint8array, lineIndex);
  89132. if (line == "FORMAT=32-bit_rle_rgbe") {
  89133. findFormat = true;
  89134. }
  89135. else if (line.length == 0) {
  89136. endOfHeader = true;
  89137. }
  89138. } while (!endOfHeader);
  89139. if (!findFormat) {
  89140. throw "HDR Bad header format, unsupported FORMAT";
  89141. }
  89142. lineIndex += (line.length + 1);
  89143. line = this.readStringLine(uint8array, lineIndex);
  89144. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  89145. var match = sizeRegexp.exec(line);
  89146. // TODO. Support +Y and -X if needed.
  89147. if (!match || match.length < 3) {
  89148. throw "HDR Bad header format, no size";
  89149. }
  89150. width = parseInt(match[2]);
  89151. height = parseInt(match[1]);
  89152. if (width < 8 || width > 0x7fff) {
  89153. throw "HDR Bad header format, unsupported size";
  89154. }
  89155. lineIndex += (line.length + 1);
  89156. return {
  89157. height: height,
  89158. width: width,
  89159. dataPosition: lineIndex
  89160. };
  89161. };
  89162. /**
  89163. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  89164. * This RGBE texture needs to store the information as a panorama.
  89165. *
  89166. * More information on this format are available here:
  89167. * https://en.wikipedia.org/wiki/RGBE_image_format
  89168. *
  89169. * @param buffer The binary file stored in an array buffer.
  89170. * @param size The expected size of the extracted cubemap.
  89171. * @return The Cube Map information.
  89172. */
  89173. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  89174. var uint8array = new Uint8Array(buffer);
  89175. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  89176. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  89177. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  89178. return cubeMapData;
  89179. };
  89180. /**
  89181. * Returns the pixels data extracted from an RGBE texture.
  89182. * This pixels will be stored left to right up to down in the R G B order in one array.
  89183. *
  89184. * More information on this format are available here:
  89185. * https://en.wikipedia.org/wiki/RGBE_image_format
  89186. *
  89187. * @param uint8array The binary file stored in an array buffer.
  89188. * @param hdrInfo The header information of the file.
  89189. * @return The pixels data in RGB right to left up to down order.
  89190. */
  89191. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  89192. // Keep for multi format supports.
  89193. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  89194. };
  89195. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  89196. var num_scanlines = hdrInfo.height;
  89197. var scanline_width = hdrInfo.width;
  89198. var a, b, c, d, count;
  89199. var dataIndex = hdrInfo.dataPosition;
  89200. var index = 0, endIndex = 0, i = 0;
  89201. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  89202. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  89203. // 3 channels of 4 bytes per pixel in float.
  89204. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  89205. var resultArray = new Float32Array(resultBuffer);
  89206. // read in each successive scanline
  89207. while (num_scanlines > 0) {
  89208. a = uint8array[dataIndex++];
  89209. b = uint8array[dataIndex++];
  89210. c = uint8array[dataIndex++];
  89211. d = uint8array[dataIndex++];
  89212. if (a != 2 || b != 2 || (c & 0x80)) {
  89213. // this file is not run length encoded
  89214. throw "HDR Bad header format, not RLE";
  89215. }
  89216. if (((c << 8) | d) != scanline_width) {
  89217. throw "HDR Bad header format, wrong scan line width";
  89218. }
  89219. index = 0;
  89220. // read each of the four channels for the scanline into the buffer
  89221. for (i = 0; i < 4; i++) {
  89222. endIndex = (i + 1) * scanline_width;
  89223. while (index < endIndex) {
  89224. a = uint8array[dataIndex++];
  89225. b = uint8array[dataIndex++];
  89226. if (a > 128) {
  89227. // a run of the same value
  89228. count = a - 128;
  89229. if ((count == 0) || (count > endIndex - index)) {
  89230. throw "HDR Bad Format, bad scanline data (run)";
  89231. }
  89232. while (count-- > 0) {
  89233. scanLineArray[index++] = b;
  89234. }
  89235. }
  89236. else {
  89237. // a non-run
  89238. count = a;
  89239. if ((count == 0) || (count > endIndex - index)) {
  89240. throw "HDR Bad Format, bad scanline data (non-run)";
  89241. }
  89242. scanLineArray[index++] = b;
  89243. if (--count > 0) {
  89244. for (var j = 0; j < count; j++) {
  89245. scanLineArray[index++] = uint8array[dataIndex++];
  89246. }
  89247. }
  89248. }
  89249. }
  89250. }
  89251. // now convert data from buffer into floats
  89252. for (i = 0; i < scanline_width; i++) {
  89253. a = scanLineArray[i];
  89254. b = scanLineArray[i + scanline_width];
  89255. c = scanLineArray[i + 2 * scanline_width];
  89256. d = scanLineArray[i + 3 * scanline_width];
  89257. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  89258. }
  89259. num_scanlines--;
  89260. }
  89261. return resultArray;
  89262. };
  89263. return HDRTools;
  89264. }());
  89265. BABYLON.HDRTools = HDRTools;
  89266. })(BABYLON || (BABYLON = {}));
  89267. //# sourceMappingURL=babylon.hdr.js.map
  89268. var BABYLON;
  89269. (function (BABYLON) {
  89270. /**
  89271. * This represents a texture coming from an HDR input.
  89272. *
  89273. * The only supported format is currently panorama picture stored in RGBE format.
  89274. * Example of such files can be found on HDRLib: http://hdrlib.com/
  89275. */
  89276. var HDRCubeTexture = /** @class */ (function (_super) {
  89277. __extends(HDRCubeTexture, _super);
  89278. /**
  89279. * Instantiates an HDRTexture from the following parameters.
  89280. *
  89281. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  89282. * @param scene The scene the texture will be used in
  89283. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  89284. * @param noMipmap Forces to not generate the mipmap if true
  89285. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  89286. * @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)
  89287. * @param reserved Reserved flag for internal use.
  89288. */
  89289. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  89290. if (noMipmap === void 0) { noMipmap = false; }
  89291. if (generateHarmonics === void 0) { generateHarmonics = true; }
  89292. if (gammaSpace === void 0) { gammaSpace = false; }
  89293. if (reserved === void 0) { reserved = false; }
  89294. if (onLoad === void 0) { onLoad = null; }
  89295. if (onError === void 0) { onError = null; }
  89296. var _this = _super.call(this, scene) || this;
  89297. _this._generateHarmonics = true;
  89298. _this._onLoad = null;
  89299. _this._onError = null;
  89300. /**
  89301. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  89302. */
  89303. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  89304. _this._isBlocking = true;
  89305. _this._rotationY = 0;
  89306. /**
  89307. * Gets or sets the center of the bounding box associated with the cube texture
  89308. * It must define where the camera used to render the texture was set
  89309. */
  89310. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  89311. if (!url) {
  89312. return _this;
  89313. }
  89314. _this.name = url;
  89315. _this.url = url;
  89316. _this.hasAlpha = false;
  89317. _this.isCube = true;
  89318. _this._textureMatrix = BABYLON.Matrix.Identity();
  89319. _this._onLoad = onLoad;
  89320. _this._onError = onError;
  89321. _this.gammaSpace = gammaSpace;
  89322. _this._noMipmap = noMipmap;
  89323. _this._size = size;
  89324. _this._texture = _this._getFromCache(url, _this._noMipmap);
  89325. if (!_this._texture) {
  89326. if (!scene.useDelayedTextureLoading) {
  89327. _this.loadTexture();
  89328. }
  89329. else {
  89330. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  89331. }
  89332. }
  89333. return _this;
  89334. }
  89335. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  89336. /**
  89337. * Gets wether or not the texture is blocking during loading.
  89338. */
  89339. get: function () {
  89340. return this._isBlocking;
  89341. },
  89342. /**
  89343. * Sets wether or not the texture is blocking during loading.
  89344. */
  89345. set: function (value) {
  89346. this._isBlocking = value;
  89347. },
  89348. enumerable: true,
  89349. configurable: true
  89350. });
  89351. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  89352. /**
  89353. * Gets texture matrix rotation angle around Y axis radians.
  89354. */
  89355. get: function () {
  89356. return this._rotationY;
  89357. },
  89358. /**
  89359. * Sets texture matrix rotation angle around Y axis in radians.
  89360. */
  89361. set: function (value) {
  89362. this._rotationY = value;
  89363. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  89364. },
  89365. enumerable: true,
  89366. configurable: true
  89367. });
  89368. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  89369. get: function () {
  89370. return this._boundingBoxSize;
  89371. },
  89372. /**
  89373. * Gets or sets the size of the bounding box associated with the cube texture
  89374. * When defined, the cubemap will switch to local mode
  89375. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  89376. * @example https://www.babylonjs-playground.com/#RNASML
  89377. */
  89378. set: function (value) {
  89379. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  89380. return;
  89381. }
  89382. this._boundingBoxSize = value;
  89383. var scene = this.getScene();
  89384. if (scene) {
  89385. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  89386. }
  89387. },
  89388. enumerable: true,
  89389. configurable: true
  89390. });
  89391. /**
  89392. * Occurs when the file is raw .hdr file.
  89393. */
  89394. HDRCubeTexture.prototype.loadTexture = function () {
  89395. var _this = this;
  89396. var callback = function (buffer) {
  89397. _this.lodGenerationOffset = 0.0;
  89398. _this.lodGenerationScale = 0.8;
  89399. var scene = _this.getScene();
  89400. if (!scene) {
  89401. return null;
  89402. }
  89403. // Extract the raw linear data.
  89404. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  89405. // Generate harmonics if needed.
  89406. if (_this._generateHarmonics) {
  89407. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  89408. _this.sphericalPolynomial = sphericalPolynomial;
  89409. }
  89410. var results = [];
  89411. var byteArray = null;
  89412. // Push each faces.
  89413. for (var j = 0; j < 6; j++) {
  89414. // Create uintarray fallback.
  89415. if (!scene.getEngine().getCaps().textureFloat) {
  89416. // 3 channels of 1 bytes per pixel in bytes.
  89417. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  89418. byteArray = new Uint8Array(byteBuffer);
  89419. }
  89420. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  89421. // If special cases.
  89422. if (_this.gammaSpace || byteArray) {
  89423. for (var i = 0; i < _this._size * _this._size; i++) {
  89424. // Put in gamma space if requested.
  89425. if (_this.gammaSpace) {
  89426. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  89427. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  89428. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  89429. }
  89430. // Convert to int texture for fallback.
  89431. if (byteArray) {
  89432. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  89433. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  89434. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  89435. // May use luminance instead if the result is not accurate.
  89436. var max = Math.max(Math.max(r, g), b);
  89437. if (max > 255) {
  89438. var scale = 255 / max;
  89439. r *= scale;
  89440. g *= scale;
  89441. b *= scale;
  89442. }
  89443. byteArray[(i * 3) + 0] = r;
  89444. byteArray[(i * 3) + 1] = g;
  89445. byteArray[(i * 3) + 2] = b;
  89446. }
  89447. }
  89448. }
  89449. if (byteArray) {
  89450. results.push(byteArray);
  89451. }
  89452. else {
  89453. results.push(dataFace);
  89454. }
  89455. }
  89456. return results;
  89457. };
  89458. var scene = this.getScene();
  89459. if (scene) {
  89460. 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);
  89461. }
  89462. };
  89463. HDRCubeTexture.prototype.clone = function () {
  89464. var scene = this.getScene();
  89465. if (!scene) {
  89466. return this;
  89467. }
  89468. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  89469. // Base texture
  89470. newTexture.level = this.level;
  89471. newTexture.wrapU = this.wrapU;
  89472. newTexture.wrapV = this.wrapV;
  89473. newTexture.coordinatesIndex = this.coordinatesIndex;
  89474. newTexture.coordinatesMode = this.coordinatesMode;
  89475. return newTexture;
  89476. };
  89477. // Methods
  89478. HDRCubeTexture.prototype.delayLoad = function () {
  89479. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  89480. return;
  89481. }
  89482. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  89483. this._texture = this._getFromCache(this.url, this._noMipmap);
  89484. if (!this._texture) {
  89485. this.loadTexture();
  89486. }
  89487. };
  89488. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  89489. return this._textureMatrix;
  89490. };
  89491. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  89492. this._textureMatrix = value;
  89493. };
  89494. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  89495. var texture = null;
  89496. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  89497. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  89498. texture.name = parsedTexture.name;
  89499. texture.hasAlpha = parsedTexture.hasAlpha;
  89500. texture.level = parsedTexture.level;
  89501. texture.coordinatesMode = parsedTexture.coordinatesMode;
  89502. texture.isBlocking = parsedTexture.isBlocking;
  89503. }
  89504. if (texture) {
  89505. if (parsedTexture.boundingBoxPosition) {
  89506. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  89507. }
  89508. if (parsedTexture.boundingBoxSize) {
  89509. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  89510. }
  89511. if (parsedTexture.rotationY) {
  89512. texture.rotationY = parsedTexture.rotationY;
  89513. }
  89514. }
  89515. return texture;
  89516. };
  89517. HDRCubeTexture.prototype.serialize = function () {
  89518. if (!this.name) {
  89519. return null;
  89520. }
  89521. var serializationObject = {};
  89522. serializationObject.name = this.name;
  89523. serializationObject.hasAlpha = this.hasAlpha;
  89524. serializationObject.isCube = true;
  89525. serializationObject.level = this.level;
  89526. serializationObject.size = this._size;
  89527. serializationObject.coordinatesMode = this.coordinatesMode;
  89528. serializationObject.useInGammaSpace = this.gammaSpace;
  89529. serializationObject.generateHarmonics = this._generateHarmonics;
  89530. serializationObject.customType = "BABYLON.HDRCubeTexture";
  89531. serializationObject.noMipmap = this._noMipmap;
  89532. serializationObject.isBlocking = this._isBlocking;
  89533. serializationObject.rotationY = this._rotationY;
  89534. return serializationObject;
  89535. };
  89536. HDRCubeTexture._facesMapping = [
  89537. "right",
  89538. "left",
  89539. "up",
  89540. "down",
  89541. "front",
  89542. "back"
  89543. ];
  89544. return HDRCubeTexture;
  89545. }(BABYLON.BaseTexture));
  89546. BABYLON.HDRCubeTexture = HDRCubeTexture;
  89547. })(BABYLON || (BABYLON = {}));
  89548. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  89549. var BABYLON;
  89550. (function (BABYLON) {
  89551. /**
  89552. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  89553. */
  89554. var PanoramaToCubeMapTools = /** @class */ (function () {
  89555. function PanoramaToCubeMapTools() {
  89556. }
  89557. /**
  89558. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  89559. *
  89560. * @param float32Array The source data.
  89561. * @param inputWidth The width of the input panorama.
  89562. * @param inputhHeight The height of the input panorama.
  89563. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  89564. * @return The cubemap data
  89565. */
  89566. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  89567. if (!float32Array) {
  89568. throw "ConvertPanoramaToCubemap: input cannot be null";
  89569. }
  89570. if (float32Array.length != inputWidth * inputHeight * 3) {
  89571. throw "ConvertPanoramaToCubemap: input size is wrong";
  89572. }
  89573. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  89574. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  89575. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  89576. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  89577. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  89578. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  89579. return {
  89580. front: textureFront,
  89581. back: textureBack,
  89582. left: textureLeft,
  89583. right: textureRight,
  89584. up: textureUp,
  89585. down: textureDown,
  89586. size: size,
  89587. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89588. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  89589. gammaSpace: false,
  89590. };
  89591. };
  89592. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  89593. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  89594. var textureArray = new Float32Array(buffer);
  89595. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  89596. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  89597. var dy = 1 / texSize;
  89598. var fy = 0;
  89599. for (var y = 0; y < texSize; y++) {
  89600. var xv1 = faceData[0];
  89601. var xv2 = faceData[2];
  89602. for (var x = 0; x < texSize; x++) {
  89603. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  89604. v.normalize();
  89605. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  89606. // 3 channels per pixels
  89607. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  89608. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  89609. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  89610. xv1 = xv1.add(rotDX1);
  89611. xv2 = xv2.add(rotDX2);
  89612. }
  89613. fy += dy;
  89614. }
  89615. return textureArray;
  89616. };
  89617. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  89618. var theta = Math.atan2(vDir.z, vDir.x);
  89619. var phi = Math.acos(vDir.y);
  89620. while (theta < -Math.PI)
  89621. theta += 2 * Math.PI;
  89622. while (theta > Math.PI)
  89623. theta -= 2 * Math.PI;
  89624. var dx = theta / Math.PI;
  89625. var dy = phi / Math.PI;
  89626. // recenter.
  89627. dx = dx * 0.5 + 0.5;
  89628. var px = Math.round(dx * inputWidth);
  89629. if (px < 0)
  89630. px = 0;
  89631. else if (px >= inputWidth)
  89632. px = inputWidth - 1;
  89633. var py = Math.round(dy * inputHeight);
  89634. if (py < 0)
  89635. py = 0;
  89636. else if (py >= inputHeight)
  89637. py = inputHeight - 1;
  89638. var inputY = (inputHeight - py - 1);
  89639. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  89640. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  89641. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  89642. return {
  89643. r: r,
  89644. g: g,
  89645. b: b
  89646. };
  89647. };
  89648. PanoramaToCubeMapTools.FACE_FRONT = [
  89649. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  89650. new BABYLON.Vector3(1.0, -1.0, -1.0),
  89651. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  89652. new BABYLON.Vector3(1.0, 1.0, -1.0)
  89653. ];
  89654. PanoramaToCubeMapTools.FACE_BACK = [
  89655. new BABYLON.Vector3(1.0, -1.0, 1.0),
  89656. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  89657. new BABYLON.Vector3(1.0, 1.0, 1.0),
  89658. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  89659. ];
  89660. PanoramaToCubeMapTools.FACE_RIGHT = [
  89661. new BABYLON.Vector3(1.0, -1.0, -1.0),
  89662. new BABYLON.Vector3(1.0, -1.0, 1.0),
  89663. new BABYLON.Vector3(1.0, 1.0, -1.0),
  89664. new BABYLON.Vector3(1.0, 1.0, 1.0)
  89665. ];
  89666. PanoramaToCubeMapTools.FACE_LEFT = [
  89667. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  89668. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  89669. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  89670. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  89671. ];
  89672. PanoramaToCubeMapTools.FACE_DOWN = [
  89673. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  89674. new BABYLON.Vector3(1.0, 1.0, -1.0),
  89675. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  89676. new BABYLON.Vector3(1.0, 1.0, 1.0)
  89677. ];
  89678. PanoramaToCubeMapTools.FACE_UP = [
  89679. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  89680. new BABYLON.Vector3(1.0, -1.0, 1.0),
  89681. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  89682. new BABYLON.Vector3(1.0, -1.0, -1.0)
  89683. ];
  89684. return PanoramaToCubeMapTools;
  89685. }());
  89686. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  89687. })(BABYLON || (BABYLON = {}));
  89688. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  89689. var BABYLON;
  89690. (function (BABYLON) {
  89691. var IndexedVector2 = /** @class */ (function (_super) {
  89692. __extends(IndexedVector2, _super);
  89693. function IndexedVector2(original, index) {
  89694. var _this = _super.call(this, original.x, original.y) || this;
  89695. _this.index = index;
  89696. return _this;
  89697. }
  89698. return IndexedVector2;
  89699. }(BABYLON.Vector2));
  89700. var PolygonPoints = /** @class */ (function () {
  89701. function PolygonPoints() {
  89702. this.elements = new Array();
  89703. }
  89704. PolygonPoints.prototype.add = function (originalPoints) {
  89705. var _this = this;
  89706. var result = new Array();
  89707. originalPoints.forEach(function (point) {
  89708. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  89709. var newPoint = new IndexedVector2(point, _this.elements.length);
  89710. result.push(newPoint);
  89711. _this.elements.push(newPoint);
  89712. }
  89713. });
  89714. return result;
  89715. };
  89716. PolygonPoints.prototype.computeBounds = function () {
  89717. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  89718. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  89719. this.elements.forEach(function (point) {
  89720. // x
  89721. if (point.x < lmin.x) {
  89722. lmin.x = point.x;
  89723. }
  89724. else if (point.x > lmax.x) {
  89725. lmax.x = point.x;
  89726. }
  89727. // y
  89728. if (point.y < lmin.y) {
  89729. lmin.y = point.y;
  89730. }
  89731. else if (point.y > lmax.y) {
  89732. lmax.y = point.y;
  89733. }
  89734. });
  89735. return {
  89736. min: lmin,
  89737. max: lmax,
  89738. width: lmax.x - lmin.x,
  89739. height: lmax.y - lmin.y
  89740. };
  89741. };
  89742. return PolygonPoints;
  89743. }());
  89744. var Polygon = /** @class */ (function () {
  89745. function Polygon() {
  89746. }
  89747. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  89748. return [
  89749. new BABYLON.Vector2(xmin, ymin),
  89750. new BABYLON.Vector2(xmax, ymin),
  89751. new BABYLON.Vector2(xmax, ymax),
  89752. new BABYLON.Vector2(xmin, ymax)
  89753. ];
  89754. };
  89755. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  89756. if (cx === void 0) { cx = 0; }
  89757. if (cy === void 0) { cy = 0; }
  89758. if (numberOfSides === void 0) { numberOfSides = 32; }
  89759. var result = new Array();
  89760. var angle = 0;
  89761. var increment = (Math.PI * 2) / numberOfSides;
  89762. for (var i = 0; i < numberOfSides; i++) {
  89763. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  89764. angle -= increment;
  89765. }
  89766. return result;
  89767. };
  89768. Polygon.Parse = function (input) {
  89769. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  89770. var i, result = [];
  89771. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  89772. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  89773. }
  89774. return result;
  89775. };
  89776. Polygon.StartingAt = function (x, y) {
  89777. return BABYLON.Path2.StartingAt(x, y);
  89778. };
  89779. return Polygon;
  89780. }());
  89781. BABYLON.Polygon = Polygon;
  89782. var PolygonMeshBuilder = /** @class */ (function () {
  89783. function PolygonMeshBuilder(name, contours, scene) {
  89784. this._points = new PolygonPoints();
  89785. this._outlinepoints = new PolygonPoints();
  89786. this._holes = new Array();
  89787. this._epoints = new Array();
  89788. this._eholes = new Array();
  89789. this._name = name;
  89790. this._scene = scene;
  89791. var points;
  89792. if (contours instanceof BABYLON.Path2) {
  89793. points = contours.getPoints();
  89794. }
  89795. else {
  89796. points = contours;
  89797. }
  89798. this._addToepoint(points);
  89799. this._points.add(points);
  89800. this._outlinepoints.add(points);
  89801. if (typeof earcut === 'undefined') {
  89802. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  89803. }
  89804. }
  89805. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  89806. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  89807. var p = points_1[_i];
  89808. this._epoints.push(p.x, p.y);
  89809. }
  89810. };
  89811. PolygonMeshBuilder.prototype.addHole = function (hole) {
  89812. this._points.add(hole);
  89813. var holepoints = new PolygonPoints();
  89814. holepoints.add(hole);
  89815. this._holes.push(holepoints);
  89816. this._eholes.push(this._epoints.length / 2);
  89817. this._addToepoint(hole);
  89818. return this;
  89819. };
  89820. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  89821. var _this = this;
  89822. if (updatable === void 0) { updatable = false; }
  89823. if (depth === void 0) { depth = 0; }
  89824. var result = new BABYLON.Mesh(this._name, this._scene);
  89825. var normals = new Array();
  89826. var positions = new Array();
  89827. var uvs = new Array();
  89828. var bounds = this._points.computeBounds();
  89829. this._points.elements.forEach(function (p) {
  89830. normals.push(0, 1.0, 0);
  89831. positions.push(p.x, 0, p.y);
  89832. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  89833. });
  89834. var indices = new Array();
  89835. var res = earcut(this._epoints, this._eholes, 2);
  89836. for (var i = 0; i < res.length; i++) {
  89837. indices.push(res[i]);
  89838. }
  89839. if (depth > 0) {
  89840. var positionscount = (positions.length / 3); //get the current pointcount
  89841. this._points.elements.forEach(function (p) {
  89842. normals.push(0, -1.0, 0);
  89843. positions.push(p.x, -depth, p.y);
  89844. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  89845. });
  89846. var totalCount = indices.length;
  89847. for (var i = 0; i < totalCount; i += 3) {
  89848. var i0 = indices[i + 0];
  89849. var i1 = indices[i + 1];
  89850. var i2 = indices[i + 2];
  89851. indices.push(i2 + positionscount);
  89852. indices.push(i1 + positionscount);
  89853. indices.push(i0 + positionscount);
  89854. }
  89855. //Add the sides
  89856. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  89857. this._holes.forEach(function (hole) {
  89858. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  89859. });
  89860. }
  89861. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  89862. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  89863. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  89864. result.setIndices(indices);
  89865. return result;
  89866. };
  89867. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  89868. var StartIndex = positions.length / 3;
  89869. var ulength = 0;
  89870. for (var i = 0; i < points.elements.length; i++) {
  89871. var p = points.elements[i];
  89872. var p1;
  89873. if ((i + 1) > points.elements.length - 1) {
  89874. p1 = points.elements[0];
  89875. }
  89876. else {
  89877. p1 = points.elements[i + 1];
  89878. }
  89879. positions.push(p.x, 0, p.y);
  89880. positions.push(p.x, -depth, p.y);
  89881. positions.push(p1.x, 0, p1.y);
  89882. positions.push(p1.x, -depth, p1.y);
  89883. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  89884. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  89885. var v3 = v2.subtract(v1);
  89886. var v4 = new BABYLON.Vector3(0, 1, 0);
  89887. var vn = BABYLON.Vector3.Cross(v3, v4);
  89888. vn = vn.normalize();
  89889. uvs.push(ulength / bounds.width, 0);
  89890. uvs.push(ulength / bounds.width, 1);
  89891. ulength += v3.length();
  89892. uvs.push((ulength / bounds.width), 0);
  89893. uvs.push((ulength / bounds.width), 1);
  89894. if (!flip) {
  89895. normals.push(-vn.x, -vn.y, -vn.z);
  89896. normals.push(-vn.x, -vn.y, -vn.z);
  89897. normals.push(-vn.x, -vn.y, -vn.z);
  89898. normals.push(-vn.x, -vn.y, -vn.z);
  89899. indices.push(StartIndex);
  89900. indices.push(StartIndex + 1);
  89901. indices.push(StartIndex + 2);
  89902. indices.push(StartIndex + 1);
  89903. indices.push(StartIndex + 3);
  89904. indices.push(StartIndex + 2);
  89905. }
  89906. else {
  89907. normals.push(vn.x, vn.y, vn.z);
  89908. normals.push(vn.x, vn.y, vn.z);
  89909. normals.push(vn.x, vn.y, vn.z);
  89910. normals.push(vn.x, vn.y, vn.z);
  89911. indices.push(StartIndex);
  89912. indices.push(StartIndex + 2);
  89913. indices.push(StartIndex + 1);
  89914. indices.push(StartIndex + 1);
  89915. indices.push(StartIndex + 2);
  89916. indices.push(StartIndex + 3);
  89917. }
  89918. StartIndex += 4;
  89919. }
  89920. ;
  89921. };
  89922. return PolygonMeshBuilder;
  89923. }());
  89924. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  89925. })(BABYLON || (BABYLON = {}));
  89926. //# sourceMappingURL=babylon.polygonMesh.js.map
  89927. var BABYLON;
  89928. (function (BABYLON) {
  89929. // Unique ID when we import meshes from Babylon to CSG
  89930. var currentCSGMeshId = 0;
  89931. // # class Vertex
  89932. // Represents a vertex of a polygon. Use your own vertex class instead of this
  89933. // one to provide additional features like texture coordinates and vertex
  89934. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  89935. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  89936. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  89937. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  89938. // is not used anywhere else.
  89939. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  89940. var Vertex = /** @class */ (function () {
  89941. function Vertex(pos, normal, uv) {
  89942. this.pos = pos;
  89943. this.normal = normal;
  89944. this.uv = uv;
  89945. }
  89946. Vertex.prototype.clone = function () {
  89947. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  89948. };
  89949. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  89950. // orientation of a polygon is flipped.
  89951. Vertex.prototype.flip = function () {
  89952. this.normal = this.normal.scale(-1);
  89953. };
  89954. // Create a new vertex between this vertex and `other` by linearly
  89955. // interpolating all properties using a parameter of `t`. Subclasses should
  89956. // override this to interpolate additional properties.
  89957. Vertex.prototype.interpolate = function (other, t) {
  89958. 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));
  89959. };
  89960. return Vertex;
  89961. }());
  89962. // # class Plane
  89963. // Represents a plane in 3D space.
  89964. var Plane = /** @class */ (function () {
  89965. function Plane(normal, w) {
  89966. this.normal = normal;
  89967. this.w = w;
  89968. }
  89969. Plane.FromPoints = function (a, b, c) {
  89970. var v0 = c.subtract(a);
  89971. var v1 = b.subtract(a);
  89972. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  89973. return null;
  89974. }
  89975. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  89976. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  89977. };
  89978. Plane.prototype.clone = function () {
  89979. return new Plane(this.normal.clone(), this.w);
  89980. };
  89981. Plane.prototype.flip = function () {
  89982. this.normal.scaleInPlace(-1);
  89983. this.w = -this.w;
  89984. };
  89985. // Split `polygon` by this plane if needed, then put the polygon or polygon
  89986. // fragments in the appropriate lists. Coplanar polygons go into either
  89987. // `coplanarFront` or `coplanarBack` depending on their orientation with
  89988. // respect to this plane. Polygons in front or in back of this plane go into
  89989. // either `front` or `back`.
  89990. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  89991. var COPLANAR = 0;
  89992. var FRONT = 1;
  89993. var BACK = 2;
  89994. var SPANNING = 3;
  89995. // Classify each point as well as the entire polygon into one of the above
  89996. // four classes.
  89997. var polygonType = 0;
  89998. var types = [];
  89999. var i;
  90000. var t;
  90001. for (i = 0; i < polygon.vertices.length; i++) {
  90002. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  90003. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  90004. polygonType |= type;
  90005. types.push(type);
  90006. }
  90007. // Put the polygon in the correct list, splitting it when necessary.
  90008. switch (polygonType) {
  90009. case COPLANAR:
  90010. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  90011. break;
  90012. case FRONT:
  90013. front.push(polygon);
  90014. break;
  90015. case BACK:
  90016. back.push(polygon);
  90017. break;
  90018. case SPANNING:
  90019. var f = [], b = [];
  90020. for (i = 0; i < polygon.vertices.length; i++) {
  90021. var j = (i + 1) % polygon.vertices.length;
  90022. var ti = types[i], tj = types[j];
  90023. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  90024. if (ti !== BACK)
  90025. f.push(vi);
  90026. if (ti !== FRONT)
  90027. b.push(ti !== BACK ? vi.clone() : vi);
  90028. if ((ti | tj) === SPANNING) {
  90029. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  90030. var v = vi.interpolate(vj, t);
  90031. f.push(v);
  90032. b.push(v.clone());
  90033. }
  90034. }
  90035. var poly;
  90036. if (f.length >= 3) {
  90037. poly = new Polygon(f, polygon.shared);
  90038. if (poly.plane)
  90039. front.push(poly);
  90040. }
  90041. if (b.length >= 3) {
  90042. poly = new Polygon(b, polygon.shared);
  90043. if (poly.plane)
  90044. back.push(poly);
  90045. }
  90046. break;
  90047. }
  90048. };
  90049. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  90050. // point is on the plane.
  90051. Plane.EPSILON = 1e-5;
  90052. return Plane;
  90053. }());
  90054. // # class Polygon
  90055. // Represents a convex polygon. The vertices used to initialize a polygon must
  90056. // be coplanar and form a convex loop.
  90057. //
  90058. // Each convex polygon has a `shared` property, which is shared between all
  90059. // polygons that are clones of each other or were split from the same polygon.
  90060. // This can be used to define per-polygon properties (such as surface color).
  90061. var Polygon = /** @class */ (function () {
  90062. function Polygon(vertices, shared) {
  90063. this.vertices = vertices;
  90064. this.shared = shared;
  90065. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  90066. }
  90067. Polygon.prototype.clone = function () {
  90068. var vertices = this.vertices.map(function (v) { return v.clone(); });
  90069. return new Polygon(vertices, this.shared);
  90070. };
  90071. Polygon.prototype.flip = function () {
  90072. this.vertices.reverse().map(function (v) { v.flip(); });
  90073. this.plane.flip();
  90074. };
  90075. return Polygon;
  90076. }());
  90077. // # class Node
  90078. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  90079. // by picking a polygon to split along. That polygon (and all other coplanar
  90080. // polygons) are added directly to that node and the other polygons are added to
  90081. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  90082. // no distinction between internal and leaf nodes.
  90083. var Node = /** @class */ (function () {
  90084. function Node(polygons) {
  90085. this.plane = null;
  90086. this.front = null;
  90087. this.back = null;
  90088. this.polygons = new Array();
  90089. if (polygons) {
  90090. this.build(polygons);
  90091. }
  90092. }
  90093. Node.prototype.clone = function () {
  90094. var node = new Node();
  90095. node.plane = this.plane && this.plane.clone();
  90096. node.front = this.front && this.front.clone();
  90097. node.back = this.back && this.back.clone();
  90098. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  90099. return node;
  90100. };
  90101. // Convert solid space to empty space and empty space to solid space.
  90102. Node.prototype.invert = function () {
  90103. for (var i = 0; i < this.polygons.length; i++) {
  90104. this.polygons[i].flip();
  90105. }
  90106. if (this.plane) {
  90107. this.plane.flip();
  90108. }
  90109. if (this.front) {
  90110. this.front.invert();
  90111. }
  90112. if (this.back) {
  90113. this.back.invert();
  90114. }
  90115. var temp = this.front;
  90116. this.front = this.back;
  90117. this.back = temp;
  90118. };
  90119. // Recursively remove all polygons in `polygons` that are inside this BSP
  90120. // tree.
  90121. Node.prototype.clipPolygons = function (polygons) {
  90122. if (!this.plane)
  90123. return polygons.slice();
  90124. var front = new Array(), back = new Array();
  90125. for (var i = 0; i < polygons.length; i++) {
  90126. this.plane.splitPolygon(polygons[i], front, back, front, back);
  90127. }
  90128. if (this.front) {
  90129. front = this.front.clipPolygons(front);
  90130. }
  90131. if (this.back) {
  90132. back = this.back.clipPolygons(back);
  90133. }
  90134. else {
  90135. back = [];
  90136. }
  90137. return front.concat(back);
  90138. };
  90139. // Remove all polygons in this BSP tree that are inside the other BSP tree
  90140. // `bsp`.
  90141. Node.prototype.clipTo = function (bsp) {
  90142. this.polygons = bsp.clipPolygons(this.polygons);
  90143. if (this.front)
  90144. this.front.clipTo(bsp);
  90145. if (this.back)
  90146. this.back.clipTo(bsp);
  90147. };
  90148. // Return a list of all polygons in this BSP tree.
  90149. Node.prototype.allPolygons = function () {
  90150. var polygons = this.polygons.slice();
  90151. if (this.front)
  90152. polygons = polygons.concat(this.front.allPolygons());
  90153. if (this.back)
  90154. polygons = polygons.concat(this.back.allPolygons());
  90155. return polygons;
  90156. };
  90157. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  90158. // new polygons are filtered down to the bottom of the tree and become new
  90159. // nodes there. Each set of polygons is partitioned using the first polygon
  90160. // (no heuristic is used to pick a good split).
  90161. Node.prototype.build = function (polygons) {
  90162. if (!polygons.length)
  90163. return;
  90164. if (!this.plane)
  90165. this.plane = polygons[0].plane.clone();
  90166. var front = new Array(), back = new Array();
  90167. for (var i = 0; i < polygons.length; i++) {
  90168. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  90169. }
  90170. if (front.length) {
  90171. if (!this.front)
  90172. this.front = new Node();
  90173. this.front.build(front);
  90174. }
  90175. if (back.length) {
  90176. if (!this.back)
  90177. this.back = new Node();
  90178. this.back.build(back);
  90179. }
  90180. };
  90181. return Node;
  90182. }());
  90183. var CSG = /** @class */ (function () {
  90184. function CSG() {
  90185. this.polygons = new Array();
  90186. }
  90187. // Convert BABYLON.Mesh to BABYLON.CSG
  90188. CSG.FromMesh = function (mesh) {
  90189. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  90190. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  90191. if (mesh instanceof BABYLON.Mesh) {
  90192. mesh.computeWorldMatrix(true);
  90193. matrix = mesh.getWorldMatrix();
  90194. meshPosition = mesh.position.clone();
  90195. meshRotation = mesh.rotation.clone();
  90196. if (mesh.rotationQuaternion) {
  90197. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  90198. }
  90199. meshScaling = mesh.scaling.clone();
  90200. }
  90201. else {
  90202. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  90203. }
  90204. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90205. var subMeshes = mesh.subMeshes;
  90206. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  90207. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  90208. vertices = [];
  90209. for (var j = 0; j < 3; j++) {
  90210. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  90211. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  90212. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  90213. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  90214. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  90215. vertex = new Vertex(position, normal, uv);
  90216. vertices.push(vertex);
  90217. }
  90218. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  90219. // To handle the case of degenerated triangle
  90220. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  90221. if (polygon.plane)
  90222. polygons.push(polygon);
  90223. }
  90224. }
  90225. var csg = CSG.FromPolygons(polygons);
  90226. csg.matrix = matrix;
  90227. csg.position = meshPosition;
  90228. csg.rotation = meshRotation;
  90229. csg.scaling = meshScaling;
  90230. csg.rotationQuaternion = meshRotationQuaternion;
  90231. currentCSGMeshId++;
  90232. return csg;
  90233. };
  90234. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  90235. CSG.FromPolygons = function (polygons) {
  90236. var csg = new CSG();
  90237. csg.polygons = polygons;
  90238. return csg;
  90239. };
  90240. CSG.prototype.clone = function () {
  90241. var csg = new CSG();
  90242. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  90243. csg.copyTransformAttributes(this);
  90244. return csg;
  90245. };
  90246. CSG.prototype.union = function (csg) {
  90247. var a = new Node(this.clone().polygons);
  90248. var b = new Node(csg.clone().polygons);
  90249. a.clipTo(b);
  90250. b.clipTo(a);
  90251. b.invert();
  90252. b.clipTo(a);
  90253. b.invert();
  90254. a.build(b.allPolygons());
  90255. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90256. };
  90257. CSG.prototype.unionInPlace = function (csg) {
  90258. var a = new Node(this.polygons);
  90259. var b = new Node(csg.polygons);
  90260. a.clipTo(b);
  90261. b.clipTo(a);
  90262. b.invert();
  90263. b.clipTo(a);
  90264. b.invert();
  90265. a.build(b.allPolygons());
  90266. this.polygons = a.allPolygons();
  90267. };
  90268. CSG.prototype.subtract = function (csg) {
  90269. var a = new Node(this.clone().polygons);
  90270. var b = new Node(csg.clone().polygons);
  90271. a.invert();
  90272. a.clipTo(b);
  90273. b.clipTo(a);
  90274. b.invert();
  90275. b.clipTo(a);
  90276. b.invert();
  90277. a.build(b.allPolygons());
  90278. a.invert();
  90279. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90280. };
  90281. CSG.prototype.subtractInPlace = function (csg) {
  90282. var a = new Node(this.polygons);
  90283. var b = new Node(csg.polygons);
  90284. a.invert();
  90285. a.clipTo(b);
  90286. b.clipTo(a);
  90287. b.invert();
  90288. b.clipTo(a);
  90289. b.invert();
  90290. a.build(b.allPolygons());
  90291. a.invert();
  90292. this.polygons = a.allPolygons();
  90293. };
  90294. CSG.prototype.intersect = function (csg) {
  90295. var a = new Node(this.clone().polygons);
  90296. var b = new Node(csg.clone().polygons);
  90297. a.invert();
  90298. b.clipTo(a);
  90299. b.invert();
  90300. a.clipTo(b);
  90301. b.clipTo(a);
  90302. a.build(b.allPolygons());
  90303. a.invert();
  90304. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90305. };
  90306. CSG.prototype.intersectInPlace = function (csg) {
  90307. var a = new Node(this.polygons);
  90308. var b = new Node(csg.polygons);
  90309. a.invert();
  90310. b.clipTo(a);
  90311. b.invert();
  90312. a.clipTo(b);
  90313. b.clipTo(a);
  90314. a.build(b.allPolygons());
  90315. a.invert();
  90316. this.polygons = a.allPolygons();
  90317. };
  90318. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  90319. // not modified.
  90320. CSG.prototype.inverse = function () {
  90321. var csg = this.clone();
  90322. csg.inverseInPlace();
  90323. return csg;
  90324. };
  90325. CSG.prototype.inverseInPlace = function () {
  90326. this.polygons.map(function (p) { p.flip(); });
  90327. };
  90328. // This is used to keep meshes transformations so they can be restored
  90329. // when we build back a Babylon Mesh
  90330. // NB : All CSG operations are performed in world coordinates
  90331. CSG.prototype.copyTransformAttributes = function (csg) {
  90332. this.matrix = csg.matrix;
  90333. this.position = csg.position;
  90334. this.rotation = csg.rotation;
  90335. this.scaling = csg.scaling;
  90336. this.rotationQuaternion = csg.rotationQuaternion;
  90337. return this;
  90338. };
  90339. // Build Raw mesh from CSG
  90340. // Coordinates here are in world space
  90341. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  90342. var matrix = this.matrix.clone();
  90343. matrix.invert();
  90344. 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;
  90345. if (keepSubMeshes) {
  90346. // Sort Polygons, since subMeshes are indices range
  90347. polygons.sort(function (a, b) {
  90348. if (a.shared.meshId === b.shared.meshId) {
  90349. return a.shared.subMeshId - b.shared.subMeshId;
  90350. }
  90351. else {
  90352. return a.shared.meshId - b.shared.meshId;
  90353. }
  90354. });
  90355. }
  90356. for (var i = 0, il = polygons.length; i < il; i++) {
  90357. polygon = polygons[i];
  90358. // Building SubMeshes
  90359. if (!subMesh_dict[polygon.shared.meshId]) {
  90360. subMesh_dict[polygon.shared.meshId] = {};
  90361. }
  90362. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  90363. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  90364. indexStart: +Infinity,
  90365. indexEnd: -Infinity,
  90366. materialIndex: polygon.shared.materialIndex
  90367. };
  90368. }
  90369. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  90370. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  90371. polygonIndices[0] = 0;
  90372. polygonIndices[1] = j - 1;
  90373. polygonIndices[2] = j;
  90374. for (var k = 0; k < 3; k++) {
  90375. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  90376. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  90377. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  90378. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  90379. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  90380. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  90381. // Check if 2 points can be merged
  90382. if (!(typeof vertex_idx !== 'undefined' &&
  90383. normals[vertex_idx * 3] === localNormal.x &&
  90384. normals[vertex_idx * 3 + 1] === localNormal.y &&
  90385. normals[vertex_idx * 3 + 2] === localNormal.z &&
  90386. uvs[vertex_idx * 2] === uv.x &&
  90387. uvs[vertex_idx * 2 + 1] === uv.y)) {
  90388. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  90389. uvs.push(uv.x, uv.y);
  90390. normals.push(normal.x, normal.y, normal.z);
  90391. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  90392. }
  90393. indices.push(vertex_idx);
  90394. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  90395. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  90396. currentIndex++;
  90397. }
  90398. }
  90399. }
  90400. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  90401. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  90402. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  90403. mesh.setIndices(indices, null);
  90404. if (keepSubMeshes) {
  90405. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  90406. var materialIndexOffset = 0, materialMaxIndex;
  90407. mesh.subMeshes = new Array();
  90408. for (var m in subMesh_dict) {
  90409. materialMaxIndex = -1;
  90410. for (var sm in subMesh_dict[m]) {
  90411. subMesh_obj = subMesh_dict[m][sm];
  90412. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  90413. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  90414. }
  90415. materialIndexOffset += ++materialMaxIndex;
  90416. }
  90417. }
  90418. return mesh;
  90419. };
  90420. // Build Mesh from CSG taking material and transforms into account
  90421. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  90422. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  90423. mesh.material = material;
  90424. mesh.position.copyFrom(this.position);
  90425. mesh.rotation.copyFrom(this.rotation);
  90426. if (this.rotationQuaternion) {
  90427. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  90428. }
  90429. mesh.scaling.copyFrom(this.scaling);
  90430. mesh.computeWorldMatrix(true);
  90431. return mesh;
  90432. };
  90433. return CSG;
  90434. }());
  90435. BABYLON.CSG = CSG;
  90436. })(BABYLON || (BABYLON = {}));
  90437. //# sourceMappingURL=babylon.csg.js.map
  90438. var BABYLON;
  90439. (function (BABYLON) {
  90440. /**
  90441. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90442. * It controls one of the indiviual texture used in the effect.
  90443. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90444. */
  90445. var LensFlare = /** @class */ (function () {
  90446. /**
  90447. * Instantiates a new Lens Flare.
  90448. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90449. * It controls one of the indiviual texture used in the effect.
  90450. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90451. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  90452. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  90453. * @param color Define the lens color
  90454. * @param imgUrl Define the lens texture url
  90455. * @param system Define the `lensFlareSystem` this flare is part of
  90456. */
  90457. function LensFlare(
  90458. /**
  90459. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  90460. */
  90461. size,
  90462. /**
  90463. * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  90464. */
  90465. position, color, imgUrl, system) {
  90466. this.size = size;
  90467. this.position = position;
  90468. /**
  90469. * Define the alpha mode to render this particular lens.
  90470. */
  90471. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  90472. this.color = color || new BABYLON.Color3(1, 1, 1);
  90473. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  90474. this._system = system;
  90475. system.lensFlares.push(this);
  90476. }
  90477. /**
  90478. * Creates a new Lens Flare.
  90479. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90480. * It controls one of the indiviual texture used in the effect.
  90481. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90482. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  90483. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  90484. * @param color Define the lens color
  90485. * @param imgUrl Define the lens texture url
  90486. * @param system Define the `lensFlareSystem` this flare is part of
  90487. * @returns The newly created Lens Flare
  90488. */
  90489. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  90490. return new LensFlare(size, position, color, imgUrl, system);
  90491. };
  90492. /**
  90493. * Dispose and release the lens flare with its associated resources.
  90494. */
  90495. LensFlare.prototype.dispose = function () {
  90496. if (this.texture) {
  90497. this.texture.dispose();
  90498. }
  90499. // Remove from scene
  90500. var index = this._system.lensFlares.indexOf(this);
  90501. this._system.lensFlares.splice(index, 1);
  90502. };
  90503. ;
  90504. return LensFlare;
  90505. }());
  90506. BABYLON.LensFlare = LensFlare;
  90507. })(BABYLON || (BABYLON = {}));
  90508. //# sourceMappingURL=babylon.lensFlare.js.map
  90509. var BABYLON;
  90510. (function (BABYLON) {
  90511. // Adds the parser to the scene parsers.
  90512. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  90513. // Lens flares
  90514. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  90515. if (!container.lensFlareSystems) {
  90516. container.lensFlareSystems = new Array();
  90517. }
  90518. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  90519. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  90520. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  90521. container.lensFlareSystems.push(lf);
  90522. }
  90523. }
  90524. });
  90525. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  90526. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  90527. if (this.lensFlareSystems[index].name === name) {
  90528. return this.lensFlareSystems[index];
  90529. }
  90530. }
  90531. return null;
  90532. };
  90533. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  90534. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  90535. if (this.lensFlareSystems[index].id === id) {
  90536. return this.lensFlareSystems[index];
  90537. }
  90538. }
  90539. return null;
  90540. };
  90541. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  90542. var index = this.lensFlareSystems.indexOf(toRemove);
  90543. if (index !== -1) {
  90544. this.lensFlareSystems.splice(index, 1);
  90545. }
  90546. return index;
  90547. };
  90548. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  90549. this.lensFlareSystems.push(newLensFlareSystem);
  90550. };
  90551. /**
  90552. * Defines the lens flare scene component responsible to manage any lens flares
  90553. * in a given scene.
  90554. */
  90555. var LensFlareSystemSceneComponent = /** @class */ (function () {
  90556. /**
  90557. * Creates a new instance of the component for the given scene
  90558. * @param scene Defines the scene to register the component in
  90559. */
  90560. function LensFlareSystemSceneComponent(scene) {
  90561. /**
  90562. * The component name helpfull to identify the component in the list of scene components.
  90563. */
  90564. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  90565. this.scene = scene;
  90566. scene.lensFlareSystems = new Array();
  90567. }
  90568. /**
  90569. * Registers the component in a given scene
  90570. */
  90571. LensFlareSystemSceneComponent.prototype.register = function () {
  90572. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  90573. };
  90574. /**
  90575. * Rebuilds the elements related to this component in case of
  90576. * context lost for instance.
  90577. */
  90578. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  90579. // Nothing to do for lens flare
  90580. };
  90581. /**
  90582. * Adds all the element from the container to the scene
  90583. * @param container the container holding the elements
  90584. */
  90585. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  90586. var _this = this;
  90587. if (!container.lensFlareSystems) {
  90588. return;
  90589. }
  90590. container.lensFlareSystems.forEach(function (o) {
  90591. _this.scene.addLensFlareSystem(o);
  90592. });
  90593. };
  90594. /**
  90595. * Removes all the elements in the container from the scene
  90596. * @param container contains the elements to remove
  90597. */
  90598. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  90599. var _this = this;
  90600. if (!container.lensFlareSystems) {
  90601. return;
  90602. }
  90603. container.lensFlareSystems.forEach(function (o) {
  90604. _this.scene.removeLensFlareSystem(o);
  90605. });
  90606. };
  90607. /**
  90608. * Serializes the component data to the specified json object
  90609. * @param serializationObject The object to serialize to
  90610. */
  90611. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  90612. // Lens flares
  90613. serializationObject.lensFlareSystems = [];
  90614. var lensFlareSystems = this.scene.lensFlareSystems;
  90615. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  90616. var lensFlareSystem = lensFlareSystems_1[_i];
  90617. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  90618. }
  90619. };
  90620. /**
  90621. * Disposes the component and the associated ressources.
  90622. */
  90623. LensFlareSystemSceneComponent.prototype.dispose = function () {
  90624. var lensFlareSystems = this.scene.lensFlareSystems;
  90625. while (lensFlareSystems.length) {
  90626. lensFlareSystems[0].dispose();
  90627. }
  90628. };
  90629. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  90630. // Lens flares
  90631. if (this.scene.lensFlaresEnabled) {
  90632. var lensFlareSystems = this.scene.lensFlareSystems;
  90633. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  90634. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  90635. var lensFlareSystem = lensFlareSystems_2[_i];
  90636. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  90637. lensFlareSystem.render();
  90638. }
  90639. }
  90640. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  90641. }
  90642. };
  90643. return LensFlareSystemSceneComponent;
  90644. }());
  90645. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  90646. })(BABYLON || (BABYLON = {}));
  90647. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  90648. var BABYLON;
  90649. (function (BABYLON) {
  90650. /**
  90651. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  90652. * It is usually composed of several `BABYLON.lensFlare`.
  90653. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90654. */
  90655. var LensFlareSystem = /** @class */ (function () {
  90656. /**
  90657. * Instantiates a lens flare system.
  90658. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  90659. * It is usually composed of several `BABYLON.lensFlare`.
  90660. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90661. * @param name Define the name of the lens flare system in the scene
  90662. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  90663. * @param scene Define the scene the lens flare system belongs to
  90664. */
  90665. function LensFlareSystem(
  90666. /**
  90667. * Define the name of the lens flare system
  90668. */
  90669. name, emitter, scene) {
  90670. this.name = name;
  90671. /**
  90672. * List of lens flares used in this system.
  90673. */
  90674. this.lensFlares = new Array();
  90675. /**
  90676. * Define a limit from the border the lens flare can be visible.
  90677. */
  90678. this.borderLimit = 300;
  90679. /**
  90680. * Define a viewport border we do not want to see the lens flare in.
  90681. */
  90682. this.viewportBorder = 0;
  90683. /**
  90684. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  90685. */
  90686. this.layerMask = 0x0FFFFFFF;
  90687. this._vertexBuffers = {};
  90688. this._isEnabled = true;
  90689. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90690. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  90691. if (!component) {
  90692. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  90693. scene._addComponent(component);
  90694. }
  90695. this._emitter = emitter;
  90696. this.id = name;
  90697. scene.lensFlareSystems.push(this);
  90698. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  90699. var engine = scene.getEngine();
  90700. // VBO
  90701. var vertices = [];
  90702. vertices.push(1, 1);
  90703. vertices.push(-1, 1);
  90704. vertices.push(-1, -1);
  90705. vertices.push(1, -1);
  90706. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  90707. // Indices
  90708. var indices = [];
  90709. indices.push(0);
  90710. indices.push(1);
  90711. indices.push(2);
  90712. indices.push(0);
  90713. indices.push(2);
  90714. indices.push(3);
  90715. this._indexBuffer = engine.createIndexBuffer(indices);
  90716. // Effects
  90717. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  90718. }
  90719. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  90720. /**
  90721. * Define if the lens flare system is enabled.
  90722. */
  90723. get: function () {
  90724. return this._isEnabled;
  90725. },
  90726. set: function (value) {
  90727. this._isEnabled = value;
  90728. },
  90729. enumerable: true,
  90730. configurable: true
  90731. });
  90732. /**
  90733. * Get the scene the effects belongs to.
  90734. * @returns the scene holding the lens flare system
  90735. */
  90736. LensFlareSystem.prototype.getScene = function () {
  90737. return this._scene;
  90738. };
  90739. /**
  90740. * Get the emitter of the lens flare system.
  90741. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  90742. * @returns the emitter of the lens flare system
  90743. */
  90744. LensFlareSystem.prototype.getEmitter = function () {
  90745. return this._emitter;
  90746. };
  90747. /**
  90748. * Set the emitter of the lens flare system.
  90749. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  90750. * @param newEmitter Define the new emitter of the system
  90751. */
  90752. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  90753. this._emitter = newEmitter;
  90754. };
  90755. /**
  90756. * Get the lens flare system emitter position.
  90757. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  90758. * @returns the position
  90759. */
  90760. LensFlareSystem.prototype.getEmitterPosition = function () {
  90761. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  90762. };
  90763. /**
  90764. * @hidden
  90765. */
  90766. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  90767. var position = this.getEmitterPosition();
  90768. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  90769. this._positionX = position.x;
  90770. this._positionY = position.y;
  90771. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  90772. if (this.viewportBorder > 0) {
  90773. globalViewport.x -= this.viewportBorder;
  90774. globalViewport.y -= this.viewportBorder;
  90775. globalViewport.width += this.viewportBorder * 2;
  90776. globalViewport.height += this.viewportBorder * 2;
  90777. position.x += this.viewportBorder;
  90778. position.y += this.viewportBorder;
  90779. this._positionX += this.viewportBorder;
  90780. this._positionY += this.viewportBorder;
  90781. }
  90782. if (position.z > 0) {
  90783. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  90784. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  90785. return true;
  90786. }
  90787. return true;
  90788. }
  90789. return false;
  90790. };
  90791. /** @hidden */
  90792. LensFlareSystem.prototype._isVisible = function () {
  90793. if (!this._isEnabled || !this._scene.activeCamera) {
  90794. return false;
  90795. }
  90796. var emitterPosition = this.getEmitterPosition();
  90797. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  90798. var distance = direction.length();
  90799. direction.normalize();
  90800. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  90801. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  90802. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  90803. };
  90804. /**
  90805. * @hidden
  90806. */
  90807. LensFlareSystem.prototype.render = function () {
  90808. if (!this._effect.isReady() || !this._scene.activeCamera)
  90809. return false;
  90810. var engine = this._scene.getEngine();
  90811. var viewport = this._scene.activeCamera.viewport;
  90812. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  90813. // Position
  90814. if (!this.computeEffectivePosition(globalViewport)) {
  90815. return false;
  90816. }
  90817. // Visibility
  90818. if (!this._isVisible()) {
  90819. return false;
  90820. }
  90821. // Intensity
  90822. var awayX;
  90823. var awayY;
  90824. if (this._positionX < this.borderLimit + globalViewport.x) {
  90825. awayX = this.borderLimit + globalViewport.x - this._positionX;
  90826. }
  90827. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  90828. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  90829. }
  90830. else {
  90831. awayX = 0;
  90832. }
  90833. if (this._positionY < this.borderLimit + globalViewport.y) {
  90834. awayY = this.borderLimit + globalViewport.y - this._positionY;
  90835. }
  90836. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  90837. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  90838. }
  90839. else {
  90840. awayY = 0;
  90841. }
  90842. var away = (awayX > awayY) ? awayX : awayY;
  90843. away -= this.viewportBorder;
  90844. if (away > this.borderLimit) {
  90845. away = this.borderLimit;
  90846. }
  90847. var intensity = 1.0 - (away / this.borderLimit);
  90848. if (intensity < 0) {
  90849. return false;
  90850. }
  90851. if (intensity > 1.0) {
  90852. intensity = 1.0;
  90853. }
  90854. if (this.viewportBorder > 0) {
  90855. globalViewport.x += this.viewportBorder;
  90856. globalViewport.y += this.viewportBorder;
  90857. globalViewport.width -= this.viewportBorder * 2;
  90858. globalViewport.height -= this.viewportBorder * 2;
  90859. this._positionX -= this.viewportBorder;
  90860. this._positionY -= this.viewportBorder;
  90861. }
  90862. // Position
  90863. var centerX = globalViewport.x + globalViewport.width / 2;
  90864. var centerY = globalViewport.y + globalViewport.height / 2;
  90865. var distX = centerX - this._positionX;
  90866. var distY = centerY - this._positionY;
  90867. // Effects
  90868. engine.enableEffect(this._effect);
  90869. engine.setState(false);
  90870. engine.setDepthBuffer(false);
  90871. // VBOs
  90872. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  90873. // Flares
  90874. for (var index = 0; index < this.lensFlares.length; index++) {
  90875. var flare = this.lensFlares[index];
  90876. engine.setAlphaMode(flare.alphaMode);
  90877. var x = centerX - (distX * flare.position);
  90878. var y = centerY - (distY * flare.position);
  90879. var cw = flare.size;
  90880. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  90881. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  90882. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  90883. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  90884. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  90885. // Texture
  90886. this._effect.setTexture("textureSampler", flare.texture);
  90887. // Color
  90888. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  90889. // Draw order
  90890. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90891. }
  90892. engine.setDepthBuffer(true);
  90893. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  90894. return true;
  90895. };
  90896. /**
  90897. * Dispose and release the lens flare with its associated resources.
  90898. */
  90899. LensFlareSystem.prototype.dispose = function () {
  90900. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90901. if (vertexBuffer) {
  90902. vertexBuffer.dispose();
  90903. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90904. }
  90905. if (this._indexBuffer) {
  90906. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90907. this._indexBuffer = null;
  90908. }
  90909. while (this.lensFlares.length) {
  90910. this.lensFlares[0].dispose();
  90911. }
  90912. // Remove from scene
  90913. var index = this._scene.lensFlareSystems.indexOf(this);
  90914. this._scene.lensFlareSystems.splice(index, 1);
  90915. };
  90916. /**
  90917. * Parse a lens flare system from a JSON repressentation
  90918. * @param parsedLensFlareSystem Define the JSON to parse
  90919. * @param scene Define the scene the parsed system should be instantiated in
  90920. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  90921. * @returns the parsed system
  90922. */
  90923. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  90924. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  90925. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  90926. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  90927. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  90928. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  90929. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  90930. var parsedFlare = parsedLensFlareSystem.flares[index];
  90931. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  90932. }
  90933. return lensFlareSystem;
  90934. };
  90935. /**
  90936. * Serialize the current Lens Flare System into a JSON representation.
  90937. * @returns the serialized JSON
  90938. */
  90939. LensFlareSystem.prototype.serialize = function () {
  90940. var serializationObject = {};
  90941. serializationObject.id = this.id;
  90942. serializationObject.name = this.name;
  90943. serializationObject.emitterId = this.getEmitter().id;
  90944. serializationObject.borderLimit = this.borderLimit;
  90945. serializationObject.flares = [];
  90946. for (var index = 0; index < this.lensFlares.length; index++) {
  90947. var flare = this.lensFlares[index];
  90948. serializationObject.flares.push({
  90949. size: flare.size,
  90950. position: flare.position,
  90951. color: flare.color.asArray(),
  90952. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  90953. });
  90954. }
  90955. return serializationObject;
  90956. };
  90957. return LensFlareSystem;
  90958. }());
  90959. BABYLON.LensFlareSystem = LensFlareSystem;
  90960. })(BABYLON || (BABYLON = {}));
  90961. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  90962. var BABYLON;
  90963. (function (BABYLON) {
  90964. /**
  90965. * This is a holder class for the physics joint created by the physics plugin.
  90966. * It holds a set of functions to control the underlying joint.
  90967. */
  90968. var PhysicsJoint = /** @class */ (function () {
  90969. function PhysicsJoint(type, jointData) {
  90970. this.type = type;
  90971. this.jointData = jointData;
  90972. jointData.nativeParams = jointData.nativeParams || {};
  90973. }
  90974. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  90975. get: function () {
  90976. return this._physicsJoint;
  90977. },
  90978. set: function (newJoint) {
  90979. if (this._physicsJoint) {
  90980. //remove from the wolrd
  90981. }
  90982. this._physicsJoint = newJoint;
  90983. },
  90984. enumerable: true,
  90985. configurable: true
  90986. });
  90987. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  90988. set: function (physicsPlugin) {
  90989. this._physicsPlugin = physicsPlugin;
  90990. },
  90991. enumerable: true,
  90992. configurable: true
  90993. });
  90994. /**
  90995. * Execute a function that is physics-plugin specific.
  90996. * @param {Function} func the function that will be executed.
  90997. * It accepts two parameters: the physics world and the physics joint.
  90998. */
  90999. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  91000. func(this._physicsPlugin.world, this._physicsJoint);
  91001. };
  91002. //TODO check if the native joints are the same
  91003. //Joint Types
  91004. PhysicsJoint.DistanceJoint = 0;
  91005. PhysicsJoint.HingeJoint = 1;
  91006. PhysicsJoint.BallAndSocketJoint = 2;
  91007. PhysicsJoint.WheelJoint = 3;
  91008. PhysicsJoint.SliderJoint = 4;
  91009. //OIMO
  91010. PhysicsJoint.PrismaticJoint = 5;
  91011. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  91012. PhysicsJoint.UniversalJoint = 6;
  91013. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  91014. //Cannon
  91015. //Similar to a Ball-Joint. Different in params
  91016. PhysicsJoint.PointToPointJoint = 8;
  91017. //Cannon only at the moment
  91018. PhysicsJoint.SpringJoint = 9;
  91019. PhysicsJoint.LockJoint = 10;
  91020. return PhysicsJoint;
  91021. }());
  91022. BABYLON.PhysicsJoint = PhysicsJoint;
  91023. /**
  91024. * A class representing a physics distance joint.
  91025. */
  91026. var DistanceJoint = /** @class */ (function (_super) {
  91027. __extends(DistanceJoint, _super);
  91028. function DistanceJoint(jointData) {
  91029. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  91030. }
  91031. /**
  91032. * Update the predefined distance.
  91033. */
  91034. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  91035. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  91036. };
  91037. return DistanceJoint;
  91038. }(PhysicsJoint));
  91039. BABYLON.DistanceJoint = DistanceJoint;
  91040. var MotorEnabledJoint = /** @class */ (function (_super) {
  91041. __extends(MotorEnabledJoint, _super);
  91042. function MotorEnabledJoint(type, jointData) {
  91043. return _super.call(this, type, jointData) || this;
  91044. }
  91045. /**
  91046. * Set the motor values.
  91047. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91048. * @param {number} force the force to apply
  91049. * @param {number} maxForce max force for this motor.
  91050. */
  91051. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  91052. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  91053. };
  91054. /**
  91055. * Set the motor's limits.
  91056. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91057. */
  91058. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  91059. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  91060. };
  91061. return MotorEnabledJoint;
  91062. }(PhysicsJoint));
  91063. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  91064. /**
  91065. * This class represents a single hinge physics joint
  91066. */
  91067. var HingeJoint = /** @class */ (function (_super) {
  91068. __extends(HingeJoint, _super);
  91069. function HingeJoint(jointData) {
  91070. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  91071. }
  91072. /**
  91073. * Set the motor values.
  91074. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91075. * @param {number} force the force to apply
  91076. * @param {number} maxForce max force for this motor.
  91077. */
  91078. HingeJoint.prototype.setMotor = function (force, maxForce) {
  91079. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  91080. };
  91081. /**
  91082. * Set the motor's limits.
  91083. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91084. */
  91085. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  91086. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  91087. };
  91088. return HingeJoint;
  91089. }(MotorEnabledJoint));
  91090. BABYLON.HingeJoint = HingeJoint;
  91091. /**
  91092. * This class represents a dual hinge physics joint (same as wheel joint)
  91093. */
  91094. var Hinge2Joint = /** @class */ (function (_super) {
  91095. __extends(Hinge2Joint, _super);
  91096. function Hinge2Joint(jointData) {
  91097. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  91098. }
  91099. /**
  91100. * Set the motor values.
  91101. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91102. * @param {number} force the force to apply
  91103. * @param {number} maxForce max force for this motor.
  91104. * @param {motorIndex} the motor's index, 0 or 1.
  91105. */
  91106. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  91107. if (motorIndex === void 0) { motorIndex = 0; }
  91108. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  91109. };
  91110. /**
  91111. * Set the motor limits.
  91112. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91113. * @param {number} upperLimit the upper limit
  91114. * @param {number} lowerLimit lower limit
  91115. * @param {motorIndex} the motor's index, 0 or 1.
  91116. */
  91117. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  91118. if (motorIndex === void 0) { motorIndex = 0; }
  91119. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  91120. };
  91121. return Hinge2Joint;
  91122. }(MotorEnabledJoint));
  91123. BABYLON.Hinge2Joint = Hinge2Joint;
  91124. })(BABYLON || (BABYLON = {}));
  91125. //# sourceMappingURL=babylon.physicsJoint.js.map
  91126. var BABYLON;
  91127. (function (BABYLON) {
  91128. var PhysicsImpostor = /** @class */ (function () {
  91129. function PhysicsImpostor(object, type, _options, _scene) {
  91130. if (_options === void 0) { _options = { mass: 0 }; }
  91131. var _this = this;
  91132. this.object = object;
  91133. this.type = type;
  91134. this._options = _options;
  91135. this._scene = _scene;
  91136. this._bodyUpdateRequired = false;
  91137. this._onBeforePhysicsStepCallbacks = new Array();
  91138. this._onAfterPhysicsStepCallbacks = new Array();
  91139. this._onPhysicsCollideCallbacks = [];
  91140. this._deltaPosition = BABYLON.Vector3.Zero();
  91141. this._isDisposed = false;
  91142. //temp variables for parent rotation calculations
  91143. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  91144. this._tmpQuat = new BABYLON.Quaternion();
  91145. this._tmpQuat2 = new BABYLON.Quaternion();
  91146. /**
  91147. * this function is executed by the physics engine.
  91148. */
  91149. this.beforeStep = function () {
  91150. if (!_this._physicsEngine) {
  91151. return;
  91152. }
  91153. _this.object.translate(_this._deltaPosition, -1);
  91154. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  91155. _this.object.computeWorldMatrix(false);
  91156. if (_this.object.parent && _this.object.rotationQuaternion) {
  91157. _this.getParentsRotation();
  91158. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  91159. }
  91160. else {
  91161. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  91162. }
  91163. if (!_this._options.disableBidirectionalTransformation) {
  91164. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  91165. }
  91166. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  91167. func(_this);
  91168. });
  91169. };
  91170. /**
  91171. * this function is executed by the physics engine.
  91172. */
  91173. this.afterStep = function () {
  91174. if (!_this._physicsEngine) {
  91175. return;
  91176. }
  91177. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  91178. func(_this);
  91179. });
  91180. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  91181. // object has now its world rotation. needs to be converted to local.
  91182. if (_this.object.parent && _this.object.rotationQuaternion) {
  91183. _this.getParentsRotation();
  91184. _this._tmpQuat.conjugateInPlace();
  91185. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  91186. }
  91187. // take the position set and make it the absolute position of this object.
  91188. _this.object.setAbsolutePosition(_this.object.position);
  91189. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  91190. _this.object.translate(_this._deltaPosition, 1);
  91191. };
  91192. /**
  91193. * Legacy collision detection event support
  91194. */
  91195. this.onCollideEvent = null;
  91196. //event and body object due to cannon's event-based architecture.
  91197. this.onCollide = function (e) {
  91198. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  91199. return;
  91200. }
  91201. if (!_this._physicsEngine) {
  91202. return;
  91203. }
  91204. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  91205. if (otherImpostor) {
  91206. // Legacy collision detection event support
  91207. if (_this.onCollideEvent) {
  91208. _this.onCollideEvent(_this, otherImpostor);
  91209. }
  91210. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  91211. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  91212. }).forEach(function (obj) {
  91213. obj.callback(_this, otherImpostor);
  91214. });
  91215. }
  91216. };
  91217. //sanity check!
  91218. if (!this.object) {
  91219. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  91220. return;
  91221. }
  91222. //legacy support for old syntax.
  91223. if (!this._scene && object.getScene) {
  91224. this._scene = object.getScene();
  91225. }
  91226. if (!this._scene) {
  91227. return;
  91228. }
  91229. this._physicsEngine = this._scene.getPhysicsEngine();
  91230. if (!this._physicsEngine) {
  91231. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  91232. }
  91233. else {
  91234. //set the object's quaternion, if not set
  91235. if (!this.object.rotationQuaternion) {
  91236. if (this.object.rotation) {
  91237. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  91238. }
  91239. else {
  91240. this.object.rotationQuaternion = new BABYLON.Quaternion();
  91241. }
  91242. }
  91243. //default options params
  91244. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  91245. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  91246. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  91247. this._joints = [];
  91248. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  91249. if (!this.object.parent || this._options.ignoreParent) {
  91250. this._init();
  91251. }
  91252. else if (this.object.parent.physicsImpostor) {
  91253. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  91254. }
  91255. }
  91256. }
  91257. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  91258. get: function () {
  91259. return this._isDisposed;
  91260. },
  91261. enumerable: true,
  91262. configurable: true
  91263. });
  91264. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  91265. get: function () {
  91266. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  91267. },
  91268. set: function (value) {
  91269. this.setMass(value);
  91270. },
  91271. enumerable: true,
  91272. configurable: true
  91273. });
  91274. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  91275. get: function () {
  91276. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  91277. },
  91278. set: function (value) {
  91279. if (!this._physicsEngine) {
  91280. return;
  91281. }
  91282. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  91283. },
  91284. enumerable: true,
  91285. configurable: true
  91286. });
  91287. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  91288. get: function () {
  91289. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  91290. },
  91291. set: function (value) {
  91292. if (!this._physicsEngine) {
  91293. return;
  91294. }
  91295. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  91296. },
  91297. enumerable: true,
  91298. configurable: true
  91299. });
  91300. /**
  91301. * This function will completly initialize this impostor.
  91302. * It will create a new body - but only if this mesh has no parent.
  91303. * If it has, this impostor will not be used other than to define the impostor
  91304. * of the child mesh.
  91305. * @hidden
  91306. */
  91307. PhysicsImpostor.prototype._init = function () {
  91308. if (!this._physicsEngine) {
  91309. return;
  91310. }
  91311. this._physicsEngine.removeImpostor(this);
  91312. this.physicsBody = null;
  91313. this._parent = this._parent || this._getPhysicsParent();
  91314. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  91315. this._physicsEngine.addImpostor(this);
  91316. }
  91317. };
  91318. PhysicsImpostor.prototype._getPhysicsParent = function () {
  91319. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  91320. var parentMesh = this.object.parent;
  91321. return parentMesh.physicsImpostor;
  91322. }
  91323. return null;
  91324. };
  91325. /**
  91326. * Should a new body be generated.
  91327. */
  91328. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  91329. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  91330. };
  91331. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  91332. this.forceUpdate();
  91333. };
  91334. /**
  91335. * Force a regeneration of this or the parent's impostor's body.
  91336. * Use under cautious - This will remove all joints already implemented.
  91337. */
  91338. PhysicsImpostor.prototype.forceUpdate = function () {
  91339. this._init();
  91340. if (this.parent && !this._options.ignoreParent) {
  91341. this.parent.forceUpdate();
  91342. }
  91343. };
  91344. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  91345. /*public get mesh(): AbstractMesh {
  91346. return this._mesh;
  91347. }*/
  91348. /**
  91349. * Gets the body that holds this impostor. Either its own, or its parent.
  91350. */
  91351. get: function () {
  91352. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  91353. },
  91354. /**
  91355. * Set the physics body. Used mainly by the physics engine/plugin
  91356. */
  91357. set: function (physicsBody) {
  91358. if (this._physicsBody && this._physicsEngine) {
  91359. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  91360. }
  91361. this._physicsBody = physicsBody;
  91362. this.resetUpdateFlags();
  91363. },
  91364. enumerable: true,
  91365. configurable: true
  91366. });
  91367. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  91368. get: function () {
  91369. return !this._options.ignoreParent && this._parent ? this._parent : null;
  91370. },
  91371. set: function (value) {
  91372. this._parent = value;
  91373. },
  91374. enumerable: true,
  91375. configurable: true
  91376. });
  91377. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  91378. this._bodyUpdateRequired = false;
  91379. };
  91380. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  91381. if (this.object.getBoundingInfo) {
  91382. var q = this.object.rotationQuaternion;
  91383. //reset rotation
  91384. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  91385. //calculate the world matrix with no rotation
  91386. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  91387. var boundingInfo = this.object.getBoundingInfo();
  91388. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  91389. //bring back the rotation
  91390. this.object.rotationQuaternion = q;
  91391. //calculate the world matrix with the new rotation
  91392. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  91393. return size;
  91394. }
  91395. else {
  91396. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  91397. }
  91398. };
  91399. PhysicsImpostor.prototype.getObjectCenter = function () {
  91400. if (this.object.getBoundingInfo) {
  91401. var boundingInfo = this.object.getBoundingInfo();
  91402. return boundingInfo.boundingBox.centerWorld;
  91403. }
  91404. else {
  91405. return this.object.position;
  91406. }
  91407. };
  91408. /**
  91409. * Get a specific parametes from the options parameter.
  91410. */
  91411. PhysicsImpostor.prototype.getParam = function (paramName) {
  91412. return this._options[paramName];
  91413. };
  91414. /**
  91415. * Sets a specific parameter in the options given to the physics plugin
  91416. */
  91417. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  91418. this._options[paramName] = value;
  91419. this._bodyUpdateRequired = true;
  91420. };
  91421. /**
  91422. * Specifically change the body's mass option. Won't recreate the physics body object
  91423. */
  91424. PhysicsImpostor.prototype.setMass = function (mass) {
  91425. if (this.getParam("mass") !== mass) {
  91426. this.setParam("mass", mass);
  91427. }
  91428. if (this._physicsEngine) {
  91429. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  91430. }
  91431. };
  91432. PhysicsImpostor.prototype.getLinearVelocity = function () {
  91433. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  91434. };
  91435. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  91436. if (this._physicsEngine) {
  91437. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  91438. }
  91439. };
  91440. PhysicsImpostor.prototype.getAngularVelocity = function () {
  91441. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  91442. };
  91443. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  91444. if (this._physicsEngine) {
  91445. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  91446. }
  91447. };
  91448. /**
  91449. * Execute a function with the physics plugin native code.
  91450. * Provide a function the will have two variables - the world object and the physics body object.
  91451. */
  91452. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  91453. if (this._physicsEngine) {
  91454. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  91455. }
  91456. };
  91457. /**
  91458. * Register a function that will be executed before the physics world is stepping forward.
  91459. */
  91460. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  91461. this._onBeforePhysicsStepCallbacks.push(func);
  91462. };
  91463. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  91464. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  91465. if (index > -1) {
  91466. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  91467. }
  91468. else {
  91469. BABYLON.Tools.Warn("Function to remove was not found");
  91470. }
  91471. };
  91472. /**
  91473. * Register a function that will be executed after the physics step
  91474. */
  91475. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  91476. this._onAfterPhysicsStepCallbacks.push(func);
  91477. };
  91478. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  91479. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  91480. if (index > -1) {
  91481. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  91482. }
  91483. else {
  91484. BABYLON.Tools.Warn("Function to remove was not found");
  91485. }
  91486. };
  91487. /**
  91488. * register a function that will be executed when this impostor collides against a different body.
  91489. */
  91490. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  91491. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  91492. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  91493. };
  91494. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  91495. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  91496. var index = -1;
  91497. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  91498. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  91499. // chcek the arrays match
  91500. var sameList = cbDef.otherImpostors.every(function (impostor) {
  91501. return collidedAgainstList.indexOf(impostor) > -1;
  91502. });
  91503. if (sameList) {
  91504. index = idx;
  91505. }
  91506. return sameList;
  91507. }
  91508. return false;
  91509. });
  91510. if (found) {
  91511. this._onPhysicsCollideCallbacks.splice(index, 1);
  91512. }
  91513. else {
  91514. BABYLON.Tools.Warn("Function to remove was not found");
  91515. }
  91516. };
  91517. PhysicsImpostor.prototype.getParentsRotation = function () {
  91518. var parent = this.object.parent;
  91519. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  91520. while (parent) {
  91521. if (parent.rotationQuaternion) {
  91522. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  91523. }
  91524. else {
  91525. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  91526. }
  91527. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  91528. parent = parent.parent;
  91529. }
  91530. return this._tmpQuat;
  91531. };
  91532. /**
  91533. * Apply a force
  91534. */
  91535. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  91536. if (this._physicsEngine) {
  91537. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  91538. }
  91539. return this;
  91540. };
  91541. /**
  91542. * Apply an impulse
  91543. */
  91544. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  91545. if (this._physicsEngine) {
  91546. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  91547. }
  91548. return this;
  91549. };
  91550. /**
  91551. * A help function to create a joint.
  91552. */
  91553. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  91554. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  91555. this.addJoint(otherImpostor, joint);
  91556. return this;
  91557. };
  91558. /**
  91559. * Add a joint to this impostor with a different impostor.
  91560. */
  91561. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  91562. this._joints.push({
  91563. otherImpostor: otherImpostor,
  91564. joint: joint
  91565. });
  91566. if (this._physicsEngine) {
  91567. this._physicsEngine.addJoint(this, otherImpostor, joint);
  91568. }
  91569. return this;
  91570. };
  91571. /**
  91572. * Will keep this body still, in a sleep mode.
  91573. */
  91574. PhysicsImpostor.prototype.sleep = function () {
  91575. if (this._physicsEngine) {
  91576. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  91577. }
  91578. return this;
  91579. };
  91580. /**
  91581. * Wake the body up.
  91582. */
  91583. PhysicsImpostor.prototype.wakeUp = function () {
  91584. if (this._physicsEngine) {
  91585. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  91586. }
  91587. return this;
  91588. };
  91589. PhysicsImpostor.prototype.clone = function (newObject) {
  91590. if (!newObject)
  91591. return null;
  91592. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  91593. };
  91594. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  91595. var _this = this;
  91596. //no dispose if no physics engine is available.
  91597. if (!this._physicsEngine) {
  91598. return;
  91599. }
  91600. this._joints.forEach(function (j) {
  91601. if (_this._physicsEngine) {
  91602. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  91603. }
  91604. });
  91605. //dispose the physics body
  91606. this._physicsEngine.removeImpostor(this);
  91607. if (this.parent) {
  91608. this.parent.forceUpdate();
  91609. }
  91610. else {
  91611. /*this._object.getChildMeshes().forEach(function(mesh) {
  91612. if (mesh.physicsImpostor) {
  91613. if (disposeChildren) {
  91614. mesh.physicsImpostor.dispose();
  91615. mesh.physicsImpostor = null;
  91616. }
  91617. }
  91618. })*/
  91619. }
  91620. this._isDisposed = true;
  91621. };
  91622. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  91623. this._deltaPosition.copyFrom(position);
  91624. };
  91625. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  91626. if (!this._deltaRotation) {
  91627. this._deltaRotation = new BABYLON.Quaternion();
  91628. }
  91629. this._deltaRotation.copyFrom(rotation);
  91630. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  91631. };
  91632. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  91633. if (this._physicsEngine) {
  91634. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  91635. }
  91636. return this;
  91637. };
  91638. PhysicsImpostor.prototype.getRadius = function () {
  91639. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  91640. };
  91641. /**
  91642. * Sync a bone with this impostor
  91643. * @param bone The bone to sync to the impostor.
  91644. * @param boneMesh The mesh that the bone is influencing.
  91645. * @param jointPivot The pivot of the joint / bone in local space.
  91646. * @param distToJoint Optional distance from the impostor to the joint.
  91647. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  91648. */
  91649. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  91650. var tempVec = PhysicsImpostor._tmpVecs[0];
  91651. var mesh = this.object;
  91652. if (mesh.rotationQuaternion) {
  91653. if (adjustRotation) {
  91654. var tempQuat = PhysicsImpostor._tmpQuat;
  91655. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  91656. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  91657. }
  91658. else {
  91659. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  91660. }
  91661. }
  91662. tempVec.x = 0;
  91663. tempVec.y = 0;
  91664. tempVec.z = 0;
  91665. if (jointPivot) {
  91666. tempVec.x = jointPivot.x;
  91667. tempVec.y = jointPivot.y;
  91668. tempVec.z = jointPivot.z;
  91669. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  91670. if (distToJoint === undefined || distToJoint === null) {
  91671. distToJoint = jointPivot.length();
  91672. }
  91673. tempVec.x *= distToJoint;
  91674. tempVec.y *= distToJoint;
  91675. tempVec.z *= distToJoint;
  91676. }
  91677. if (bone.getParent()) {
  91678. tempVec.addInPlace(mesh.getAbsolutePosition());
  91679. bone.setAbsolutePosition(tempVec, boneMesh);
  91680. }
  91681. else {
  91682. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  91683. boneMesh.position.x -= tempVec.x;
  91684. boneMesh.position.y -= tempVec.y;
  91685. boneMesh.position.z -= tempVec.z;
  91686. }
  91687. };
  91688. /**
  91689. * Sync impostor to a bone
  91690. * @param bone The bone that the impostor will be synced to.
  91691. * @param boneMesh The mesh that the bone is influencing.
  91692. * @param jointPivot The pivot of the joint / bone in local space.
  91693. * @param distToJoint Optional distance from the impostor to the joint.
  91694. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  91695. * @param boneAxis Optional vector3 axis the bone is aligned with
  91696. */
  91697. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  91698. var mesh = this.object;
  91699. if (mesh.rotationQuaternion) {
  91700. if (adjustRotation) {
  91701. var tempQuat = PhysicsImpostor._tmpQuat;
  91702. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  91703. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  91704. }
  91705. else {
  91706. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  91707. }
  91708. }
  91709. var pos = PhysicsImpostor._tmpVecs[0];
  91710. var boneDir = PhysicsImpostor._tmpVecs[1];
  91711. if (!boneAxis) {
  91712. boneAxis = PhysicsImpostor._tmpVecs[2];
  91713. boneAxis.x = 0;
  91714. boneAxis.y = 1;
  91715. boneAxis.z = 0;
  91716. }
  91717. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  91718. bone.getAbsolutePositionToRef(boneMesh, pos);
  91719. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  91720. distToJoint = jointPivot.length();
  91721. }
  91722. if (distToJoint !== undefined && distToJoint !== null) {
  91723. pos.x += boneDir.x * distToJoint;
  91724. pos.y += boneDir.y * distToJoint;
  91725. pos.z += boneDir.z * distToJoint;
  91726. }
  91727. mesh.setAbsolutePosition(pos);
  91728. };
  91729. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  91730. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  91731. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91732. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  91733. //Impostor types
  91734. PhysicsImpostor.NoImpostor = 0;
  91735. PhysicsImpostor.SphereImpostor = 1;
  91736. PhysicsImpostor.BoxImpostor = 2;
  91737. PhysicsImpostor.PlaneImpostor = 3;
  91738. PhysicsImpostor.MeshImpostor = 4;
  91739. PhysicsImpostor.CylinderImpostor = 7;
  91740. PhysicsImpostor.ParticleImpostor = 8;
  91741. PhysicsImpostor.HeightmapImpostor = 9;
  91742. return PhysicsImpostor;
  91743. }());
  91744. BABYLON.PhysicsImpostor = PhysicsImpostor;
  91745. })(BABYLON || (BABYLON = {}));
  91746. //# sourceMappingURL=babylon.physicsImpostor.js.map
  91747. var BABYLON;
  91748. (function (BABYLON) {
  91749. /**
  91750. * Class used to control physics engine
  91751. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  91752. */
  91753. var PhysicsEngine = /** @class */ (function () {
  91754. /**
  91755. * Creates a new Physics Engine
  91756. * @param gravity defines the gravity vector used by the simulation
  91757. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  91758. */
  91759. function PhysicsEngine(gravity, _physicsPlugin) {
  91760. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  91761. this._physicsPlugin = _physicsPlugin;
  91762. this._impostors = [];
  91763. this._joints = [];
  91764. if (!this._physicsPlugin.isSupported()) {
  91765. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  91766. + "Please make sure it is included.");
  91767. }
  91768. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  91769. this.setGravity(gravity);
  91770. this.setTimeStep();
  91771. }
  91772. /**
  91773. * Sets the gravity vector used by the simulation
  91774. * @param gravity defines the gravity vector to use
  91775. */
  91776. PhysicsEngine.prototype.setGravity = function (gravity) {
  91777. this.gravity = gravity;
  91778. this._physicsPlugin.setGravity(this.gravity);
  91779. };
  91780. /**
  91781. * Set the time step of the physics engine.
  91782. * Default is 1/60.
  91783. * To slow it down, enter 1/600 for example.
  91784. * To speed it up, 1/30
  91785. * @param newTimeStep defines the new timestep to apply to this world.
  91786. */
  91787. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  91788. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  91789. this._physicsPlugin.setTimeStep(newTimeStep);
  91790. };
  91791. /**
  91792. * Get the time step of the physics engine.
  91793. * @returns the current time step
  91794. */
  91795. PhysicsEngine.prototype.getTimeStep = function () {
  91796. return this._physicsPlugin.getTimeStep();
  91797. };
  91798. /**
  91799. * Release all resources
  91800. */
  91801. PhysicsEngine.prototype.dispose = function () {
  91802. this._impostors.forEach(function (impostor) {
  91803. impostor.dispose();
  91804. });
  91805. this._physicsPlugin.dispose();
  91806. };
  91807. /**
  91808. * Gets the name of the current physics plugin
  91809. * @returns the name of the plugin
  91810. */
  91811. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  91812. return this._physicsPlugin.name;
  91813. };
  91814. /**
  91815. * Adding a new impostor for the impostor tracking.
  91816. * This will be done by the impostor itself.
  91817. * @param impostor the impostor to add
  91818. */
  91819. PhysicsEngine.prototype.addImpostor = function (impostor) {
  91820. impostor.uniqueId = this._impostors.push(impostor);
  91821. //if no parent, generate the body
  91822. if (!impostor.parent) {
  91823. this._physicsPlugin.generatePhysicsBody(impostor);
  91824. }
  91825. };
  91826. /**
  91827. * Remove an impostor from the engine.
  91828. * This impostor and its mesh will not longer be updated by the physics engine.
  91829. * @param impostor the impostor to remove
  91830. */
  91831. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  91832. var index = this._impostors.indexOf(impostor);
  91833. if (index > -1) {
  91834. var removed = this._impostors.splice(index, 1);
  91835. //Is it needed?
  91836. if (removed.length) {
  91837. //this will also remove it from the world.
  91838. removed[0].physicsBody = null;
  91839. }
  91840. }
  91841. };
  91842. /**
  91843. * Add a joint to the physics engine
  91844. * @param mainImpostor defines the main impostor to which the joint is added.
  91845. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  91846. * @param joint defines the joint that will connect both impostors.
  91847. */
  91848. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  91849. var impostorJoint = {
  91850. mainImpostor: mainImpostor,
  91851. connectedImpostor: connectedImpostor,
  91852. joint: joint
  91853. };
  91854. joint.physicsPlugin = this._physicsPlugin;
  91855. this._joints.push(impostorJoint);
  91856. this._physicsPlugin.generateJoint(impostorJoint);
  91857. };
  91858. /**
  91859. * Removes a joint from the simulation
  91860. * @param mainImpostor defines the impostor used with the joint
  91861. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  91862. * @param joint defines the joint to remove
  91863. */
  91864. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  91865. var matchingJoints = this._joints.filter(function (impostorJoint) {
  91866. return (impostorJoint.connectedImpostor === connectedImpostor
  91867. && impostorJoint.joint === joint
  91868. && impostorJoint.mainImpostor === mainImpostor);
  91869. });
  91870. if (matchingJoints.length) {
  91871. this._physicsPlugin.removeJoint(matchingJoints[0]);
  91872. //TODO remove it from the list as well
  91873. }
  91874. };
  91875. /**
  91876. * Called by the scene. No need to call it.
  91877. * @param delta defines the timespam between frames
  91878. */
  91879. PhysicsEngine.prototype._step = function (delta) {
  91880. var _this = this;
  91881. //check if any mesh has no body / requires an update
  91882. this._impostors.forEach(function (impostor) {
  91883. if (impostor.isBodyInitRequired()) {
  91884. _this._physicsPlugin.generatePhysicsBody(impostor);
  91885. }
  91886. });
  91887. if (delta > 0.1) {
  91888. delta = 0.1;
  91889. }
  91890. else if (delta <= 0) {
  91891. delta = 1.0 / 60.0;
  91892. }
  91893. this._physicsPlugin.executeStep(delta, this._impostors);
  91894. };
  91895. /**
  91896. * Gets the current plugin used to run the simulation
  91897. * @returns current plugin
  91898. */
  91899. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  91900. return this._physicsPlugin;
  91901. };
  91902. /**
  91903. * Gets the list of physic impostors
  91904. * @returns an array of PhysicsImpostor
  91905. */
  91906. PhysicsEngine.prototype.getImpostors = function () {
  91907. return this._impostors;
  91908. };
  91909. /**
  91910. * Gets the impostor for a physics enabled object
  91911. * @param object defines the object impersonated by the impostor
  91912. * @returns the PhysicsImpostor or null if not found
  91913. */
  91914. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  91915. for (var i = 0; i < this._impostors.length; ++i) {
  91916. if (this._impostors[i].object === object) {
  91917. return this._impostors[i];
  91918. }
  91919. }
  91920. return null;
  91921. };
  91922. /**
  91923. * Gets the impostor for a physics body object
  91924. * @param body defines physics body used by the impostor
  91925. * @returns the PhysicsImpostor or null if not found
  91926. */
  91927. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  91928. for (var i = 0; i < this._impostors.length; ++i) {
  91929. if (this._impostors[i].physicsBody === body) {
  91930. return this._impostors[i];
  91931. }
  91932. }
  91933. return null;
  91934. };
  91935. /**
  91936. * Global value used to control the smallest number supported by the simulation
  91937. */
  91938. PhysicsEngine.Epsilon = 0.001;
  91939. return PhysicsEngine;
  91940. }());
  91941. BABYLON.PhysicsEngine = PhysicsEngine;
  91942. })(BABYLON || (BABYLON = {}));
  91943. //# sourceMappingURL=babylon.physicsEngine.js.map
  91944. var BABYLON;
  91945. (function (BABYLON) {
  91946. var PhysicsHelper = /** @class */ (function () {
  91947. function PhysicsHelper(scene) {
  91948. this._scene = scene;
  91949. this._physicsEngine = this._scene.getPhysicsEngine();
  91950. if (!this._physicsEngine) {
  91951. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  91952. }
  91953. }
  91954. /**
  91955. * @param {Vector3} origin the origin of the explosion
  91956. * @param {number} radius the explosion radius
  91957. * @param {number} strength the explosion strength
  91958. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91959. */
  91960. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  91961. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91962. if (!this._physicsEngine) {
  91963. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  91964. return null;
  91965. }
  91966. var impostors = this._physicsEngine.getImpostors();
  91967. if (impostors.length === 0) {
  91968. return null;
  91969. }
  91970. var event = new PhysicsRadialExplosionEvent(this._scene);
  91971. impostors.forEach(function (impostor) {
  91972. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  91973. if (!impostorForceAndContactPoint) {
  91974. return;
  91975. }
  91976. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91977. });
  91978. event.dispose(false);
  91979. return event;
  91980. };
  91981. /**
  91982. * @param {Vector3} origin the origin of the explosion
  91983. * @param {number} radius the explosion radius
  91984. * @param {number} strength the explosion strength
  91985. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91986. */
  91987. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  91988. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91989. if (!this._physicsEngine) {
  91990. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91991. return null;
  91992. }
  91993. var impostors = this._physicsEngine.getImpostors();
  91994. if (impostors.length === 0) {
  91995. return null;
  91996. }
  91997. var event = new PhysicsRadialExplosionEvent(this._scene);
  91998. impostors.forEach(function (impostor) {
  91999. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  92000. if (!impostorForceAndContactPoint) {
  92001. return;
  92002. }
  92003. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92004. });
  92005. event.dispose(false);
  92006. return event;
  92007. };
  92008. /**
  92009. * @param {Vector3} origin the origin of the explosion
  92010. * @param {number} radius the explosion radius
  92011. * @param {number} strength the explosion strength
  92012. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  92013. */
  92014. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  92015. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92016. if (!this._physicsEngine) {
  92017. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92018. return null;
  92019. }
  92020. var impostors = this._physicsEngine.getImpostors();
  92021. if (impostors.length === 0) {
  92022. return null;
  92023. }
  92024. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  92025. event.dispose(false);
  92026. return event;
  92027. };
  92028. /**
  92029. * @param {Vector3} origin the origin of the updraft
  92030. * @param {number} radius the radius of the updraft
  92031. * @param {number} strength the strength of the updraft
  92032. * @param {number} height the height of the updraft
  92033. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  92034. */
  92035. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  92036. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  92037. if (!this._physicsEngine) {
  92038. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92039. return null;
  92040. }
  92041. if (this._physicsEngine.getImpostors().length === 0) {
  92042. return null;
  92043. }
  92044. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  92045. event.dispose(false);
  92046. return event;
  92047. };
  92048. /**
  92049. * @param {Vector3} origin the of the vortex
  92050. * @param {number} radius the radius of the vortex
  92051. * @param {number} strength the strength of the vortex
  92052. * @param {number} height the height of the vortex
  92053. */
  92054. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  92055. if (!this._physicsEngine) {
  92056. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92057. return null;
  92058. }
  92059. if (this._physicsEngine.getImpostors().length === 0) {
  92060. return null;
  92061. }
  92062. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  92063. event.dispose(false);
  92064. return event;
  92065. };
  92066. return PhysicsHelper;
  92067. }());
  92068. BABYLON.PhysicsHelper = PhysicsHelper;
  92069. /***** Radial explosion *****/
  92070. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  92071. function PhysicsRadialExplosionEvent(scene) {
  92072. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  92073. this._rays = [];
  92074. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  92075. this._scene = scene;
  92076. }
  92077. /**
  92078. * Returns the data related to the radial explosion event (sphere & rays).
  92079. * @returns {PhysicsRadialExplosionEventData}
  92080. */
  92081. PhysicsRadialExplosionEvent.prototype.getData = function () {
  92082. this._dataFetched = true;
  92083. return {
  92084. sphere: this._sphere,
  92085. rays: this._rays,
  92086. };
  92087. };
  92088. /**
  92089. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  92090. * @param impostor
  92091. * @param {Vector3} origin the origin of the explosion
  92092. * @param {number} radius the explosion radius
  92093. * @param {number} strength the explosion strength
  92094. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  92095. * @returns {Nullable<PhysicsForceAndContactPoint>}
  92096. */
  92097. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  92098. if (impostor.mass === 0) {
  92099. return null;
  92100. }
  92101. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  92102. return null;
  92103. }
  92104. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  92105. return null;
  92106. }
  92107. var impostorObjectCenter = impostor.getObjectCenter();
  92108. var direction = impostorObjectCenter.subtract(origin);
  92109. var ray = new BABYLON.Ray(origin, direction, radius);
  92110. this._rays.push(ray);
  92111. var hit = ray.intersectsMesh(impostor.object);
  92112. var contactPoint = hit.pickedPoint;
  92113. if (!contactPoint) {
  92114. return null;
  92115. }
  92116. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  92117. if (distanceFromOrigin > radius) {
  92118. return null;
  92119. }
  92120. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  92121. ? strength
  92122. : strength * (1 - (distanceFromOrigin / radius));
  92123. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  92124. return { force: force, contactPoint: contactPoint };
  92125. };
  92126. /**
  92127. * Disposes the sphere.
  92128. * @param {bolean} force
  92129. */
  92130. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  92131. var _this = this;
  92132. if (force === void 0) { force = true; }
  92133. if (force) {
  92134. this._sphere.dispose();
  92135. }
  92136. else {
  92137. setTimeout(function () {
  92138. if (!_this._dataFetched) {
  92139. _this._sphere.dispose();
  92140. }
  92141. }, 0);
  92142. }
  92143. };
  92144. /*** Helpers ***/
  92145. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  92146. if (!this._sphere) {
  92147. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  92148. this._sphere.isVisible = false;
  92149. }
  92150. };
  92151. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  92152. var impostorObject = impostor.object;
  92153. this._prepareSphere();
  92154. this._sphere.position = origin;
  92155. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  92156. this._sphere._updateBoundingInfo();
  92157. this._sphere.computeWorldMatrix(true);
  92158. return this._sphere.intersectsMesh(impostorObject, true);
  92159. };
  92160. return PhysicsRadialExplosionEvent;
  92161. }());
  92162. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  92163. /***** Gravitational Field *****/
  92164. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  92165. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  92166. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92167. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92168. this._physicsHelper = physicsHelper;
  92169. this._scene = scene;
  92170. this._origin = origin;
  92171. this._radius = radius;
  92172. this._strength = strength;
  92173. this._falloff = falloff;
  92174. this._tickCallback = this._tick.bind(this);
  92175. }
  92176. /**
  92177. * Returns the data related to the gravitational field event (sphere).
  92178. * @returns {PhysicsGravitationalFieldEventData}
  92179. */
  92180. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  92181. this._dataFetched = true;
  92182. return {
  92183. sphere: this._sphere,
  92184. };
  92185. };
  92186. /**
  92187. * Enables the gravitational field.
  92188. */
  92189. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  92190. this._tickCallback.call(this);
  92191. this._scene.registerBeforeRender(this._tickCallback);
  92192. };
  92193. /**
  92194. * Disables the gravitational field.
  92195. */
  92196. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  92197. this._scene.unregisterBeforeRender(this._tickCallback);
  92198. };
  92199. /**
  92200. * Disposes the sphere.
  92201. * @param {bolean} force
  92202. */
  92203. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  92204. var _this = this;
  92205. if (force === void 0) { force = true; }
  92206. if (force) {
  92207. this._sphere.dispose();
  92208. }
  92209. else {
  92210. setTimeout(function () {
  92211. if (!_this._dataFetched) {
  92212. _this._sphere.dispose();
  92213. }
  92214. }, 0);
  92215. }
  92216. };
  92217. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  92218. // Since the params won't change, we fetch the event only once
  92219. if (this._sphere) {
  92220. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  92221. }
  92222. else {
  92223. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  92224. if (radialExplosionEvent) {
  92225. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  92226. }
  92227. }
  92228. };
  92229. return PhysicsGravitationalFieldEvent;
  92230. }());
  92231. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  92232. /***** Updraft *****/
  92233. var PhysicsUpdraftEvent = /** @class */ (function () {
  92234. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  92235. this._scene = _scene;
  92236. this._origin = _origin;
  92237. this._radius = _radius;
  92238. this._strength = _strength;
  92239. this._height = _height;
  92240. this._updraftMode = _updraftMode;
  92241. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  92242. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  92243. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  92244. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92245. this._physicsEngine = this._scene.getPhysicsEngine();
  92246. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  92247. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  92248. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  92249. this._originDirection = this._origin.subtract(this._originTop).normalize();
  92250. }
  92251. this._tickCallback = this._tick.bind(this);
  92252. }
  92253. /**
  92254. * Returns the data related to the updraft event (cylinder).
  92255. * @returns {PhysicsUpdraftEventData}
  92256. */
  92257. PhysicsUpdraftEvent.prototype.getData = function () {
  92258. this._dataFetched = true;
  92259. return {
  92260. cylinder: this._cylinder,
  92261. };
  92262. };
  92263. /**
  92264. * Enables the updraft.
  92265. */
  92266. PhysicsUpdraftEvent.prototype.enable = function () {
  92267. this._tickCallback.call(this);
  92268. this._scene.registerBeforeRender(this._tickCallback);
  92269. };
  92270. /**
  92271. * Disables the cortex.
  92272. */
  92273. PhysicsUpdraftEvent.prototype.disable = function () {
  92274. this._scene.unregisterBeforeRender(this._tickCallback);
  92275. };
  92276. /**
  92277. * Disposes the sphere.
  92278. * @param {bolean} force
  92279. */
  92280. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  92281. var _this = this;
  92282. if (force === void 0) { force = true; }
  92283. if (force) {
  92284. this._cylinder.dispose();
  92285. }
  92286. else {
  92287. setTimeout(function () {
  92288. if (!_this._dataFetched) {
  92289. _this._cylinder.dispose();
  92290. }
  92291. }, 0);
  92292. }
  92293. };
  92294. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  92295. if (impostor.mass === 0) {
  92296. return null;
  92297. }
  92298. if (!this._intersectsWithCylinder(impostor)) {
  92299. return null;
  92300. }
  92301. var impostorObjectCenter = impostor.getObjectCenter();
  92302. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  92303. var direction = this._originDirection;
  92304. }
  92305. else {
  92306. var direction = impostorObjectCenter.subtract(this._originTop);
  92307. }
  92308. var multiplier = this._strength * -1;
  92309. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  92310. return { force: force, contactPoint: impostorObjectCenter };
  92311. };
  92312. PhysicsUpdraftEvent.prototype._tick = function () {
  92313. var _this = this;
  92314. this._physicsEngine.getImpostors().forEach(function (impostor) {
  92315. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  92316. if (!impostorForceAndContactPoint) {
  92317. return;
  92318. }
  92319. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92320. });
  92321. };
  92322. /*** Helpers ***/
  92323. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  92324. if (!this._cylinder) {
  92325. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  92326. height: this._height,
  92327. diameter: this._radius * 2,
  92328. }, this._scene);
  92329. this._cylinder.isVisible = false;
  92330. }
  92331. };
  92332. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  92333. var impostorObject = impostor.object;
  92334. this._prepareCylinder();
  92335. this._cylinder.position = this._cylinderPosition;
  92336. return this._cylinder.intersectsMesh(impostorObject, true);
  92337. };
  92338. return PhysicsUpdraftEvent;
  92339. }());
  92340. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  92341. /***** Vortex *****/
  92342. var PhysicsVortexEvent = /** @class */ (function () {
  92343. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  92344. this._scene = _scene;
  92345. this._origin = _origin;
  92346. this._radius = _radius;
  92347. this._strength = _strength;
  92348. this._height = _height;
  92349. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  92350. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  92351. this._updraftMultiplier = 0.02;
  92352. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  92353. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92354. this._physicsEngine = this._scene.getPhysicsEngine();
  92355. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  92356. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  92357. this._tickCallback = this._tick.bind(this);
  92358. }
  92359. /**
  92360. * Returns the data related to the vortex event (cylinder).
  92361. * @returns {PhysicsVortexEventData}
  92362. */
  92363. PhysicsVortexEvent.prototype.getData = function () {
  92364. this._dataFetched = true;
  92365. return {
  92366. cylinder: this._cylinder,
  92367. };
  92368. };
  92369. /**
  92370. * Enables the vortex.
  92371. */
  92372. PhysicsVortexEvent.prototype.enable = function () {
  92373. this._tickCallback.call(this);
  92374. this._scene.registerBeforeRender(this._tickCallback);
  92375. };
  92376. /**
  92377. * Disables the cortex.
  92378. */
  92379. PhysicsVortexEvent.prototype.disable = function () {
  92380. this._scene.unregisterBeforeRender(this._tickCallback);
  92381. };
  92382. /**
  92383. * Disposes the sphere.
  92384. * @param {bolean} force
  92385. */
  92386. PhysicsVortexEvent.prototype.dispose = function (force) {
  92387. var _this = this;
  92388. if (force === void 0) { force = true; }
  92389. if (force) {
  92390. this._cylinder.dispose();
  92391. }
  92392. else {
  92393. setTimeout(function () {
  92394. if (!_this._dataFetched) {
  92395. _this._cylinder.dispose();
  92396. }
  92397. }, 0);
  92398. }
  92399. };
  92400. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  92401. if (impostor.mass === 0) {
  92402. return null;
  92403. }
  92404. if (!this._intersectsWithCylinder(impostor)) {
  92405. return null;
  92406. }
  92407. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  92408. return null;
  92409. }
  92410. var impostorObjectCenter = impostor.getObjectCenter();
  92411. 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)
  92412. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  92413. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  92414. var hit = ray.intersectsMesh(impostor.object);
  92415. var contactPoint = hit.pickedPoint;
  92416. if (!contactPoint) {
  92417. return null;
  92418. }
  92419. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  92420. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  92421. var directionToOrigin = contactPoint.normalize();
  92422. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  92423. directionToOrigin = directionToOrigin.negate();
  92424. }
  92425. // TODO: find a more physically based solution
  92426. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  92427. var forceX = directionToOrigin.x * this._strength / 8;
  92428. var forceY = directionToOrigin.y * this._updraftMultiplier;
  92429. var forceZ = directionToOrigin.z * this._strength / 8;
  92430. }
  92431. else {
  92432. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  92433. var forceY = this._originTop.y * this._updraftMultiplier;
  92434. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  92435. }
  92436. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  92437. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  92438. return { force: force, contactPoint: impostorObjectCenter };
  92439. };
  92440. PhysicsVortexEvent.prototype._tick = function () {
  92441. var _this = this;
  92442. this._physicsEngine.getImpostors().forEach(function (impostor) {
  92443. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  92444. if (!impostorForceAndContactPoint) {
  92445. return;
  92446. }
  92447. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92448. });
  92449. };
  92450. /*** Helpers ***/
  92451. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  92452. if (!this._cylinder) {
  92453. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  92454. height: this._height,
  92455. diameter: this._radius * 2,
  92456. }, this._scene);
  92457. this._cylinder.isVisible = false;
  92458. }
  92459. };
  92460. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  92461. var impostorObject = impostor.object;
  92462. this._prepareCylinder();
  92463. this._cylinder.position = this._cylinderPosition;
  92464. return this._cylinder.intersectsMesh(impostorObject, true);
  92465. };
  92466. return PhysicsVortexEvent;
  92467. }());
  92468. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  92469. /***** Enums *****/
  92470. /**
  92471. * The strenght of the force in correspondence to the distance of the affected object
  92472. */
  92473. var PhysicsRadialImpulseFalloff;
  92474. (function (PhysicsRadialImpulseFalloff) {
  92475. /** Defines that impulse is constant in strength across it's whole radius */
  92476. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  92477. /** DEfines that impulse gets weaker if it's further from the origin */
  92478. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  92479. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  92480. /**
  92481. * The strenght of the force in correspondence to the distance of the affected object
  92482. */
  92483. var PhysicsUpdraftMode;
  92484. (function (PhysicsUpdraftMode) {
  92485. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  92486. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  92487. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  92488. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  92489. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  92490. })(BABYLON || (BABYLON = {}));
  92491. //# sourceMappingURL=babylon.physicsHelper.js.map
  92492. var BABYLON;
  92493. (function (BABYLON) {
  92494. /** @hidden */
  92495. var CannonJSPlugin = /** @class */ (function () {
  92496. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  92497. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  92498. if (iterations === void 0) { iterations = 10; }
  92499. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  92500. this.name = "CannonJSPlugin";
  92501. this._physicsMaterials = new Array();
  92502. this._fixedTimeStep = 1 / 60;
  92503. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  92504. this.BJSCANNON = CANNON;
  92505. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  92506. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  92507. this._tmpPosition = BABYLON.Vector3.Zero();
  92508. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  92509. this._tmpUnityRotation = new BABYLON.Quaternion();
  92510. if (!this.isSupported()) {
  92511. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  92512. return;
  92513. }
  92514. this._extendNamespace();
  92515. this.world = new this.BJSCANNON.World();
  92516. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  92517. this.world.solver.iterations = iterations;
  92518. }
  92519. CannonJSPlugin.prototype.setGravity = function (gravity) {
  92520. this.world.gravity.copy(gravity);
  92521. };
  92522. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  92523. this._fixedTimeStep = timeStep;
  92524. };
  92525. CannonJSPlugin.prototype.getTimeStep = function () {
  92526. return this._fixedTimeStep;
  92527. };
  92528. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  92529. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  92530. };
  92531. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  92532. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  92533. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  92534. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  92535. };
  92536. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  92537. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  92538. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  92539. impostor.physicsBody.applyForce(impulse, worldPoint);
  92540. };
  92541. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  92542. //parent-child relationship. Does this impostor has a parent impostor?
  92543. if (impostor.parent) {
  92544. if (impostor.physicsBody) {
  92545. this.removePhysicsBody(impostor);
  92546. //TODO is that needed?
  92547. impostor.forceUpdate();
  92548. }
  92549. return;
  92550. }
  92551. //should a new body be created for this impostor?
  92552. if (impostor.isBodyInitRequired()) {
  92553. var shape = this._createShape(impostor);
  92554. //unregister events, if body is being changed
  92555. var oldBody = impostor.physicsBody;
  92556. if (oldBody) {
  92557. this.removePhysicsBody(impostor);
  92558. }
  92559. //create the body and material
  92560. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  92561. var bodyCreationObject = {
  92562. mass: impostor.getParam("mass"),
  92563. material: material
  92564. };
  92565. // A simple extend, in case native options were used.
  92566. var nativeOptions = impostor.getParam("nativeOptions");
  92567. for (var key in nativeOptions) {
  92568. if (nativeOptions.hasOwnProperty(key)) {
  92569. bodyCreationObject[key] = nativeOptions[key];
  92570. }
  92571. }
  92572. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  92573. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  92574. this.world.addEventListener("preStep", impostor.beforeStep);
  92575. this.world.addEventListener("postStep", impostor.afterStep);
  92576. impostor.physicsBody.addShape(shape);
  92577. this.world.add(impostor.physicsBody);
  92578. //try to keep the body moving in the right direction by taking old properties.
  92579. //Should be tested!
  92580. if (oldBody) {
  92581. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  92582. impostor.physicsBody[param].copy(oldBody[param]);
  92583. });
  92584. }
  92585. this._processChildMeshes(impostor);
  92586. }
  92587. //now update the body's transformation
  92588. this._updatePhysicsBodyTransformation(impostor);
  92589. };
  92590. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  92591. var _this = this;
  92592. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  92593. var currentRotation = mainImpostor.object.rotationQuaternion;
  92594. if (meshChildren.length) {
  92595. var processMesh = function (localPosition, mesh) {
  92596. if (!currentRotation || !mesh.rotationQuaternion) {
  92597. return;
  92598. }
  92599. var childImpostor = mesh.getPhysicsImpostor();
  92600. if (childImpostor) {
  92601. var parent = childImpostor.parent;
  92602. if (parent !== mainImpostor) {
  92603. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  92604. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  92605. if (childImpostor.physicsBody) {
  92606. _this.removePhysicsBody(childImpostor);
  92607. childImpostor.physicsBody = null;
  92608. }
  92609. childImpostor.parent = mainImpostor;
  92610. childImpostor.resetUpdateFlags();
  92611. 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));
  92612. //Add the mass of the children.
  92613. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  92614. }
  92615. }
  92616. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  92617. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  92618. };
  92619. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  92620. }
  92621. };
  92622. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  92623. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  92624. this.world.removeEventListener("preStep", impostor.beforeStep);
  92625. this.world.removeEventListener("postStep", impostor.afterStep);
  92626. this.world.remove(impostor.physicsBody);
  92627. };
  92628. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  92629. var mainBody = impostorJoint.mainImpostor.physicsBody;
  92630. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  92631. if (!mainBody || !connectedBody) {
  92632. return;
  92633. }
  92634. var constraint;
  92635. var jointData = impostorJoint.joint.jointData;
  92636. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  92637. var constraintData = {
  92638. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  92639. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  92640. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  92641. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  92642. maxForce: jointData.nativeParams.maxForce,
  92643. collideConnected: !!jointData.collision
  92644. };
  92645. switch (impostorJoint.joint.type) {
  92646. case BABYLON.PhysicsJoint.HingeJoint:
  92647. case BABYLON.PhysicsJoint.Hinge2Joint:
  92648. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  92649. break;
  92650. case BABYLON.PhysicsJoint.DistanceJoint:
  92651. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  92652. break;
  92653. case BABYLON.PhysicsJoint.SpringJoint:
  92654. var springData = jointData;
  92655. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  92656. restLength: springData.length,
  92657. stiffness: springData.stiffness,
  92658. damping: springData.damping,
  92659. localAnchorA: constraintData.pivotA,
  92660. localAnchorB: constraintData.pivotB
  92661. });
  92662. break;
  92663. case BABYLON.PhysicsJoint.LockJoint:
  92664. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  92665. break;
  92666. case BABYLON.PhysicsJoint.PointToPointJoint:
  92667. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  92668. default:
  92669. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  92670. break;
  92671. }
  92672. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  92673. constraint.collideConnected = !!jointData.collision;
  92674. impostorJoint.joint.physicsJoint = constraint;
  92675. //don't add spring as constraint, as it is not one.
  92676. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  92677. this.world.addConstraint(constraint);
  92678. }
  92679. else {
  92680. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  92681. constraint.applyForce();
  92682. };
  92683. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  92684. }
  92685. };
  92686. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  92687. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  92688. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  92689. }
  92690. else {
  92691. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  92692. }
  92693. };
  92694. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  92695. var index;
  92696. var mat;
  92697. for (index = 0; index < this._physicsMaterials.length; index++) {
  92698. mat = this._physicsMaterials[index];
  92699. if (mat.friction === friction && mat.restitution === restitution) {
  92700. return mat;
  92701. }
  92702. }
  92703. var currentMat = new this.BJSCANNON.Material(name);
  92704. currentMat.friction = friction;
  92705. currentMat.restitution = restitution;
  92706. this._physicsMaterials.push(currentMat);
  92707. return currentMat;
  92708. };
  92709. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  92710. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  92711. };
  92712. CannonJSPlugin.prototype._createShape = function (impostor) {
  92713. var object = impostor.object;
  92714. var returnValue;
  92715. var extendSize = impostor.getObjectExtendSize();
  92716. switch (impostor.type) {
  92717. case BABYLON.PhysicsImpostor.SphereImpostor:
  92718. var radiusX = extendSize.x;
  92719. var radiusY = extendSize.y;
  92720. var radiusZ = extendSize.z;
  92721. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  92722. break;
  92723. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  92724. case BABYLON.PhysicsImpostor.CylinderImpostor:
  92725. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  92726. break;
  92727. case BABYLON.PhysicsImpostor.BoxImpostor:
  92728. var box = extendSize.scale(0.5);
  92729. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  92730. break;
  92731. case BABYLON.PhysicsImpostor.PlaneImpostor:
  92732. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  92733. returnValue = new this.BJSCANNON.Plane();
  92734. break;
  92735. case BABYLON.PhysicsImpostor.MeshImpostor:
  92736. // should transform the vertex data to world coordinates!!
  92737. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  92738. var rawFaces = object.getIndices ? object.getIndices() : [];
  92739. if (!rawVerts)
  92740. return;
  92741. // get only scale! so the object could transform correctly.
  92742. var oldPosition = object.position.clone();
  92743. var oldRotation = object.rotation && object.rotation.clone();
  92744. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  92745. object.position.copyFromFloats(0, 0, 0);
  92746. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  92747. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  92748. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  92749. var transform = object.computeWorldMatrix(true);
  92750. // convert rawVerts to object space
  92751. var temp = new Array();
  92752. var index;
  92753. for (index = 0; index < rawVerts.length; index += 3) {
  92754. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  92755. }
  92756. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  92757. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  92758. //now set back the transformation!
  92759. object.position.copyFrom(oldPosition);
  92760. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  92761. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  92762. break;
  92763. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  92764. var oldPosition2 = object.position.clone();
  92765. var oldRotation2 = object.rotation && object.rotation.clone();
  92766. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  92767. object.position.copyFromFloats(0, 0, 0);
  92768. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  92769. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  92770. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  92771. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  92772. returnValue = this._createHeightmap(object);
  92773. object.position.copyFrom(oldPosition2);
  92774. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  92775. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  92776. object.computeWorldMatrix(true);
  92777. break;
  92778. case BABYLON.PhysicsImpostor.ParticleImpostor:
  92779. returnValue = new this.BJSCANNON.Particle();
  92780. break;
  92781. }
  92782. return returnValue;
  92783. };
  92784. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  92785. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  92786. var transform = object.computeWorldMatrix(true);
  92787. // convert rawVerts to object space
  92788. var temp = new Array();
  92789. var index;
  92790. for (index = 0; index < pos.length; index += 3) {
  92791. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  92792. }
  92793. pos = temp;
  92794. var matrix = new Array();
  92795. //For now pointDepth will not be used and will be automatically calculated.
  92796. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  92797. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  92798. var boundingInfo = object.getBoundingInfo();
  92799. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  92800. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  92801. var elementSize = dim * 2 / arraySize;
  92802. for (var i = 0; i < pos.length; i = i + 3) {
  92803. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  92804. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  92805. var y = -pos[i + 2] + minY;
  92806. if (!matrix[x]) {
  92807. matrix[x] = [];
  92808. }
  92809. if (!matrix[x][z]) {
  92810. matrix[x][z] = y;
  92811. }
  92812. matrix[x][z] = Math.max(y, matrix[x][z]);
  92813. }
  92814. for (var x = 0; x <= arraySize; ++x) {
  92815. if (!matrix[x]) {
  92816. var loc = 1;
  92817. while (!matrix[(x + loc) % arraySize]) {
  92818. loc++;
  92819. }
  92820. matrix[x] = matrix[(x + loc) % arraySize].slice();
  92821. //console.log("missing x", x);
  92822. }
  92823. for (var z = 0; z <= arraySize; ++z) {
  92824. if (!matrix[x][z]) {
  92825. var loc = 1;
  92826. var newValue;
  92827. while (newValue === undefined) {
  92828. newValue = matrix[x][(z + loc++) % arraySize];
  92829. }
  92830. matrix[x][z] = newValue;
  92831. }
  92832. }
  92833. }
  92834. var shape = new this.BJSCANNON.Heightfield(matrix, {
  92835. elementSize: elementSize
  92836. });
  92837. //For future reference, needed for body transformation
  92838. shape.minY = minY;
  92839. return shape;
  92840. };
  92841. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  92842. var object = impostor.object;
  92843. //make sure it is updated...
  92844. object.computeWorldMatrix && object.computeWorldMatrix(true);
  92845. // The delta between the mesh position and the mesh bounding box center
  92846. var bInfo = object.getBoundingInfo();
  92847. if (!bInfo)
  92848. return;
  92849. var center = impostor.getObjectCenter();
  92850. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  92851. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  92852. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  92853. this._tmpPosition.copyFrom(center);
  92854. var quaternion = object.rotationQuaternion;
  92855. if (!quaternion) {
  92856. return;
  92857. }
  92858. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  92859. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  92860. //-90 DEG in X, precalculated
  92861. quaternion = quaternion.multiply(this._minus90X);
  92862. //Invert! (Precalculated, 90 deg in X)
  92863. //No need to clone. this will never change.
  92864. impostor.setDeltaRotation(this._plus90X);
  92865. }
  92866. //If it is a heightfield, if should be centered.
  92867. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  92868. var mesh = object;
  92869. var boundingInfo = mesh.getBoundingInfo();
  92870. //calculate the correct body position:
  92871. var rotationQuaternion = mesh.rotationQuaternion;
  92872. mesh.rotationQuaternion = this._tmpUnityRotation;
  92873. mesh.computeWorldMatrix(true);
  92874. //get original center with no rotation
  92875. var c = center.clone();
  92876. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  92877. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  92878. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  92879. mesh.setPreTransformMatrix(p);
  92880. mesh.computeWorldMatrix(true);
  92881. //calculate the translation
  92882. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  92883. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  92884. //add it inverted to the delta
  92885. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  92886. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  92887. //rotation is back
  92888. mesh.rotationQuaternion = rotationQuaternion;
  92889. mesh.setPreTransformMatrix(oldPivot);
  92890. mesh.computeWorldMatrix(true);
  92891. }
  92892. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  92893. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  92894. //this._tmpPosition.copyFrom(object.position);
  92895. }
  92896. impostor.setDeltaPosition(this._tmpDeltaPosition);
  92897. //Now update the impostor object
  92898. impostor.physicsBody.position.copy(this._tmpPosition);
  92899. impostor.physicsBody.quaternion.copy(quaternion);
  92900. };
  92901. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  92902. impostor.object.position.copyFrom(impostor.physicsBody.position);
  92903. if (impostor.object.rotationQuaternion) {
  92904. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  92905. }
  92906. };
  92907. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  92908. impostor.physicsBody.position.copy(newPosition);
  92909. impostor.physicsBody.quaternion.copy(newRotation);
  92910. };
  92911. CannonJSPlugin.prototype.isSupported = function () {
  92912. return this.BJSCANNON !== undefined;
  92913. };
  92914. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  92915. impostor.physicsBody.velocity.copy(velocity);
  92916. };
  92917. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  92918. impostor.physicsBody.angularVelocity.copy(velocity);
  92919. };
  92920. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  92921. var v = impostor.physicsBody.velocity;
  92922. if (!v) {
  92923. return null;
  92924. }
  92925. return new BABYLON.Vector3(v.x, v.y, v.z);
  92926. };
  92927. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  92928. var v = impostor.physicsBody.angularVelocity;
  92929. if (!v) {
  92930. return null;
  92931. }
  92932. return new BABYLON.Vector3(v.x, v.y, v.z);
  92933. };
  92934. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  92935. impostor.physicsBody.mass = mass;
  92936. impostor.physicsBody.updateMassProperties();
  92937. };
  92938. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  92939. return impostor.physicsBody.mass;
  92940. };
  92941. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  92942. return impostor.physicsBody.material.friction;
  92943. };
  92944. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  92945. impostor.physicsBody.material.friction = friction;
  92946. };
  92947. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  92948. return impostor.physicsBody.material.restitution;
  92949. };
  92950. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  92951. impostor.physicsBody.material.restitution = restitution;
  92952. };
  92953. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  92954. impostor.physicsBody.sleep();
  92955. };
  92956. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  92957. impostor.physicsBody.wakeUp();
  92958. };
  92959. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  92960. joint.physicsJoint.distance = maxDistance;
  92961. };
  92962. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  92963. // if (!motorIndex) {
  92964. // joint.physicsJoint.enableMotor();
  92965. // }
  92966. // }
  92967. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  92968. // if (!motorIndex) {
  92969. // joint.physicsJoint.disableMotor();
  92970. // }
  92971. // }
  92972. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  92973. if (!motorIndex) {
  92974. joint.physicsJoint.enableMotor();
  92975. joint.physicsJoint.setMotorSpeed(speed);
  92976. if (maxForce) {
  92977. this.setLimit(joint, maxForce);
  92978. }
  92979. }
  92980. };
  92981. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  92982. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  92983. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  92984. };
  92985. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  92986. var body = impostor.physicsBody;
  92987. mesh.position.x = body.position.x;
  92988. mesh.position.y = body.position.y;
  92989. mesh.position.z = body.position.z;
  92990. if (mesh.rotationQuaternion) {
  92991. mesh.rotationQuaternion.x = body.quaternion.x;
  92992. mesh.rotationQuaternion.y = body.quaternion.y;
  92993. mesh.rotationQuaternion.z = body.quaternion.z;
  92994. mesh.rotationQuaternion.w = body.quaternion.w;
  92995. }
  92996. };
  92997. CannonJSPlugin.prototype.getRadius = function (impostor) {
  92998. var shape = impostor.physicsBody.shapes[0];
  92999. return shape.boundingSphereRadius;
  93000. };
  93001. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  93002. var shape = impostor.physicsBody.shapes[0];
  93003. result.x = shape.halfExtents.x * 2;
  93004. result.y = shape.halfExtents.y * 2;
  93005. result.z = shape.halfExtents.z * 2;
  93006. };
  93007. CannonJSPlugin.prototype.dispose = function () {
  93008. };
  93009. CannonJSPlugin.prototype._extendNamespace = function () {
  93010. //this will force cannon to execute at least one step when using interpolation
  93011. var step_tmp1 = new this.BJSCANNON.Vec3();
  93012. var Engine = this.BJSCANNON;
  93013. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  93014. maxSubSteps = maxSubSteps || 10;
  93015. timeSinceLastCalled = timeSinceLastCalled || 0;
  93016. if (timeSinceLastCalled === 0) {
  93017. this.internalStep(dt);
  93018. this.time += dt;
  93019. }
  93020. else {
  93021. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  93022. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  93023. var t0 = performance.now();
  93024. for (var i = 0; i !== internalSteps; i++) {
  93025. this.internalStep(dt);
  93026. if (performance.now() - t0 > dt * 1000) {
  93027. break;
  93028. }
  93029. }
  93030. this.time += timeSinceLastCalled;
  93031. var h = this.time % dt;
  93032. var h_div_dt = h / dt;
  93033. var interpvelo = step_tmp1;
  93034. var bodies = this.bodies;
  93035. for (var j = 0; j !== bodies.length; j++) {
  93036. var b = bodies[j];
  93037. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  93038. b.position.vsub(b.previousPosition, interpvelo);
  93039. interpvelo.scale(h_div_dt, interpvelo);
  93040. b.position.vadd(interpvelo, b.interpolatedPosition);
  93041. }
  93042. else {
  93043. b.interpolatedPosition.copy(b.position);
  93044. b.interpolatedQuaternion.copy(b.quaternion);
  93045. }
  93046. }
  93047. }
  93048. };
  93049. };
  93050. return CannonJSPlugin;
  93051. }());
  93052. BABYLON.CannonJSPlugin = CannonJSPlugin;
  93053. })(BABYLON || (BABYLON = {}));
  93054. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  93055. var BABYLON;
  93056. (function (BABYLON) {
  93057. /** @hidden */
  93058. var OimoJSPlugin = /** @class */ (function () {
  93059. function OimoJSPlugin(iterations) {
  93060. this.name = "OimoJSPlugin";
  93061. this._tmpImpostorsArray = [];
  93062. this._tmpPositionVector = BABYLON.Vector3.Zero();
  93063. this.BJSOIMO = OIMO;
  93064. this.world = new this.BJSOIMO.World({
  93065. iterations: iterations
  93066. });
  93067. this.world.clear();
  93068. }
  93069. OimoJSPlugin.prototype.setGravity = function (gravity) {
  93070. this.world.gravity.copy(gravity);
  93071. };
  93072. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  93073. this.world.timeStep = timeStep;
  93074. };
  93075. OimoJSPlugin.prototype.getTimeStep = function () {
  93076. return this.world.timeStep;
  93077. };
  93078. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  93079. var _this = this;
  93080. impostors.forEach(function (impostor) {
  93081. impostor.beforeStep();
  93082. });
  93083. this.world.step();
  93084. impostors.forEach(function (impostor) {
  93085. impostor.afterStep();
  93086. //update the ordered impostors array
  93087. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  93088. });
  93089. //check for collisions
  93090. var contact = this.world.contacts;
  93091. while (contact !== null) {
  93092. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  93093. contact = contact.next;
  93094. continue;
  93095. }
  93096. //is this body colliding with any other? get the impostor
  93097. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  93098. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  93099. if (!mainImpostor || !collidingImpostor) {
  93100. contact = contact.next;
  93101. continue;
  93102. }
  93103. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  93104. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  93105. contact = contact.next;
  93106. }
  93107. };
  93108. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  93109. var mass = impostor.physicsBody.mass;
  93110. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  93111. };
  93112. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  93113. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  93114. this.applyImpulse(impostor, force, contactPoint);
  93115. };
  93116. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  93117. var _this = this;
  93118. //parent-child relationship. Does this impostor has a parent impostor?
  93119. if (impostor.parent) {
  93120. if (impostor.physicsBody) {
  93121. this.removePhysicsBody(impostor);
  93122. //TODO is that needed?
  93123. impostor.forceUpdate();
  93124. }
  93125. return;
  93126. }
  93127. if (impostor.isBodyInitRequired()) {
  93128. var bodyConfig = {
  93129. name: impostor.uniqueId,
  93130. //Oimo must have mass, also for static objects.
  93131. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  93132. size: [],
  93133. type: [],
  93134. pos: [],
  93135. posShape: [],
  93136. rot: [],
  93137. rotShape: [],
  93138. move: impostor.getParam("mass") !== 0,
  93139. density: impostor.getParam("mass"),
  93140. friction: impostor.getParam("friction"),
  93141. restitution: impostor.getParam("restitution"),
  93142. //Supporting older versions of Oimo
  93143. world: this.world
  93144. };
  93145. var impostors = [impostor];
  93146. var addToArray = function (parent) {
  93147. if (!parent.getChildMeshes)
  93148. return;
  93149. parent.getChildMeshes().forEach(function (m) {
  93150. if (m.physicsImpostor) {
  93151. impostors.push(m.physicsImpostor);
  93152. //m.physicsImpostor._init();
  93153. }
  93154. });
  93155. };
  93156. addToArray(impostor.object);
  93157. var checkWithEpsilon_1 = function (value) {
  93158. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  93159. };
  93160. var globalQuaternion_1 = new BABYLON.Quaternion();
  93161. impostors.forEach(function (i) {
  93162. if (!i.object.rotationQuaternion) {
  93163. return;
  93164. }
  93165. //get the correct bounding box
  93166. var oldQuaternion = i.object.rotationQuaternion;
  93167. globalQuaternion_1 = oldQuaternion.clone();
  93168. var rot = oldQuaternion.toEulerAngles();
  93169. var extendSize = i.getObjectExtendSize();
  93170. var radToDeg = 57.295779513082320876;
  93171. if (i === impostor) {
  93172. var center = impostor.getObjectCenter();
  93173. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  93174. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  93175. //Can also use Array.prototype.push.apply
  93176. bodyConfig.pos.push(center.x);
  93177. bodyConfig.pos.push(center.y);
  93178. bodyConfig.pos.push(center.z);
  93179. bodyConfig.posShape.push(0, 0, 0);
  93180. //tmp solution
  93181. bodyConfig.rot.push(0);
  93182. bodyConfig.rot.push(0);
  93183. bodyConfig.rot.push(0);
  93184. bodyConfig.rotShape.push(0, 0, 0);
  93185. }
  93186. else {
  93187. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  93188. bodyConfig.posShape.push(localPosition.x);
  93189. bodyConfig.posShape.push(localPosition.y);
  93190. bodyConfig.posShape.push(localPosition.z);
  93191. bodyConfig.pos.push(0, 0, 0);
  93192. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  93193. bodyConfig.rot.push(0);
  93194. bodyConfig.rot.push(0);
  93195. bodyConfig.rot.push(0);
  93196. bodyConfig.rotShape.push(rot.x * radToDeg);
  93197. bodyConfig.rotShape.push(rot.y * radToDeg);
  93198. bodyConfig.rotShape.push(rot.z * radToDeg);
  93199. }
  93200. // register mesh
  93201. switch (i.type) {
  93202. case BABYLON.PhysicsImpostor.ParticleImpostor:
  93203. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  93204. case BABYLON.PhysicsImpostor.SphereImpostor:
  93205. var radiusX = extendSize.x;
  93206. var radiusY = extendSize.y;
  93207. var radiusZ = extendSize.z;
  93208. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  93209. bodyConfig.type.push('sphere');
  93210. //due to the way oimo works with compounds, add 3 times
  93211. bodyConfig.size.push(size);
  93212. bodyConfig.size.push(size);
  93213. bodyConfig.size.push(size);
  93214. break;
  93215. case BABYLON.PhysicsImpostor.CylinderImpostor:
  93216. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  93217. var sizeY = checkWithEpsilon_1(extendSize.y);
  93218. bodyConfig.type.push('cylinder');
  93219. bodyConfig.size.push(sizeX);
  93220. bodyConfig.size.push(sizeY);
  93221. //due to the way oimo works with compounds, add one more value.
  93222. bodyConfig.size.push(sizeY);
  93223. break;
  93224. case BABYLON.PhysicsImpostor.PlaneImpostor:
  93225. case BABYLON.PhysicsImpostor.BoxImpostor:
  93226. default:
  93227. var sizeX = checkWithEpsilon_1(extendSize.x);
  93228. var sizeY = checkWithEpsilon_1(extendSize.y);
  93229. var sizeZ = checkWithEpsilon_1(extendSize.z);
  93230. bodyConfig.type.push('box');
  93231. //if (i === impostor) {
  93232. bodyConfig.size.push(sizeX);
  93233. bodyConfig.size.push(sizeY);
  93234. bodyConfig.size.push(sizeZ);
  93235. //} else {
  93236. // bodyConfig.size.push(0,0,0);
  93237. //}
  93238. break;
  93239. }
  93240. //actually not needed, but hey...
  93241. i.object.rotationQuaternion = oldQuaternion;
  93242. });
  93243. impostor.physicsBody = this.world.add(bodyConfig);
  93244. // set the quaternion, ignoring the previously defined (euler) rotation
  93245. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  93246. // update with delta 0, so the body will reveive the new rotation.
  93247. impostor.physicsBody.updatePosition(0);
  93248. }
  93249. else {
  93250. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  93251. }
  93252. impostor.setDeltaPosition(this._tmpPositionVector);
  93253. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  93254. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  93255. };
  93256. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  93257. //impostor.physicsBody.dispose();
  93258. //Same as : (older oimo versions)
  93259. this.world.removeRigidBody(impostor.physicsBody);
  93260. };
  93261. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  93262. var mainBody = impostorJoint.mainImpostor.physicsBody;
  93263. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  93264. if (!mainBody || !connectedBody) {
  93265. return;
  93266. }
  93267. var jointData = impostorJoint.joint.jointData;
  93268. var options = jointData.nativeParams || {};
  93269. var type;
  93270. var nativeJointData = {
  93271. body1: mainBody,
  93272. body2: connectedBody,
  93273. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  93274. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  93275. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  93276. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  93277. min: options.min,
  93278. max: options.max,
  93279. collision: options.collision || jointData.collision,
  93280. spring: options.spring,
  93281. //supporting older version of Oimo
  93282. world: this.world
  93283. };
  93284. switch (impostorJoint.joint.type) {
  93285. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  93286. type = "jointBall";
  93287. break;
  93288. case BABYLON.PhysicsJoint.SpringJoint:
  93289. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  93290. var springData = jointData;
  93291. nativeJointData.min = springData.length || nativeJointData.min;
  93292. //Max should also be set, just make sure it is at least min
  93293. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  93294. case BABYLON.PhysicsJoint.DistanceJoint:
  93295. type = "jointDistance";
  93296. nativeJointData.max = jointData.maxDistance;
  93297. break;
  93298. case BABYLON.PhysicsJoint.PrismaticJoint:
  93299. type = "jointPrisme";
  93300. break;
  93301. case BABYLON.PhysicsJoint.SliderJoint:
  93302. type = "jointSlide";
  93303. break;
  93304. case BABYLON.PhysicsJoint.WheelJoint:
  93305. type = "jointWheel";
  93306. break;
  93307. case BABYLON.PhysicsJoint.HingeJoint:
  93308. default:
  93309. type = "jointHinge";
  93310. break;
  93311. }
  93312. nativeJointData.type = type;
  93313. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  93314. };
  93315. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  93316. //Bug in Oimo prevents us from disposing a joint in the playground
  93317. //joint.joint.physicsJoint.dispose();
  93318. //So we will bruteforce it!
  93319. try {
  93320. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  93321. }
  93322. catch (e) {
  93323. BABYLON.Tools.Warn(e);
  93324. }
  93325. };
  93326. OimoJSPlugin.prototype.isSupported = function () {
  93327. return this.BJSOIMO !== undefined;
  93328. };
  93329. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  93330. if (!impostor.physicsBody.sleeping) {
  93331. //TODO check that
  93332. /*if (impostor.physicsBody.shapes.next) {
  93333. var parentShape = this._getLastShape(impostor.physicsBody);
  93334. impostor.object.position.copyFrom(parentShape.position);
  93335. console.log(parentShape.position);
  93336. } else {*/
  93337. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  93338. //}
  93339. if (impostor.object.rotationQuaternion) {
  93340. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  93341. }
  93342. }
  93343. };
  93344. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  93345. var body = impostor.physicsBody;
  93346. body.position.copy(newPosition);
  93347. body.orientation.copy(newRotation);
  93348. body.syncShapes();
  93349. body.awake();
  93350. };
  93351. /*private _getLastShape(body: any): any {
  93352. var lastShape = body.shapes;
  93353. while (lastShape.next) {
  93354. lastShape = lastShape.next;
  93355. }
  93356. return lastShape;
  93357. }*/
  93358. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  93359. impostor.physicsBody.linearVelocity.copy(velocity);
  93360. };
  93361. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  93362. impostor.physicsBody.angularVelocity.copy(velocity);
  93363. };
  93364. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  93365. var v = impostor.physicsBody.linearVelocity;
  93366. if (!v) {
  93367. return null;
  93368. }
  93369. return new BABYLON.Vector3(v.x, v.y, v.z);
  93370. };
  93371. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  93372. var v = impostor.physicsBody.angularVelocity;
  93373. if (!v) {
  93374. return null;
  93375. }
  93376. return new BABYLON.Vector3(v.x, v.y, v.z);
  93377. };
  93378. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  93379. var staticBody = mass === 0;
  93380. //this will actually set the body's density and not its mass.
  93381. //But this is how oimo treats the mass variable.
  93382. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  93383. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  93384. };
  93385. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  93386. return impostor.physicsBody.shapes.density;
  93387. };
  93388. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  93389. return impostor.physicsBody.shapes.friction;
  93390. };
  93391. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  93392. impostor.physicsBody.shapes.friction = friction;
  93393. };
  93394. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  93395. return impostor.physicsBody.shapes.restitution;
  93396. };
  93397. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  93398. impostor.physicsBody.shapes.restitution = restitution;
  93399. };
  93400. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  93401. impostor.physicsBody.sleep();
  93402. };
  93403. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  93404. impostor.physicsBody.awake();
  93405. };
  93406. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  93407. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  93408. if (minDistance !== void 0) {
  93409. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  93410. }
  93411. };
  93412. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  93413. //TODO separate rotational and transational motors.
  93414. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  93415. if (motor) {
  93416. motor.setMotor(speed, maxForce);
  93417. }
  93418. };
  93419. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  93420. //TODO separate rotational and transational motors.
  93421. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  93422. if (motor) {
  93423. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  93424. }
  93425. };
  93426. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  93427. var body = impostor.physicsBody;
  93428. mesh.position.x = body.position.x;
  93429. mesh.position.y = body.position.y;
  93430. mesh.position.z = body.position.z;
  93431. if (mesh.rotationQuaternion) {
  93432. mesh.rotationQuaternion.x = body.orientation.x;
  93433. mesh.rotationQuaternion.y = body.orientation.y;
  93434. mesh.rotationQuaternion.z = body.orientation.z;
  93435. mesh.rotationQuaternion.w = body.orientation.s;
  93436. }
  93437. };
  93438. OimoJSPlugin.prototype.getRadius = function (impostor) {
  93439. return impostor.physicsBody.shapes.radius;
  93440. };
  93441. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  93442. var shape = impostor.physicsBody.shapes;
  93443. result.x = shape.halfWidth * 2;
  93444. result.y = shape.halfHeight * 2;
  93445. result.z = shape.halfDepth * 2;
  93446. };
  93447. OimoJSPlugin.prototype.dispose = function () {
  93448. this.world.clear();
  93449. };
  93450. return OimoJSPlugin;
  93451. }());
  93452. BABYLON.OimoJSPlugin = OimoJSPlugin;
  93453. })(BABYLON || (BABYLON = {}));
  93454. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  93455. var BABYLON;
  93456. (function (BABYLON) {
  93457. /**
  93458. * Gets the current physics engine
  93459. * @returns a IPhysicsEngine or null if none attached
  93460. */
  93461. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  93462. return this._physicsEngine;
  93463. };
  93464. /**
  93465. * Enables physics to the current scene
  93466. * @param gravity defines the scene's gravity for the physics engine
  93467. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  93468. * @return a boolean indicating if the physics engine was initialized
  93469. */
  93470. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  93471. if (gravity === void 0) { gravity = null; }
  93472. if (this._physicsEngine) {
  93473. return true;
  93474. }
  93475. // Register the component to the scene
  93476. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  93477. if (!component) {
  93478. component = new PhysicsEngineSceneComponent(this);
  93479. this._addComponent(component);
  93480. }
  93481. try {
  93482. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  93483. return true;
  93484. }
  93485. catch (e) {
  93486. BABYLON.Tools.Error(e.message);
  93487. return false;
  93488. }
  93489. };
  93490. /**
  93491. * Disables and disposes the physics engine associated with the scene
  93492. */
  93493. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  93494. if (!this._physicsEngine) {
  93495. return;
  93496. }
  93497. this._physicsEngine.dispose();
  93498. this._physicsEngine = null;
  93499. };
  93500. /**
  93501. * Gets a boolean indicating if there is an active physics engine
  93502. * @returns a boolean indicating if there is an active physics engine
  93503. */
  93504. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  93505. return this._physicsEngine !== undefined;
  93506. };
  93507. /**
  93508. * Deletes a physics compound impostor
  93509. * @param compound defines the compound to delete
  93510. */
  93511. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  93512. var mesh = compound.parts[0].mesh;
  93513. if (mesh.physicsImpostor) {
  93514. mesh.physicsImpostor.dispose( /*true*/);
  93515. mesh.physicsImpostor = null;
  93516. }
  93517. };
  93518. /** @hidden */
  93519. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  93520. if (this._physicsEngine) {
  93521. this.onBeforePhysicsObservable.notifyObservers(this);
  93522. this._physicsEngine._step(step / 1000);
  93523. this.onAfterPhysicsObservable.notifyObservers(this);
  93524. }
  93525. };
  93526. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  93527. get: function () {
  93528. return this._physicsImpostor;
  93529. },
  93530. set: function (value) {
  93531. var _this = this;
  93532. if (this._physicsImpostor === value) {
  93533. return;
  93534. }
  93535. if (this._disposePhysicsObserver) {
  93536. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  93537. }
  93538. this._physicsImpostor = value;
  93539. if (value) {
  93540. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  93541. // Physics
  93542. if (_this.physicsImpostor) {
  93543. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  93544. _this.physicsImpostor = null;
  93545. }
  93546. });
  93547. }
  93548. },
  93549. enumerable: true,
  93550. configurable: true
  93551. });
  93552. /**
  93553. * Gets the current physics impostor
  93554. * @see http://doc.babylonjs.com/features/physics_engine
  93555. * @returns a physics impostor or null
  93556. */
  93557. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  93558. return this.physicsImpostor;
  93559. };
  93560. /**
  93561. * Apply a physic impulse to the mesh
  93562. * @param force defines the force to apply
  93563. * @param contactPoint defines where to apply the force
  93564. * @returns the current mesh
  93565. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  93566. */
  93567. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  93568. if (!this.physicsImpostor) {
  93569. return this;
  93570. }
  93571. this.physicsImpostor.applyImpulse(force, contactPoint);
  93572. return this;
  93573. };
  93574. /**
  93575. * Creates a physic joint between two meshes
  93576. * @param otherMesh defines the other mesh to use
  93577. * @param pivot1 defines the pivot to use on this mesh
  93578. * @param pivot2 defines the pivot to use on the other mesh
  93579. * @param options defines additional options (can be plugin dependent)
  93580. * @returns the current mesh
  93581. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  93582. */
  93583. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  93584. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  93585. return this;
  93586. }
  93587. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  93588. mainPivot: pivot1,
  93589. connectedPivot: pivot2,
  93590. nativeParams: options
  93591. });
  93592. return this;
  93593. };
  93594. /**
  93595. * Defines the physics engine scene component responsible to manage a physics engine
  93596. */
  93597. var PhysicsEngineSceneComponent = /** @class */ (function () {
  93598. /**
  93599. * Creates a new instance of the component for the given scene
  93600. * @param scene Defines the scene to register the component in
  93601. */
  93602. function PhysicsEngineSceneComponent(scene) {
  93603. var _this = this;
  93604. /**
  93605. * The component name helpful to identify the component in the list of scene components.
  93606. */
  93607. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  93608. this.scene = scene;
  93609. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  93610. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  93611. // Replace the function used to get the deterministic frame time
  93612. this.scene.getDeterministicFrameTime = function () {
  93613. if (_this.scene._physicsEngine) {
  93614. return _this.scene._physicsEngine.getTimeStep() * 1000;
  93615. }
  93616. return 1000.0 / 60.0;
  93617. };
  93618. }
  93619. /**
  93620. * Registers the component in a given scene
  93621. */
  93622. PhysicsEngineSceneComponent.prototype.register = function () {
  93623. };
  93624. /**
  93625. * Rebuilds the elements related to this component in case of
  93626. * context lost for instance.
  93627. */
  93628. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  93629. // Nothing to do for this component
  93630. };
  93631. /**
  93632. * Disposes the component and the associated ressources
  93633. */
  93634. PhysicsEngineSceneComponent.prototype.dispose = function () {
  93635. this.scene.onBeforePhysicsObservable.clear();
  93636. this.scene.onAfterPhysicsObservable.clear();
  93637. if (this.scene._physicsEngine) {
  93638. this.scene.disablePhysicsEngine();
  93639. }
  93640. };
  93641. return PhysicsEngineSceneComponent;
  93642. }());
  93643. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  93644. })(BABYLON || (BABYLON = {}));
  93645. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  93646. var BABYLON;
  93647. (function (BABYLON) {
  93648. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  93649. // All values and structures referenced from:
  93650. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  93651. var DDS_MAGIC = 0x20534444;
  93652. var
  93653. //DDSD_CAPS = 0x1,
  93654. //DDSD_HEIGHT = 0x2,
  93655. //DDSD_WIDTH = 0x4,
  93656. //DDSD_PITCH = 0x8,
  93657. //DDSD_PIXELFORMAT = 0x1000,
  93658. DDSD_MIPMAPCOUNT = 0x20000;
  93659. //DDSD_LINEARSIZE = 0x80000,
  93660. //DDSD_DEPTH = 0x800000;
  93661. // var DDSCAPS_COMPLEX = 0x8,
  93662. // DDSCAPS_MIPMAP = 0x400000,
  93663. // DDSCAPS_TEXTURE = 0x1000;
  93664. var DDSCAPS2_CUBEMAP = 0x200;
  93665. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  93666. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  93667. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  93668. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  93669. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  93670. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  93671. // DDSCAPS2_VOLUME = 0x200000;
  93672. var
  93673. //DDPF_ALPHAPIXELS = 0x1,
  93674. //DDPF_ALPHA = 0x2,
  93675. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  93676. //DDPF_YUV = 0x200,
  93677. DDPF_LUMINANCE = 0x20000;
  93678. function FourCCToInt32(value) {
  93679. return value.charCodeAt(0) +
  93680. (value.charCodeAt(1) << 8) +
  93681. (value.charCodeAt(2) << 16) +
  93682. (value.charCodeAt(3) << 24);
  93683. }
  93684. function Int32ToFourCC(value) {
  93685. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  93686. }
  93687. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  93688. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  93689. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  93690. var FOURCC_DX10 = FourCCToInt32("DX10");
  93691. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  93692. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  93693. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  93694. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  93695. var headerLengthInt = 31; // The header length in 32 bit ints
  93696. // Offsets into the header array
  93697. var off_magic = 0;
  93698. var off_size = 1;
  93699. var off_flags = 2;
  93700. var off_height = 3;
  93701. var off_width = 4;
  93702. var off_mipmapCount = 7;
  93703. var off_pfFlags = 20;
  93704. var off_pfFourCC = 21;
  93705. var off_RGBbpp = 22;
  93706. var off_RMask = 23;
  93707. var off_GMask = 24;
  93708. var off_BMask = 25;
  93709. var off_AMask = 26;
  93710. // var off_caps1 = 27;
  93711. var off_caps2 = 28;
  93712. // var off_caps3 = 29;
  93713. // var off_caps4 = 30;
  93714. var off_dxgiFormat = 32;
  93715. ;
  93716. var DDSTools = /** @class */ (function () {
  93717. function DDSTools() {
  93718. }
  93719. DDSTools.GetDDSInfo = function (arrayBuffer) {
  93720. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  93721. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  93722. var mipmapCount = 1;
  93723. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  93724. mipmapCount = Math.max(1, header[off_mipmapCount]);
  93725. }
  93726. var fourCC = header[off_pfFourCC];
  93727. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  93728. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93729. switch (fourCC) {
  93730. case FOURCC_D3DFMT_R16G16B16A16F:
  93731. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93732. break;
  93733. case FOURCC_D3DFMT_R32G32B32A32F:
  93734. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93735. break;
  93736. case FOURCC_DX10:
  93737. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  93738. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93739. break;
  93740. }
  93741. }
  93742. return {
  93743. width: header[off_width],
  93744. height: header[off_height],
  93745. mipmapCount: mipmapCount,
  93746. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  93747. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  93748. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  93749. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  93750. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  93751. dxgiFormat: dxgiFormat,
  93752. textureType: textureType
  93753. };
  93754. };
  93755. DDSTools._ToHalfFloat = function (value) {
  93756. if (!DDSTools._FloatView) {
  93757. DDSTools._FloatView = new Float32Array(1);
  93758. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  93759. }
  93760. DDSTools._FloatView[0] = value;
  93761. var x = DDSTools._Int32View[0];
  93762. var bits = (x >> 16) & 0x8000; /* Get the sign */
  93763. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  93764. var e = (x >> 23) & 0xff; /* Using int is faster here */
  93765. /* If zero, or denormal, or exponent underflows too much for a denormal
  93766. * half, return signed zero. */
  93767. if (e < 103) {
  93768. return bits;
  93769. }
  93770. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  93771. if (e > 142) {
  93772. bits |= 0x7c00;
  93773. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  93774. * not Inf, so make sure we set one mantissa bit too. */
  93775. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  93776. return bits;
  93777. }
  93778. /* If exponent underflows but not too much, return a denormal */
  93779. if (e < 113) {
  93780. m |= 0x0800;
  93781. /* Extra rounding may overflow and set mantissa to 0 and exponent
  93782. * to 1, which is OK. */
  93783. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  93784. return bits;
  93785. }
  93786. bits |= ((e - 112) << 10) | (m >> 1);
  93787. bits += m & 1;
  93788. return bits;
  93789. };
  93790. DDSTools._FromHalfFloat = function (value) {
  93791. var s = (value & 0x8000) >> 15;
  93792. var e = (value & 0x7C00) >> 10;
  93793. var f = value & 0x03FF;
  93794. if (e === 0) {
  93795. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  93796. }
  93797. else if (e == 0x1F) {
  93798. return f ? NaN : ((s ? -1 : 1) * Infinity);
  93799. }
  93800. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  93801. };
  93802. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93803. var destArray = new Float32Array(dataLength);
  93804. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93805. var index = 0;
  93806. for (var y = 0; y < height; y++) {
  93807. for (var x = 0; x < width; x++) {
  93808. var srcPos = (x + y * width) * 4;
  93809. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  93810. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  93811. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  93812. if (DDSTools.StoreLODInAlphaChannel) {
  93813. destArray[index + 3] = lod;
  93814. }
  93815. else {
  93816. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  93817. }
  93818. index += 4;
  93819. }
  93820. }
  93821. return destArray;
  93822. };
  93823. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93824. if (DDSTools.StoreLODInAlphaChannel) {
  93825. var destArray = new Uint16Array(dataLength);
  93826. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93827. var index = 0;
  93828. for (var y = 0; y < height; y++) {
  93829. for (var x = 0; x < width; x++) {
  93830. var srcPos = (x + y * width) * 4;
  93831. destArray[index] = srcData[srcPos];
  93832. destArray[index + 1] = srcData[srcPos + 1];
  93833. destArray[index + 2] = srcData[srcPos + 2];
  93834. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  93835. index += 4;
  93836. }
  93837. }
  93838. return destArray;
  93839. }
  93840. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  93841. };
  93842. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93843. if (DDSTools.StoreLODInAlphaChannel) {
  93844. var destArray = new Float32Array(dataLength);
  93845. var srcData = new Float32Array(arrayBuffer, dataOffset);
  93846. var index = 0;
  93847. for (var y = 0; y < height; y++) {
  93848. for (var x = 0; x < width; x++) {
  93849. var srcPos = (x + y * width) * 4;
  93850. destArray[index] = srcData[srcPos];
  93851. destArray[index + 1] = srcData[srcPos + 1];
  93852. destArray[index + 2] = srcData[srcPos + 2];
  93853. destArray[index + 3] = lod;
  93854. index += 4;
  93855. }
  93856. }
  93857. return destArray;
  93858. }
  93859. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  93860. };
  93861. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93862. var destArray = new Uint8Array(dataLength);
  93863. var srcData = new Float32Array(arrayBuffer, dataOffset);
  93864. var index = 0;
  93865. for (var y = 0; y < height; y++) {
  93866. for (var x = 0; x < width; x++) {
  93867. var srcPos = (x + y * width) * 4;
  93868. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  93869. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  93870. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  93871. if (DDSTools.StoreLODInAlphaChannel) {
  93872. destArray[index + 3] = lod;
  93873. }
  93874. else {
  93875. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  93876. }
  93877. index += 4;
  93878. }
  93879. }
  93880. return destArray;
  93881. };
  93882. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93883. var destArray = new Uint8Array(dataLength);
  93884. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93885. var index = 0;
  93886. for (var y = 0; y < height; y++) {
  93887. for (var x = 0; x < width; x++) {
  93888. var srcPos = (x + y * width) * 4;
  93889. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  93890. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  93891. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  93892. if (DDSTools.StoreLODInAlphaChannel) {
  93893. destArray[index + 3] = lod;
  93894. }
  93895. else {
  93896. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  93897. }
  93898. index += 4;
  93899. }
  93900. }
  93901. return destArray;
  93902. };
  93903. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  93904. var byteArray = new Uint8Array(dataLength);
  93905. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93906. var index = 0;
  93907. for (var y = 0; y < height; y++) {
  93908. for (var x = 0; x < width; x++) {
  93909. var srcPos = (x + y * width) * 4;
  93910. byteArray[index] = srcData[srcPos + rOffset];
  93911. byteArray[index + 1] = srcData[srcPos + gOffset];
  93912. byteArray[index + 2] = srcData[srcPos + bOffset];
  93913. byteArray[index + 3] = srcData[srcPos + aOffset];
  93914. index += 4;
  93915. }
  93916. }
  93917. return byteArray;
  93918. };
  93919. DDSTools._ExtractLongWordOrder = function (value) {
  93920. if (value === 0 || value === 255 || value === -16777216) {
  93921. return 0;
  93922. }
  93923. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  93924. };
  93925. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  93926. var byteArray = new Uint8Array(dataLength);
  93927. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93928. var index = 0;
  93929. for (var y = 0; y < height; y++) {
  93930. for (var x = 0; x < width; x++) {
  93931. var srcPos = (x + y * width) * 3;
  93932. byteArray[index] = srcData[srcPos + rOffset];
  93933. byteArray[index + 1] = srcData[srcPos + gOffset];
  93934. byteArray[index + 2] = srcData[srcPos + bOffset];
  93935. index += 3;
  93936. }
  93937. }
  93938. return byteArray;
  93939. };
  93940. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  93941. var byteArray = new Uint8Array(dataLength);
  93942. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93943. var index = 0;
  93944. for (var y = 0; y < height; y++) {
  93945. for (var x = 0; x < width; x++) {
  93946. var srcPos = (x + y * width);
  93947. byteArray[index] = srcData[srcPos];
  93948. index++;
  93949. }
  93950. }
  93951. return byteArray;
  93952. };
  93953. /**
  93954. * Uploads DDS Levels to a Babylon Texture
  93955. * @hidden
  93956. */
  93957. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  93958. if (lodIndex === void 0) { lodIndex = -1; }
  93959. var sphericalPolynomialFaces = null;
  93960. if (info.sphericalPolynomial) {
  93961. sphericalPolynomialFaces = new Array();
  93962. }
  93963. var ext = engine.getCaps().s3tc;
  93964. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  93965. var fourCC, width, height, dataLength = 0, dataOffset;
  93966. var byteArray, mipmapCount, mip;
  93967. var internalCompressedFormat = 0;
  93968. var blockBytes = 1;
  93969. if (header[off_magic] !== DDS_MAGIC) {
  93970. BABYLON.Tools.Error("Invalid magic number in DDS header");
  93971. return;
  93972. }
  93973. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  93974. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  93975. return;
  93976. }
  93977. if (info.isCompressed && !ext) {
  93978. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  93979. return;
  93980. }
  93981. var bpp = header[off_RGBbpp];
  93982. dataOffset = header[off_size] + 4;
  93983. var computeFormats = false;
  93984. if (info.isFourCC) {
  93985. fourCC = header[off_pfFourCC];
  93986. switch (fourCC) {
  93987. case FOURCC_DXT1:
  93988. blockBytes = 8;
  93989. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  93990. break;
  93991. case FOURCC_DXT3:
  93992. blockBytes = 16;
  93993. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  93994. break;
  93995. case FOURCC_DXT5:
  93996. blockBytes = 16;
  93997. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  93998. break;
  93999. case FOURCC_D3DFMT_R16G16B16A16F:
  94000. computeFormats = true;
  94001. break;
  94002. case FOURCC_D3DFMT_R32G32B32A32F:
  94003. computeFormats = true;
  94004. break;
  94005. case FOURCC_DX10:
  94006. // There is an additionnal header so dataOffset need to be changed
  94007. dataOffset += 5 * 4; // 5 uints
  94008. var supported = false;
  94009. switch (info.dxgiFormat) {
  94010. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  94011. computeFormats = true;
  94012. supported = true;
  94013. break;
  94014. case DXGI_FORMAT_B8G8R8X8_UNORM:
  94015. info.isRGB = true;
  94016. info.isFourCC = false;
  94017. bpp = 32;
  94018. supported = true;
  94019. break;
  94020. }
  94021. if (supported) {
  94022. break;
  94023. }
  94024. default:
  94025. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  94026. return;
  94027. }
  94028. }
  94029. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  94030. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  94031. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  94032. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  94033. if (computeFormats) {
  94034. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  94035. }
  94036. mipmapCount = 1;
  94037. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  94038. mipmapCount = Math.max(1, header[off_mipmapCount]);
  94039. }
  94040. for (var face = 0; face < faces; face++) {
  94041. width = header[off_width];
  94042. height = header[off_height];
  94043. for (mip = 0; mip < mipmapCount; ++mip) {
  94044. if (lodIndex === -1 || lodIndex === mip) {
  94045. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  94046. var i = (lodIndex === -1) ? mip : 0;
  94047. if (!info.isCompressed && info.isFourCC) {
  94048. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94049. dataLength = width * height * 4;
  94050. var floatArray = null;
  94051. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  94052. if (bpp === 128) {
  94053. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94054. if (sphericalPolynomialFaces && i == 0) {
  94055. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94056. }
  94057. }
  94058. else if (bpp === 64) {
  94059. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94060. if (sphericalPolynomialFaces && i == 0) {
  94061. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94062. }
  94063. }
  94064. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94065. }
  94066. else {
  94067. if (bpp === 128) {
  94068. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94069. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94070. if (sphericalPolynomialFaces && i == 0) {
  94071. sphericalPolynomialFaces.push(floatArray);
  94072. }
  94073. }
  94074. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  94075. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94076. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94077. if (sphericalPolynomialFaces && i == 0) {
  94078. sphericalPolynomialFaces.push(floatArray);
  94079. }
  94080. }
  94081. else { // 64
  94082. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94083. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94084. if (sphericalPolynomialFaces && i == 0) {
  94085. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94086. }
  94087. }
  94088. }
  94089. if (floatArray) {
  94090. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  94091. }
  94092. }
  94093. else if (info.isRGB) {
  94094. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94095. if (bpp === 24) {
  94096. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  94097. dataLength = width * height * 3;
  94098. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  94099. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94100. }
  94101. else { // 32
  94102. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94103. dataLength = width * height * 4;
  94104. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  94105. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94106. }
  94107. }
  94108. else if (info.isLuminance) {
  94109. var unpackAlignment = engine._getUnpackAlignement();
  94110. var unpaddedRowSize = width;
  94111. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  94112. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  94113. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  94114. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  94115. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94116. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94117. }
  94118. else {
  94119. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  94120. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  94121. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94122. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  94123. }
  94124. }
  94125. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  94126. width *= 0.5;
  94127. height *= 0.5;
  94128. width = Math.max(1.0, width);
  94129. height = Math.max(1.0, height);
  94130. }
  94131. if (currentFace !== undefined) {
  94132. // Loading a single face
  94133. break;
  94134. }
  94135. }
  94136. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  94137. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  94138. size: header[off_width],
  94139. right: sphericalPolynomialFaces[0],
  94140. left: sphericalPolynomialFaces[1],
  94141. up: sphericalPolynomialFaces[2],
  94142. down: sphericalPolynomialFaces[3],
  94143. front: sphericalPolynomialFaces[4],
  94144. back: sphericalPolynomialFaces[5],
  94145. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  94146. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  94147. gammaSpace: false,
  94148. });
  94149. }
  94150. else {
  94151. info.sphericalPolynomial = undefined;
  94152. }
  94153. };
  94154. DDSTools.StoreLODInAlphaChannel = false;
  94155. return DDSTools;
  94156. }());
  94157. BABYLON.DDSTools = DDSTools;
  94158. })(BABYLON || (BABYLON = {}));
  94159. //# sourceMappingURL=babylon.dds.js.map
  94160. var BABYLON;
  94161. (function (BABYLON) {
  94162. /**
  94163. * Implementation of the DDS Texture Loader.
  94164. */
  94165. var DDSTextureLoader = /** @class */ (function () {
  94166. function DDSTextureLoader() {
  94167. /**
  94168. * Defines wether the loader supports cascade loading the different faces.
  94169. */
  94170. this.supportCascades = true;
  94171. }
  94172. /**
  94173. * This returns if the loader support the current file information.
  94174. * @param extension defines the file extension of the file being loaded
  94175. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94176. * @param fallback defines the fallback internal texture if any
  94177. * @param isBase64 defines whether the texture is encoded as a base64
  94178. * @param isBuffer defines whether the texture data are stored as a buffer
  94179. * @returns true if the loader can load the specified file
  94180. */
  94181. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94182. return extension.indexOf(".dds") === 0;
  94183. };
  94184. /**
  94185. * Transform the url before loading if required.
  94186. * @param rootUrl the url of the texture
  94187. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94188. * @returns the transformed texture
  94189. */
  94190. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94191. return rootUrl;
  94192. };
  94193. /**
  94194. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94195. * @param rootUrl the url of the texture
  94196. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94197. * @returns the fallback texture
  94198. */
  94199. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94200. return null;
  94201. };
  94202. /**
  94203. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94204. * @param data contains the texture data
  94205. * @param texture defines the BabylonJS internal texture
  94206. * @param createPolynomials will be true if polynomials have been requested
  94207. * @param onLoad defines the callback to trigger once the texture is ready
  94208. * @param onError defines the callback to trigger in case of error
  94209. */
  94210. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  94211. var engine = texture.getEngine();
  94212. var info;
  94213. var loadMipmap = false;
  94214. if (Array.isArray(imgs)) {
  94215. for (var index = 0; index < imgs.length; index++) {
  94216. var data_1 = imgs[index];
  94217. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  94218. texture.width = info.width;
  94219. texture.height = info.height;
  94220. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  94221. engine._unpackFlipY(info.isCompressed);
  94222. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  94223. if (!info.isFourCC && info.mipmapCount === 1) {
  94224. engine.generateMipMapsForCubemap(texture);
  94225. }
  94226. }
  94227. }
  94228. else {
  94229. var data = imgs;
  94230. info = BABYLON.DDSTools.GetDDSInfo(data);
  94231. texture.width = info.width;
  94232. texture.height = info.height;
  94233. if (createPolynomials) {
  94234. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  94235. }
  94236. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  94237. engine._unpackFlipY(info.isCompressed);
  94238. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  94239. if (!info.isFourCC && info.mipmapCount === 1) {
  94240. engine.generateMipMapsForCubemap(texture);
  94241. }
  94242. }
  94243. engine._setCubeMapTextureParams(loadMipmap);
  94244. texture.isReady = true;
  94245. if (onLoad) {
  94246. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  94247. }
  94248. };
  94249. /**
  94250. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94251. * @param data contains the texture data
  94252. * @param texture defines the BabylonJS internal texture
  94253. * @param callback defines the method to call once ready to upload
  94254. */
  94255. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  94256. var info = BABYLON.DDSTools.GetDDSInfo(data);
  94257. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  94258. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  94259. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  94260. });
  94261. };
  94262. return DDSTextureLoader;
  94263. }());
  94264. // Register the loader.
  94265. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  94266. })(BABYLON || (BABYLON = {}));
  94267. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  94268. var BABYLON;
  94269. (function (BABYLON) {
  94270. /*
  94271. * Based on jsTGALoader - Javascript loader for TGA file
  94272. * By Vincent Thibault
  94273. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  94274. */
  94275. var TGATools = /** @class */ (function () {
  94276. function TGATools() {
  94277. }
  94278. TGATools.GetTGAHeader = function (data) {
  94279. var offset = 0;
  94280. var header = {
  94281. id_length: data[offset++],
  94282. colormap_type: data[offset++],
  94283. image_type: data[offset++],
  94284. colormap_index: data[offset++] | data[offset++] << 8,
  94285. colormap_length: data[offset++] | data[offset++] << 8,
  94286. colormap_size: data[offset++],
  94287. origin: [
  94288. data[offset++] | data[offset++] << 8,
  94289. data[offset++] | data[offset++] << 8
  94290. ],
  94291. width: data[offset++] | data[offset++] << 8,
  94292. height: data[offset++] | data[offset++] << 8,
  94293. pixel_size: data[offset++],
  94294. flags: data[offset++]
  94295. };
  94296. return header;
  94297. };
  94298. /**
  94299. * Uploads TGA content to a Babylon Texture
  94300. * @hidden
  94301. */
  94302. TGATools.UploadContent = function (texture, data) {
  94303. // Not enough data to contain header ?
  94304. if (data.length < 19) {
  94305. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  94306. return;
  94307. }
  94308. // Read Header
  94309. var offset = 18;
  94310. var header = TGATools.GetTGAHeader(data);
  94311. // Assume it's a valid Targa file.
  94312. if (header.id_length + offset > data.length) {
  94313. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  94314. return;
  94315. }
  94316. // Skip not needed data
  94317. offset += header.id_length;
  94318. var use_rle = false;
  94319. var use_pal = false;
  94320. var use_grey = false;
  94321. // Get some informations.
  94322. switch (header.image_type) {
  94323. case TGATools._TYPE_RLE_INDEXED:
  94324. use_rle = true;
  94325. case TGATools._TYPE_INDEXED:
  94326. use_pal = true;
  94327. break;
  94328. case TGATools._TYPE_RLE_RGB:
  94329. use_rle = true;
  94330. case TGATools._TYPE_RGB:
  94331. // use_rgb = true;
  94332. break;
  94333. case TGATools._TYPE_RLE_GREY:
  94334. use_rle = true;
  94335. case TGATools._TYPE_GREY:
  94336. use_grey = true;
  94337. break;
  94338. }
  94339. var pixel_data;
  94340. // var numAlphaBits = header.flags & 0xf;
  94341. var pixel_size = header.pixel_size >> 3;
  94342. var pixel_total = header.width * header.height * pixel_size;
  94343. // Read palettes
  94344. var palettes;
  94345. if (use_pal) {
  94346. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  94347. }
  94348. // Read LRE
  94349. if (use_rle) {
  94350. pixel_data = new Uint8Array(pixel_total);
  94351. var c, count, i;
  94352. var localOffset = 0;
  94353. var pixels = new Uint8Array(pixel_size);
  94354. while (offset < pixel_total && localOffset < pixel_total) {
  94355. c = data[offset++];
  94356. count = (c & 0x7f) + 1;
  94357. // RLE pixels
  94358. if (c & 0x80) {
  94359. // Bind pixel tmp array
  94360. for (i = 0; i < pixel_size; ++i) {
  94361. pixels[i] = data[offset++];
  94362. }
  94363. // Copy pixel array
  94364. for (i = 0; i < count; ++i) {
  94365. pixel_data.set(pixels, localOffset + i * pixel_size);
  94366. }
  94367. localOffset += pixel_size * count;
  94368. }
  94369. // Raw pixels
  94370. else {
  94371. count *= pixel_size;
  94372. for (i = 0; i < count; ++i) {
  94373. pixel_data[localOffset + i] = data[offset++];
  94374. }
  94375. localOffset += count;
  94376. }
  94377. }
  94378. }
  94379. // RAW Pixels
  94380. else {
  94381. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  94382. }
  94383. // Load to texture
  94384. var x_start, y_start, x_step, y_step, y_end, x_end;
  94385. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  94386. default:
  94387. case TGATools._ORIGIN_UL:
  94388. x_start = 0;
  94389. x_step = 1;
  94390. x_end = header.width;
  94391. y_start = 0;
  94392. y_step = 1;
  94393. y_end = header.height;
  94394. break;
  94395. case TGATools._ORIGIN_BL:
  94396. x_start = 0;
  94397. x_step = 1;
  94398. x_end = header.width;
  94399. y_start = header.height - 1;
  94400. y_step = -1;
  94401. y_end = -1;
  94402. break;
  94403. case TGATools._ORIGIN_UR:
  94404. x_start = header.width - 1;
  94405. x_step = -1;
  94406. x_end = -1;
  94407. y_start = 0;
  94408. y_step = 1;
  94409. y_end = header.height;
  94410. break;
  94411. case TGATools._ORIGIN_BR:
  94412. x_start = header.width - 1;
  94413. x_step = -1;
  94414. x_end = -1;
  94415. y_start = header.height - 1;
  94416. y_step = -1;
  94417. y_end = -1;
  94418. break;
  94419. }
  94420. // Load the specify method
  94421. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  94422. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  94423. var engine = texture.getEngine();
  94424. engine._uploadDataToTextureDirectly(texture, imageData);
  94425. };
  94426. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94427. var image = pixel_data, colormap = palettes;
  94428. var width = header.width, height = header.height;
  94429. var color, i = 0, x, y;
  94430. var imageData = new Uint8Array(width * height * 4);
  94431. for (y = y_start; y !== y_end; y += y_step) {
  94432. for (x = x_start; x !== x_end; x += x_step, i++) {
  94433. color = image[i];
  94434. imageData[(x + width * y) * 4 + 3] = 255;
  94435. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  94436. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  94437. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  94438. }
  94439. }
  94440. return imageData;
  94441. };
  94442. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94443. var image = pixel_data;
  94444. var width = header.width, height = header.height;
  94445. var color, i = 0, x, y;
  94446. var imageData = new Uint8Array(width * height * 4);
  94447. for (y = y_start; y !== y_end; y += y_step) {
  94448. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  94449. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  94450. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  94451. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  94452. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  94453. imageData[(x + width * y) * 4 + 0] = r;
  94454. imageData[(x + width * y) * 4 + 1] = g;
  94455. imageData[(x + width * y) * 4 + 2] = b;
  94456. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  94457. }
  94458. }
  94459. return imageData;
  94460. };
  94461. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94462. var image = pixel_data;
  94463. var width = header.width, height = header.height;
  94464. var i = 0, x, y;
  94465. var imageData = new Uint8Array(width * height * 4);
  94466. for (y = y_start; y !== y_end; y += y_step) {
  94467. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  94468. imageData[(x + width * y) * 4 + 3] = 255;
  94469. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  94470. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  94471. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  94472. }
  94473. }
  94474. return imageData;
  94475. };
  94476. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94477. var image = pixel_data;
  94478. var width = header.width, height = header.height;
  94479. var i = 0, x, y;
  94480. var imageData = new Uint8Array(width * height * 4);
  94481. for (y = y_start; y !== y_end; y += y_step) {
  94482. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  94483. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  94484. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  94485. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  94486. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  94487. }
  94488. }
  94489. return imageData;
  94490. };
  94491. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94492. var image = pixel_data;
  94493. var width = header.width, height = header.height;
  94494. var color, i = 0, x, y;
  94495. var imageData = new Uint8Array(width * height * 4);
  94496. for (y = y_start; y !== y_end; y += y_step) {
  94497. for (x = x_start; x !== x_end; x += x_step, i++) {
  94498. color = image[i];
  94499. imageData[(x + width * y) * 4 + 0] = color;
  94500. imageData[(x + width * y) * 4 + 1] = color;
  94501. imageData[(x + width * y) * 4 + 2] = color;
  94502. imageData[(x + width * y) * 4 + 3] = 255;
  94503. }
  94504. }
  94505. return imageData;
  94506. };
  94507. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94508. var image = pixel_data;
  94509. var width = header.width, height = header.height;
  94510. var i = 0, x, y;
  94511. var imageData = new Uint8Array(width * height * 4);
  94512. for (y = y_start; y !== y_end; y += y_step) {
  94513. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  94514. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  94515. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  94516. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  94517. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  94518. }
  94519. }
  94520. return imageData;
  94521. };
  94522. //private static _TYPE_NO_DATA = 0;
  94523. TGATools._TYPE_INDEXED = 1;
  94524. TGATools._TYPE_RGB = 2;
  94525. TGATools._TYPE_GREY = 3;
  94526. TGATools._TYPE_RLE_INDEXED = 9;
  94527. TGATools._TYPE_RLE_RGB = 10;
  94528. TGATools._TYPE_RLE_GREY = 11;
  94529. TGATools._ORIGIN_MASK = 0x30;
  94530. TGATools._ORIGIN_SHIFT = 0x04;
  94531. TGATools._ORIGIN_BL = 0x00;
  94532. TGATools._ORIGIN_BR = 0x01;
  94533. TGATools._ORIGIN_UL = 0x02;
  94534. TGATools._ORIGIN_UR = 0x03;
  94535. return TGATools;
  94536. }());
  94537. BABYLON.TGATools = TGATools;
  94538. })(BABYLON || (BABYLON = {}));
  94539. //# sourceMappingURL=babylon.tga.js.map
  94540. var BABYLON;
  94541. (function (BABYLON) {
  94542. /**
  94543. * Implementation of the TGA Texture Loader.
  94544. */
  94545. var TGATextureLoader = /** @class */ (function () {
  94546. function TGATextureLoader() {
  94547. /**
  94548. * Defines wether the loader supports cascade loading the different faces.
  94549. */
  94550. this.supportCascades = false;
  94551. }
  94552. /**
  94553. * This returns if the loader support the current file information.
  94554. * @param extension defines the file extension of the file being loaded
  94555. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94556. * @param fallback defines the fallback internal texture if any
  94557. * @param isBase64 defines whether the texture is encoded as a base64
  94558. * @param isBuffer defines whether the texture data are stored as a buffer
  94559. * @returns true if the loader can load the specified file
  94560. */
  94561. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94562. return extension.indexOf(".tga") === 0;
  94563. };
  94564. /**
  94565. * Transform the url before loading if required.
  94566. * @param rootUrl the url of the texture
  94567. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94568. * @returns the transformed texture
  94569. */
  94570. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94571. return rootUrl;
  94572. };
  94573. /**
  94574. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94575. * @param rootUrl the url of the texture
  94576. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94577. * @returns the fallback texture
  94578. */
  94579. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94580. return null;
  94581. };
  94582. /**
  94583. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94584. * @param data contains the texture data
  94585. * @param texture defines the BabylonJS internal texture
  94586. * @param createPolynomials will be true if polynomials have been requested
  94587. * @param onLoad defines the callback to trigger once the texture is ready
  94588. * @param onError defines the callback to trigger in case of error
  94589. */
  94590. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94591. throw ".env not supported in Cube.";
  94592. };
  94593. /**
  94594. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94595. * @param data contains the texture data
  94596. * @param texture defines the BabylonJS internal texture
  94597. * @param callback defines the method to call once ready to upload
  94598. */
  94599. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  94600. var uintData = new Uint8Array(data);
  94601. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  94602. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  94603. BABYLON.TGATools.UploadContent(texture, uintData);
  94604. });
  94605. };
  94606. return TGATextureLoader;
  94607. }());
  94608. // Register the loader.
  94609. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  94610. })(BABYLON || (BABYLON = {}));
  94611. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  94612. var BABYLON;
  94613. (function (BABYLON) {
  94614. /**
  94615. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  94616. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  94617. */
  94618. var KhronosTextureContainer = /** @class */ (function () {
  94619. /**
  94620. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  94621. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  94622. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  94623. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  94624. */
  94625. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  94626. this.arrayBuffer = arrayBuffer;
  94627. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  94628. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  94629. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  94630. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  94631. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  94632. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  94633. BABYLON.Tools.Error("texture missing KTX identifier");
  94634. return;
  94635. }
  94636. // load the reset of the header in native 32 bit int
  94637. var header = new Int32Array(this.arrayBuffer, 12, 13);
  94638. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  94639. var oppositeEndianess = header[0] === 0x01020304;
  94640. // read all the header elements in order they exist in the file, without modification (sans endainness)
  94641. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  94642. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  94643. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  94644. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  94645. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  94646. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  94647. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  94648. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  94649. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  94650. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  94651. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  94652. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  94653. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  94654. if (this.glType !== 0) {
  94655. BABYLON.Tools.Error("only compressed formats currently supported");
  94656. return;
  94657. }
  94658. else {
  94659. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  94660. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  94661. }
  94662. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  94663. BABYLON.Tools.Error("only 2D textures currently supported");
  94664. return;
  94665. }
  94666. if (this.numberOfArrayElements !== 0) {
  94667. BABYLON.Tools.Error("texture arrays not currently supported");
  94668. return;
  94669. }
  94670. if (this.numberOfFaces !== facesExpected) {
  94671. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  94672. return;
  94673. }
  94674. // we now have a completely validated file, so could use existence of loadType as success
  94675. // would need to make this more elaborate & adjust checks above to support more than one load type
  94676. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  94677. }
  94678. // not as fast hardware based, but will probably never need to use
  94679. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  94680. return ((val & 0xFF) << 24)
  94681. | ((val & 0xFF00) << 8)
  94682. | ((val >> 8) & 0xFF00)
  94683. | ((val >> 24) & 0xFF);
  94684. };
  94685. /**
  94686. * Uploads KTX content to a Babylon Texture.
  94687. * It is assumed that the texture has already been created & is currently bound
  94688. * @hidden
  94689. */
  94690. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  94691. switch (this.loadType) {
  94692. case KhronosTextureContainer.COMPRESSED_2D:
  94693. this._upload2DCompressedLevels(texture, loadMipmaps);
  94694. break;
  94695. case KhronosTextureContainer.TEX_2D:
  94696. case KhronosTextureContainer.COMPRESSED_3D:
  94697. case KhronosTextureContainer.TEX_3D:
  94698. }
  94699. };
  94700. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  94701. // initialize width & height for level 1
  94702. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  94703. var width = this.pixelWidth;
  94704. var height = this.pixelHeight;
  94705. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  94706. for (var level = 0; level < mipmapCount; level++) {
  94707. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  94708. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  94709. for (var face = 0; face < this.numberOfFaces; face++) {
  94710. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  94711. var engine = texture.getEngine();
  94712. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  94713. dataOffset += imageSize; // add size of the image for the next face/mipmap
  94714. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  94715. }
  94716. width = Math.max(1.0, width * 0.5);
  94717. height = Math.max(1.0, height * 0.5);
  94718. }
  94719. };
  94720. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  94721. // load types
  94722. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  94723. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  94724. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  94725. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  94726. return KhronosTextureContainer;
  94727. }());
  94728. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  94729. })(BABYLON || (BABYLON = {}));
  94730. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  94731. var BABYLON;
  94732. (function (BABYLON) {
  94733. /**
  94734. * Implementation of the KTX Texture Loader.
  94735. */
  94736. var KTXTextureLoader = /** @class */ (function () {
  94737. function KTXTextureLoader() {
  94738. /**
  94739. * Defines wether the loader supports cascade loading the different faces.
  94740. */
  94741. this.supportCascades = false;
  94742. }
  94743. /**
  94744. * This returns if the loader support the current file information.
  94745. * @param extension defines the file extension of the file being loaded
  94746. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94747. * @param fallback defines the fallback internal texture if any
  94748. * @param isBase64 defines whether the texture is encoded as a base64
  94749. * @param isBuffer defines whether the texture data are stored as a buffer
  94750. * @returns true if the loader can load the specified file
  94751. */
  94752. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94753. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  94754. return true;
  94755. }
  94756. return false;
  94757. };
  94758. /**
  94759. * Transform the url before loading if required.
  94760. * @param rootUrl the url of the texture
  94761. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94762. * @returns the transformed texture
  94763. */
  94764. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94765. var lastDot = rootUrl.lastIndexOf('.');
  94766. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  94767. };
  94768. /**
  94769. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94770. * @param rootUrl the url of the texture
  94771. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94772. * @returns the fallback texture
  94773. */
  94774. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94775. // remove the format appended to the rootUrl in the original createCubeTexture call.
  94776. var exp = new RegExp("" + textureFormatInUse + "$");
  94777. return rootUrl.replace(exp, "");
  94778. };
  94779. /**
  94780. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94781. * @param data contains the texture data
  94782. * @param texture defines the BabylonJS internal texture
  94783. * @param createPolynomials will be true if polynomials have been requested
  94784. * @param onLoad defines the callback to trigger once the texture is ready
  94785. * @param onError defines the callback to trigger in case of error
  94786. */
  94787. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94788. if (Array.isArray(data)) {
  94789. return;
  94790. }
  94791. var engine = texture.getEngine();
  94792. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  94793. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  94794. engine._unpackFlipY(true);
  94795. ktx.uploadLevels(texture, texture.generateMipMaps);
  94796. texture.width = ktx.pixelWidth;
  94797. texture.height = ktx.pixelHeight;
  94798. engine._setCubeMapTextureParams(loadMipmap);
  94799. texture.isReady = true;
  94800. };
  94801. /**
  94802. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94803. * @param data contains the texture data
  94804. * @param texture defines the BabylonJS internal texture
  94805. * @param callback defines the method to call once ready to upload
  94806. */
  94807. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  94808. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  94809. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  94810. ktx.uploadLevels(texture, texture.generateMipMaps);
  94811. });
  94812. };
  94813. return KTXTextureLoader;
  94814. }());
  94815. // Register the loader.
  94816. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  94817. })(BABYLON || (BABYLON = {}));
  94818. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  94819. var BABYLON;
  94820. (function (BABYLON) {
  94821. /**
  94822. * Sets of helpers addressing the serialization and deserialization of environment texture
  94823. * stored in a BabylonJS env file.
  94824. * Those files are usually stored as .env files.
  94825. */
  94826. var EnvironmentTextureTools = /** @class */ (function () {
  94827. function EnvironmentTextureTools() {
  94828. }
  94829. /**
  94830. * Gets the environment info from an env file.
  94831. * @param data The array buffer containing the .env bytes.
  94832. * @returns the environment file info (the json header) if successfully parsed.
  94833. */
  94834. EnvironmentTextureTools.GetEnvInfo = function (data) {
  94835. var dataView = new DataView(data);
  94836. var pos = 0;
  94837. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  94838. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  94839. BABYLON.Tools.Error('Not a babylon environment map');
  94840. return null;
  94841. }
  94842. }
  94843. // Read json manifest - collect characters up to null terminator
  94844. var manifestString = '';
  94845. var charCode = 0x00;
  94846. while ((charCode = dataView.getUint8(pos++))) {
  94847. manifestString += String.fromCharCode(charCode);
  94848. }
  94849. var manifest = JSON.parse(manifestString);
  94850. if (manifest.specular) {
  94851. // Extend the header with the position of the payload.
  94852. manifest.specular.specularDataPosition = pos;
  94853. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  94854. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  94855. }
  94856. return manifest;
  94857. };
  94858. /**
  94859. * Creates an environment texture from a loaded cube texture.
  94860. * @param texture defines the cube texture to convert in env file
  94861. * @return a promise containing the environment data if succesfull.
  94862. */
  94863. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  94864. var _this = this;
  94865. var internalTexture = texture.getInternalTexture();
  94866. if (!internalTexture) {
  94867. return Promise.reject("The cube texture is invalid.");
  94868. }
  94869. if (!texture._prefiltered) {
  94870. return Promise.reject("The cube texture is invalid (not prefiltered).");
  94871. }
  94872. var engine = internalTexture.getEngine();
  94873. if (engine && engine.premultipliedAlpha) {
  94874. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  94875. }
  94876. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  94877. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  94878. }
  94879. var canvas = engine.getRenderingCanvas();
  94880. if (!canvas) {
  94881. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  94882. }
  94883. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94884. if (!engine.getCaps().textureFloatRender) {
  94885. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94886. if (!engine.getCaps().textureHalfFloatRender) {
  94887. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  94888. }
  94889. }
  94890. var cubeWidth = internalTexture.width;
  94891. var hostingScene = new BABYLON.Scene(engine);
  94892. var specularTextures = {};
  94893. var promises = [];
  94894. // Read and collect all mipmaps data from the cube.
  94895. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  94896. mipmapsCount = Math.round(mipmapsCount);
  94897. var _loop_1 = function (i) {
  94898. var faceWidth = Math.pow(2, mipmapsCount - i);
  94899. var _loop_2 = function (face) {
  94900. var data = texture.readPixels(face, i);
  94901. // Creates a temp texture with the face data.
  94902. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  94903. // And rgbdEncode them.
  94904. var promise = new Promise(function (resolve, reject) {
  94905. 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);
  94906. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  94907. rgbdPostProcess.onApply = function (effect) {
  94908. effect._bindTexture("textureSampler", tempTexture);
  94909. };
  94910. // As the process needs to happen on the main canvas, keep track of the current size
  94911. var currentW = engine.getRenderWidth();
  94912. var currentH = engine.getRenderHeight();
  94913. // Set the desired size for the texture
  94914. engine.setSize(faceWidth, faceWidth);
  94915. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  94916. // Reading datas from WebGL
  94917. BABYLON.Tools.ToBlob(canvas, function (blob) {
  94918. var fileReader = new FileReader();
  94919. fileReader.onload = function (event) {
  94920. var arrayBuffer = event.target.result;
  94921. specularTextures[i * 6 + face] = arrayBuffer;
  94922. resolve();
  94923. };
  94924. fileReader.readAsArrayBuffer(blob);
  94925. });
  94926. // Reapply the previous canvas size
  94927. engine.setSize(currentW, currentH);
  94928. });
  94929. });
  94930. promises.push(promise);
  94931. };
  94932. // All faces of the cube.
  94933. for (var face = 0; face < 6; face++) {
  94934. _loop_2(face);
  94935. }
  94936. };
  94937. for (var i = 0; i <= mipmapsCount; i++) {
  94938. _loop_1(i);
  94939. }
  94940. // Once all the textures haves been collected as RGBD stored in PNGs
  94941. return Promise.all(promises).then(function () {
  94942. // We can delete the hosting scene keeping track of all the creation objects
  94943. hostingScene.dispose();
  94944. // Creates the json header for the env texture
  94945. var info = {
  94946. version: 1,
  94947. width: cubeWidth,
  94948. irradiance: _this._CreateEnvTextureIrradiance(texture),
  94949. specular: {
  94950. mipmaps: [],
  94951. lodGenerationScale: texture.lodGenerationScale
  94952. }
  94953. };
  94954. // Sets the specular image data information
  94955. var position = 0;
  94956. for (var i = 0; i <= mipmapsCount; i++) {
  94957. for (var face = 0; face < 6; face++) {
  94958. var byteLength = specularTextures[i * 6 + face].byteLength;
  94959. info.specular.mipmaps.push({
  94960. length: byteLength,
  94961. position: position
  94962. });
  94963. position += byteLength;
  94964. }
  94965. }
  94966. // Encode the JSON as an array buffer
  94967. var infoString = JSON.stringify(info);
  94968. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  94969. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  94970. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  94971. infoView[i] = infoString.charCodeAt(i);
  94972. }
  94973. // Ends up with a null terminator for easier parsing
  94974. infoView[infoString.length] = 0x00;
  94975. // Computes the final required size and creates the storage
  94976. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  94977. var finalBuffer = new ArrayBuffer(totalSize);
  94978. var finalBufferView = new Uint8Array(finalBuffer);
  94979. var dataView = new DataView(finalBuffer);
  94980. // Copy the magic bytes identifying the file in
  94981. var pos = 0;
  94982. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  94983. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  94984. }
  94985. // Add the json info
  94986. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  94987. pos += infoBuffer.byteLength;
  94988. // Finally inserts the texture data
  94989. for (var i = 0; i <= mipmapsCount; i++) {
  94990. for (var face = 0; face < 6; face++) {
  94991. var dataBuffer = specularTextures[i * 6 + face];
  94992. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  94993. pos += dataBuffer.byteLength;
  94994. }
  94995. }
  94996. // Voila
  94997. return finalBuffer;
  94998. });
  94999. };
  95000. /**
  95001. * Creates a JSON representation of the spherical data.
  95002. * @param texture defines the texture containing the polynomials
  95003. * @return the JSON representation of the spherical info
  95004. */
  95005. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  95006. var polynmials = texture.sphericalPolynomial;
  95007. if (polynmials == null) {
  95008. return null;
  95009. }
  95010. return {
  95011. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  95012. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  95013. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  95014. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  95015. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  95016. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  95017. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  95018. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  95019. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  95020. };
  95021. };
  95022. /**
  95023. * Uploads the texture info contained in the env file to the GPU.
  95024. * @param texture defines the internal texture to upload to
  95025. * @param arrayBuffer defines the buffer cotaining the data to load
  95026. * @param info defines the texture info retrieved through the GetEnvInfo method
  95027. * @returns a promise
  95028. */
  95029. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  95030. if (info.version !== 1) {
  95031. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  95032. }
  95033. var specularInfo = info.specular;
  95034. if (!specularInfo) {
  95035. // Nothing else parsed so far
  95036. return Promise.resolve();
  95037. }
  95038. // Double checks the enclosed info
  95039. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  95040. mipmapsCount = Math.round(mipmapsCount) + 1;
  95041. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  95042. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  95043. }
  95044. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  95045. var imageData = new Array(mipmapsCount);
  95046. for (var i = 0; i < mipmapsCount; i++) {
  95047. imageData[i] = new Array(6);
  95048. for (var face = 0; face < 6; face++) {
  95049. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  95050. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  95051. }
  95052. }
  95053. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  95054. };
  95055. /**
  95056. * Uploads the levels of image data to the GPU.
  95057. * @param texture defines the internal texture to upload to
  95058. * @param imageData defines the array buffer views of image data [mipmap][face]
  95059. * @returns a promise
  95060. */
  95061. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  95062. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  95063. throw new Error("Texture size must be a power of two");
  95064. }
  95065. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  95066. // Gets everything ready.
  95067. var engine = texture.getEngine();
  95068. var expandTexture = false;
  95069. var generateNonLODTextures = false;
  95070. var rgbdPostProcess = null;
  95071. var cubeRtt = null;
  95072. var lodTextures = null;
  95073. var caps = engine.getCaps();
  95074. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  95075. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95076. texture.generateMipMaps = true;
  95077. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  95078. // Add extra process if texture lod is not supported
  95079. if (!caps.textureLOD) {
  95080. expandTexture = false;
  95081. generateNonLODTextures = true;
  95082. lodTextures = {};
  95083. }
  95084. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  95085. else if (engine.webGLVersion < 2) {
  95086. expandTexture = false;
  95087. }
  95088. // If half float available we can uncompress the texture
  95089. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  95090. expandTexture = true;
  95091. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95092. }
  95093. // If full float available we can uncompress the texture
  95094. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  95095. expandTexture = true;
  95096. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95097. }
  95098. // Expand the texture if possible
  95099. if (expandTexture) {
  95100. // Simply run through the decode PP
  95101. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  95102. texture._isRGBD = false;
  95103. texture.invertY = false;
  95104. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  95105. generateDepthBuffer: false,
  95106. generateMipMaps: true,
  95107. generateStencilBuffer: false,
  95108. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  95109. type: texture.type,
  95110. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  95111. });
  95112. }
  95113. else {
  95114. texture._isRGBD = true;
  95115. texture.invertY = true;
  95116. // In case of missing support, applies the same patch than DDS files.
  95117. if (generateNonLODTextures) {
  95118. var mipSlices = 3;
  95119. var scale = texture._lodGenerationScale;
  95120. var offset = texture._lodGenerationOffset;
  95121. for (var i = 0; i < mipSlices; i++) {
  95122. //compute LOD from even spacing in smoothness (matching shader calculation)
  95123. var smoothness = i / (mipSlices - 1);
  95124. var roughness = 1 - smoothness;
  95125. var minLODIndex = offset; // roughness = 0
  95126. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  95127. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  95128. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  95129. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  95130. glTextureFromLod.isCube = true;
  95131. glTextureFromLod.invertY = true;
  95132. glTextureFromLod.generateMipMaps = false;
  95133. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  95134. // Wrap in a base texture for easy binding.
  95135. var lodTexture = new BABYLON.BaseTexture(null);
  95136. lodTexture.isCube = true;
  95137. lodTexture._texture = glTextureFromLod;
  95138. lodTextures[mipmapIndex] = lodTexture;
  95139. switch (i) {
  95140. case 0:
  95141. texture._lodTextureLow = lodTexture;
  95142. break;
  95143. case 1:
  95144. texture._lodTextureMid = lodTexture;
  95145. break;
  95146. case 2:
  95147. texture._lodTextureHigh = lodTexture;
  95148. break;
  95149. }
  95150. }
  95151. }
  95152. }
  95153. var promises = [];
  95154. var _loop_3 = function (i) {
  95155. var _loop_4 = function (face) {
  95156. // Constructs an image element from image data
  95157. var bytes = imageData[i][face];
  95158. var blob = new Blob([bytes], { type: 'image/png' });
  95159. var url = URL.createObjectURL(blob);
  95160. var image = new Image();
  95161. image.src = url;
  95162. // Enqueue promise to upload to the texture.
  95163. var promise = new Promise(function (resolve, reject) {
  95164. image.onload = function () {
  95165. if (expandTexture) {
  95166. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  95167. reject(message);
  95168. }, image);
  95169. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  95170. // Uncompress the data to a RTT
  95171. rgbdPostProcess.onApply = function (effect) {
  95172. effect._bindTexture("textureSampler", tempTexture_1);
  95173. effect.setFloat2("scale", 1, 1);
  95174. };
  95175. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  95176. // Cleanup
  95177. engine.restoreDefaultFramebuffer();
  95178. tempTexture_1.dispose();
  95179. window.URL.revokeObjectURL(url);
  95180. resolve();
  95181. });
  95182. }
  95183. else {
  95184. engine._uploadImageToTexture(texture, image, face, i);
  95185. // Upload the face to the non lod texture support
  95186. if (generateNonLODTextures) {
  95187. var lodTexture = lodTextures[i];
  95188. if (lodTexture) {
  95189. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  95190. }
  95191. }
  95192. resolve();
  95193. }
  95194. };
  95195. image.onerror = function (error) {
  95196. reject(error);
  95197. };
  95198. });
  95199. promises.push(promise);
  95200. };
  95201. // All faces
  95202. for (var face = 0; face < 6; face++) {
  95203. _loop_4(face);
  95204. }
  95205. };
  95206. // All mipmaps up to provided number of images
  95207. for (var i = 0; i < imageData.length; i++) {
  95208. _loop_3(i);
  95209. }
  95210. // Fill remaining mipmaps with black textures.
  95211. if (imageData.length < mipmapsCount) {
  95212. var data = void 0;
  95213. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  95214. var dataLength = size * size * 4;
  95215. switch (texture.type) {
  95216. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  95217. data = new Uint8Array(dataLength);
  95218. break;
  95219. }
  95220. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  95221. data = new Uint16Array(dataLength);
  95222. break;
  95223. }
  95224. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  95225. data = new Float32Array(dataLength);
  95226. break;
  95227. }
  95228. }
  95229. for (var i = imageData.length; i < mipmapsCount; i++) {
  95230. for (var face = 0; face < 6; face++) {
  95231. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  95232. }
  95233. }
  95234. }
  95235. // Once all done, finishes the cleanup and return
  95236. return Promise.all(promises).then(function () {
  95237. // Release temp RTT.
  95238. if (cubeRtt) {
  95239. engine._releaseFramebufferObjects(cubeRtt);
  95240. cubeRtt._swapAndDie(texture);
  95241. }
  95242. // Release temp Post Process.
  95243. if (rgbdPostProcess) {
  95244. rgbdPostProcess.dispose();
  95245. }
  95246. // Flag internal texture as ready in case they are in use.
  95247. if (generateNonLODTextures) {
  95248. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  95249. texture._lodTextureHigh._texture.isReady = true;
  95250. }
  95251. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  95252. texture._lodTextureMid._texture.isReady = true;
  95253. }
  95254. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  95255. texture._lodTextureLow._texture.isReady = true;
  95256. }
  95257. }
  95258. });
  95259. };
  95260. /**
  95261. * Uploads spherical polynomials information to the texture.
  95262. * @param texture defines the texture we are trying to upload the information to
  95263. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  95264. */
  95265. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  95266. if (info.version !== 1) {
  95267. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  95268. }
  95269. var irradianceInfo = info.irradiance;
  95270. if (!irradianceInfo) {
  95271. return;
  95272. }
  95273. var sp = new BABYLON.SphericalPolynomial();
  95274. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  95275. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  95276. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  95277. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  95278. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  95279. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  95280. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  95281. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  95282. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  95283. texture._sphericalPolynomial = sp;
  95284. };
  95285. /**
  95286. * Magic number identifying the env file.
  95287. */
  95288. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  95289. return EnvironmentTextureTools;
  95290. }());
  95291. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  95292. })(BABYLON || (BABYLON = {}));
  95293. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  95294. var BABYLON;
  95295. (function (BABYLON) {
  95296. /**
  95297. * Implementation of the ENV Texture Loader.
  95298. */
  95299. var ENVTextureLoader = /** @class */ (function () {
  95300. function ENVTextureLoader() {
  95301. /**
  95302. * Defines wether the loader supports cascade loading the different faces.
  95303. */
  95304. this.supportCascades = false;
  95305. }
  95306. /**
  95307. * This returns if the loader support the current file information.
  95308. * @param extension defines the file extension of the file being loaded
  95309. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95310. * @param fallback defines the fallback internal texture if any
  95311. * @param isBase64 defines whether the texture is encoded as a base64
  95312. * @param isBuffer defines whether the texture data are stored as a buffer
  95313. * @returns true if the loader can load the specified file
  95314. */
  95315. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95316. return extension.indexOf(".env") === 0;
  95317. };
  95318. /**
  95319. * Transform the url before loading if required.
  95320. * @param rootUrl the url of the texture
  95321. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95322. * @returns the transformed texture
  95323. */
  95324. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95325. return rootUrl;
  95326. };
  95327. /**
  95328. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95329. * @param rootUrl the url of the texture
  95330. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95331. * @returns the fallback texture
  95332. */
  95333. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95334. return null;
  95335. };
  95336. /**
  95337. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95338. * @param data contains the texture data
  95339. * @param texture defines the BabylonJS internal texture
  95340. * @param createPolynomials will be true if polynomials have been requested
  95341. * @param onLoad defines the callback to trigger once the texture is ready
  95342. * @param onError defines the callback to trigger in case of error
  95343. */
  95344. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  95345. if (Array.isArray(data)) {
  95346. return;
  95347. }
  95348. data = data;
  95349. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  95350. if (info) {
  95351. texture.width = info.width;
  95352. texture.height = info.width;
  95353. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  95354. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  95355. texture.isReady = true;
  95356. if (onLoad) {
  95357. onLoad();
  95358. }
  95359. });
  95360. }
  95361. else if (onError) {
  95362. onError("Can not parse the environment file", null);
  95363. }
  95364. };
  95365. /**
  95366. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95367. * @param data contains the texture data
  95368. * @param texture defines the BabylonJS internal texture
  95369. * @param callback defines the method to call once ready to upload
  95370. */
  95371. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  95372. throw ".env not supported in 2d.";
  95373. };
  95374. return ENVTextureLoader;
  95375. }());
  95376. // Register the loader.
  95377. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  95378. })(BABYLON || (BABYLON = {}));
  95379. //# sourceMappingURL=babylon.envTextureLoader.js.map
  95380. var BABYLON;
  95381. (function (BABYLON) {
  95382. /**
  95383. * Renders a layer on top of an existing scene
  95384. */
  95385. var UtilityLayerRenderer = /** @class */ (function () {
  95386. /**
  95387. * Instantiates a UtilityLayerRenderer
  95388. * @param originalScene the original scene that will be rendered on top of
  95389. */
  95390. function UtilityLayerRenderer(
  95391. /** the original scene that will be rendered on top of */
  95392. originalScene) {
  95393. var _this = this;
  95394. this.originalScene = originalScene;
  95395. this._pointerCaptures = {};
  95396. this._lastPointerEvents = {};
  95397. /**
  95398. * If the utility layer should automatically be rendered on top of existing scene
  95399. */
  95400. this.shouldRender = true;
  95401. /**
  95402. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  95403. */
  95404. this.onlyCheckPointerDownEvents = true;
  95405. /**
  95406. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  95407. */
  95408. this.processAllEvents = false;
  95409. /**
  95410. * Observable raised when the pointer move from the utility layer scene to the main scene
  95411. */
  95412. this.onPointerOutObservable = new BABYLON.Observable();
  95413. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  95414. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  95415. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  95416. this.utilityLayerScene._allowPostProcessClearColor = false;
  95417. originalScene.getEngine().scenes.pop();
  95418. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  95419. this.utilityLayerScene.detachControl();
  95420. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  95421. if (!_this.processAllEvents) {
  95422. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  95423. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  95424. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  95425. return;
  95426. }
  95427. }
  95428. var pointerEvent = (prePointerInfo.event);
  95429. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  95430. _this._pointerCaptures[pointerEvent.pointerId] = false;
  95431. return;
  95432. }
  95433. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  95434. if (!prePointerInfo.ray && utilityScenePick) {
  95435. prePointerInfo.ray = utilityScenePick.ray;
  95436. }
  95437. // always fire the prepointer oversvable
  95438. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  95439. // allow every non pointer down event to flow to the utility layer
  95440. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  95441. if (!prePointerInfo.skipOnPointerObservable) {
  95442. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  95443. }
  95444. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  95445. _this._pointerCaptures[pointerEvent.pointerId] = false;
  95446. }
  95447. return;
  95448. }
  95449. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  95450. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  95451. if (utilityScenePick && utilityScenePick.hit) {
  95452. if (!prePointerInfo.skipOnPointerObservable) {
  95453. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  95454. }
  95455. prePointerInfo.skipOnPointerObservable = true;
  95456. }
  95457. }
  95458. else {
  95459. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  95460. var pointerEvent_1 = (prePointerInfo.event);
  95461. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  95462. if (originalScenePick && utilityScenePick) {
  95463. // No pick in utility scene
  95464. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  95465. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  95466. // We touched an utility mesh present in the main scene
  95467. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  95468. prePointerInfo.skipOnPointerObservable = true;
  95469. }
  95470. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95471. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  95472. }
  95473. }
  95474. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  95475. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  95476. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  95477. // If a previous utility layer set this, do not unset this
  95478. if (!prePointerInfo.skipOnPointerObservable) {
  95479. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  95480. }
  95481. }
  95482. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  95483. // We have a pick in both scenes but main is closer than utility
  95484. // We touched an utility mesh present in the main scene
  95485. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  95486. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  95487. prePointerInfo.skipOnPointerObservable = true;
  95488. }
  95489. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  95490. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  95491. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  95492. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  95493. }
  95494. }
  95495. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  95496. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  95497. }
  95498. }
  95499. }
  95500. });
  95501. // Render directly on top of existing scene without clearing
  95502. this.utilityLayerScene.autoClear = false;
  95503. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  95504. if (_this.shouldRender) {
  95505. _this.render();
  95506. }
  95507. });
  95508. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  95509. _this.dispose();
  95510. });
  95511. this._updateCamera();
  95512. }
  95513. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  95514. /**
  95515. * 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)
  95516. */
  95517. get: function () {
  95518. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  95519. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  95520. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  95521. UtilityLayerRenderer._DefaultUtilityLayer = null;
  95522. });
  95523. }
  95524. return UtilityLayerRenderer._DefaultUtilityLayer;
  95525. },
  95526. enumerable: true,
  95527. configurable: true
  95528. });
  95529. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  95530. /**
  95531. * 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)
  95532. */
  95533. get: function () {
  95534. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  95535. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  95536. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  95537. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  95538. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  95539. });
  95540. }
  95541. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  95542. },
  95543. enumerable: true,
  95544. configurable: true
  95545. });
  95546. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  95547. if (!prePointerInfo.skipOnPointerObservable) {
  95548. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  95549. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  95550. }
  95551. };
  95552. /**
  95553. * Renders the utility layers scene on top of the original scene
  95554. */
  95555. UtilityLayerRenderer.prototype.render = function () {
  95556. this._updateCamera();
  95557. if (this.utilityLayerScene.activeCamera) {
  95558. // Set the camera's scene to utility layers scene
  95559. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  95560. var camera = this.utilityLayerScene.activeCamera;
  95561. camera._scene = this.utilityLayerScene;
  95562. if (camera.leftCamera) {
  95563. camera.leftCamera._scene = this.utilityLayerScene;
  95564. }
  95565. if (camera.rightCamera) {
  95566. camera.rightCamera._scene = this.utilityLayerScene;
  95567. }
  95568. this.utilityLayerScene.render(false);
  95569. // Reset camera's scene back to original
  95570. camera._scene = oldScene;
  95571. if (camera.leftCamera) {
  95572. camera.leftCamera._scene = oldScene;
  95573. }
  95574. if (camera.rightCamera) {
  95575. camera.rightCamera._scene = oldScene;
  95576. }
  95577. }
  95578. };
  95579. /**
  95580. * Disposes of the renderer
  95581. */
  95582. UtilityLayerRenderer.prototype.dispose = function () {
  95583. this.onPointerOutObservable.clear();
  95584. if (this._afterRenderObserver) {
  95585. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  95586. }
  95587. if (this._sceneDisposeObserver) {
  95588. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95589. }
  95590. if (this._originalPointerObserver) {
  95591. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  95592. }
  95593. this.utilityLayerScene.dispose();
  95594. };
  95595. UtilityLayerRenderer.prototype._updateCamera = function () {
  95596. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  95597. };
  95598. UtilityLayerRenderer._DefaultUtilityLayer = null;
  95599. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  95600. return UtilityLayerRenderer;
  95601. }());
  95602. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  95603. })(BABYLON || (BABYLON = {}));
  95604. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  95605. //# sourceMappingURL=babylon.behavior.js.map
  95606. var BABYLON;
  95607. (function (BABYLON) {
  95608. /**
  95609. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  95610. */
  95611. var PointerDragBehavior = /** @class */ (function () {
  95612. /**
  95613. * Creates a pointer drag behavior that can be attached to a mesh
  95614. * @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)
  95615. */
  95616. function PointerDragBehavior(options) {
  95617. /**
  95618. * 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)
  95619. */
  95620. this.maxDragAngle = 0;
  95621. /**
  95622. * @hidden
  95623. */
  95624. this._useAlternatePickedPointAboveMaxDragAngle = false;
  95625. /**
  95626. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  95627. */
  95628. this.currentDraggingPointerID = -1;
  95629. /**
  95630. * If the behavior is currently in a dragging state
  95631. */
  95632. this.dragging = false;
  95633. /**
  95634. * 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)
  95635. */
  95636. this.dragDeltaRatio = 0.2;
  95637. /**
  95638. * If the drag plane orientation should be updated during the dragging (Default: true)
  95639. */
  95640. this.updateDragPlane = true;
  95641. // Debug mode will display drag planes to help visualize behavior
  95642. this._debugMode = false;
  95643. this._moving = false;
  95644. /**
  95645. * Fires each time the attached mesh is dragged with the pointer
  95646. * * delta between last drag position and current drag position in world space
  95647. * * dragDistance along the drag axis
  95648. * * dragPlaneNormal normal of the current drag plane used during the drag
  95649. * * dragPlanePoint in world space where the drag intersects the drag plane
  95650. */
  95651. this.onDragObservable = new BABYLON.Observable();
  95652. /**
  95653. * Fires each time a drag begins (eg. mouse down on mesh)
  95654. */
  95655. this.onDragStartObservable = new BABYLON.Observable();
  95656. /**
  95657. * Fires each time a drag ends (eg. mouse release after drag)
  95658. */
  95659. this.onDragEndObservable = new BABYLON.Observable();
  95660. /**
  95661. * If the attached mesh should be moved when dragged
  95662. */
  95663. this.moveAttached = true;
  95664. /**
  95665. * If the drag behavior will react to drag events (Default: true)
  95666. */
  95667. this.enabled = true;
  95668. /**
  95669. * If camera controls should be detached during the drag
  95670. */
  95671. this.detachCameraControls = true;
  95672. /**
  95673. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  95674. */
  95675. this.useObjectOrienationForDragging = true;
  95676. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  95677. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  95678. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  95679. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  95680. this._attachedElement = null;
  95681. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  95682. this._lastPointerRay = {};
  95683. this._dragDelta = new BABYLON.Vector3();
  95684. // Variables to avoid instantiation in the below method
  95685. this._pointA = new BABYLON.Vector3(0, 0, 0);
  95686. this._pointB = new BABYLON.Vector3(0, 0, 0);
  95687. this._pointC = new BABYLON.Vector3(0, 0, 0);
  95688. this._lineA = new BABYLON.Vector3(0, 0, 0);
  95689. this._lineB = new BABYLON.Vector3(0, 0, 0);
  95690. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  95691. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  95692. this._options = options ? options : {};
  95693. var optionCount = 0;
  95694. if (this._options.dragAxis) {
  95695. optionCount++;
  95696. }
  95697. if (this._options.dragPlaneNormal) {
  95698. optionCount++;
  95699. }
  95700. if (optionCount > 1) {
  95701. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  95702. }
  95703. }
  95704. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  95705. /**
  95706. * The name of the behavior
  95707. */
  95708. get: function () {
  95709. return "PointerDrag";
  95710. },
  95711. enumerable: true,
  95712. configurable: true
  95713. });
  95714. /**
  95715. * Initializes the behavior
  95716. */
  95717. PointerDragBehavior.prototype.init = function () { };
  95718. /**
  95719. * Attaches the drag behavior the passed in mesh
  95720. * @param ownerNode The mesh that will be dragged around once attached
  95721. */
  95722. PointerDragBehavior.prototype.attach = function (ownerNode) {
  95723. var _this = this;
  95724. this._scene = ownerNode.getScene();
  95725. this._attachedNode = ownerNode;
  95726. // Initialize drag plane to not interfere with existing scene
  95727. if (!PointerDragBehavior._planeScene) {
  95728. if (this._debugMode) {
  95729. PointerDragBehavior._planeScene = this._scene;
  95730. }
  95731. else {
  95732. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  95733. PointerDragBehavior._planeScene.detachControl();
  95734. this._scene.getEngine().scenes.pop();
  95735. this._scene.onDisposeObservable.addOnce(function () {
  95736. PointerDragBehavior._planeScene.dispose();
  95737. PointerDragBehavior._planeScene = null;
  95738. });
  95739. }
  95740. }
  95741. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  95742. // State of the drag
  95743. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  95744. var pickPredicate = function (m) {
  95745. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  95746. };
  95747. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  95748. if (!_this.enabled) {
  95749. return;
  95750. }
  95751. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95752. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  95753. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  95754. }
  95755. }
  95756. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  95757. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  95758. _this.releaseDrag();
  95759. }
  95760. }
  95761. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95762. var pointerId = pointerInfo.event.pointerId;
  95763. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  95764. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  95765. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  95766. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  95767. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  95768. }
  95769. _this.currentDraggingPointerID = pointerId;
  95770. }
  95771. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  95772. if (!_this._lastPointerRay[pointerId]) {
  95773. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  95774. }
  95775. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  95776. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  95777. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  95778. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  95779. _this._moveDrag(pointerInfo.pickInfo.ray);
  95780. }
  95781. }
  95782. }
  95783. });
  95784. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  95785. if (_this._moving && _this.moveAttached) {
  95786. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  95787. // Slowly move mesh to avoid jitter
  95788. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  95789. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  95790. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  95791. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  95792. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  95793. }
  95794. });
  95795. };
  95796. /**
  95797. * Force relase the drag action by code.
  95798. */
  95799. PointerDragBehavior.prototype.releaseDrag = function () {
  95800. this.dragging = false;
  95801. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  95802. this.currentDraggingPointerID = -1;
  95803. this._moving = false;
  95804. // Reattach camera controls
  95805. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  95806. this._scene.activeCamera.attachControl(this._attachedElement, true);
  95807. }
  95808. };
  95809. /**
  95810. * Simulates the start of a pointer drag event on the behavior
  95811. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  95812. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  95813. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  95814. */
  95815. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  95816. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  95817. this._startDrag(pointerId, fromRay, startPickedPoint);
  95818. var lastRay = this._lastPointerRay[pointerId];
  95819. if (pointerId === PointerDragBehavior._AnyMouseID) {
  95820. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  95821. }
  95822. if (lastRay) {
  95823. // if there was a last pointer ray drag the object there
  95824. this._moveDrag(lastRay);
  95825. }
  95826. };
  95827. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  95828. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  95829. return;
  95830. }
  95831. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  95832. // Create start ray from the camera to the object
  95833. if (fromRay) {
  95834. this._startDragRay.direction.copyFrom(fromRay.direction);
  95835. this._startDragRay.origin.copyFrom(fromRay.origin);
  95836. }
  95837. else {
  95838. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  95839. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  95840. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  95841. }
  95842. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  95843. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  95844. if (pickedPoint) {
  95845. this.dragging = true;
  95846. this.currentDraggingPointerID = pointerId;
  95847. this.lastDragPosition.copyFrom(pickedPoint);
  95848. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  95849. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  95850. // Detatch camera controls
  95851. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  95852. if (this._scene.activeCamera.inputs.attachedElement) {
  95853. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  95854. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  95855. }
  95856. else {
  95857. this._attachedElement = null;
  95858. }
  95859. }
  95860. }
  95861. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  95862. };
  95863. PointerDragBehavior.prototype._moveDrag = function (ray) {
  95864. this._moving = true;
  95865. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  95866. if (pickedPoint) {
  95867. if (this.updateDragPlane) {
  95868. this._updateDragPlanePosition(ray, pickedPoint);
  95869. }
  95870. var dragLength = 0;
  95871. // depending on the drag mode option drag accordingly
  95872. if (this._options.dragAxis) {
  95873. // Convert local drag axis to world
  95874. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  95875. // Project delta drag from the drag plane onto the drag axis
  95876. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  95877. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  95878. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  95879. }
  95880. else {
  95881. dragLength = this._dragDelta.length();
  95882. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  95883. }
  95884. this._targetPosition.addInPlace(this._dragDelta);
  95885. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  95886. this.lastDragPosition.copyFrom(pickedPoint);
  95887. }
  95888. };
  95889. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  95890. var _this = this;
  95891. if (!ray) {
  95892. return null;
  95893. }
  95894. // Calculate angle between plane normal and ray
  95895. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  95896. // Correct if ray is casted from oposite side
  95897. if (angle > Math.PI / 2) {
  95898. angle = Math.PI - angle;
  95899. }
  95900. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  95901. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  95902. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  95903. // Invert ray direction along the towards object axis
  95904. this._tmpVector.copyFrom(ray.direction);
  95905. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  95906. this._alternatePickedPoint.normalize();
  95907. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  95908. this._tmpVector.addInPlace(this._alternatePickedPoint);
  95909. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  95910. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  95911. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  95912. this._alternatePickedPoint.addInPlace(this._tmpVector);
  95913. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  95914. return this._alternatePickedPoint;
  95915. }
  95916. else {
  95917. return null;
  95918. }
  95919. }
  95920. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  95921. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  95922. return pickResult.pickedPoint;
  95923. }
  95924. else {
  95925. return null;
  95926. }
  95927. };
  95928. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  95929. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  95930. this._pointA.copyFrom(dragPlanePosition);
  95931. if (this._options.dragAxis) {
  95932. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  95933. // Calculate plane normal in direction of camera but perpendicular to drag axis
  95934. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  95935. ray.origin.subtractToRef(this._pointA, this._pointC);
  95936. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  95937. // Get perpendicular line from direction to camera and drag axis
  95938. this._pointB.subtractToRef(this._pointA, this._lineA);
  95939. this._pointC.subtractToRef(this._pointA, this._lineB);
  95940. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  95941. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  95942. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  95943. this._lookAt.normalize();
  95944. this._dragPlane.position.copyFrom(this._pointA);
  95945. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  95946. this._dragPlane.lookAt(this._lookAt);
  95947. }
  95948. else if (this._options.dragPlaneNormal) {
  95949. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  95950. this._dragPlane.position.copyFrom(this._pointA);
  95951. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  95952. this._dragPlane.lookAt(this._lookAt);
  95953. }
  95954. else {
  95955. this._dragPlane.position.copyFrom(this._pointA);
  95956. this._dragPlane.lookAt(ray.origin);
  95957. }
  95958. this._dragPlane.computeWorldMatrix(true);
  95959. };
  95960. /**
  95961. * Detaches the behavior from the mesh
  95962. */
  95963. PointerDragBehavior.prototype.detach = function () {
  95964. if (this._pointerObserver) {
  95965. this._scene.onPointerObservable.remove(this._pointerObserver);
  95966. }
  95967. if (this._beforeRenderObserver) {
  95968. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  95969. }
  95970. };
  95971. PointerDragBehavior._AnyMouseID = -2;
  95972. return PointerDragBehavior;
  95973. }());
  95974. BABYLON.PointerDragBehavior = PointerDragBehavior;
  95975. })(BABYLON || (BABYLON = {}));
  95976. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  95977. var BABYLON;
  95978. (function (BABYLON) {
  95979. /**
  95980. * A behavior that when attached to a mesh will allow the mesh to be scaled
  95981. */
  95982. var MultiPointerScaleBehavior = /** @class */ (function () {
  95983. /**
  95984. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  95985. */
  95986. function MultiPointerScaleBehavior() {
  95987. this._startDistance = 0;
  95988. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  95989. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  95990. this._sceneRenderObserver = null;
  95991. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  95992. this._dragBehaviorA.moveAttached = false;
  95993. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  95994. this._dragBehaviorB.moveAttached = false;
  95995. }
  95996. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  95997. /**
  95998. * The name of the behavior
  95999. */
  96000. get: function () {
  96001. return "MultiPointerScale";
  96002. },
  96003. enumerable: true,
  96004. configurable: true
  96005. });
  96006. /**
  96007. * Initializes the behavior
  96008. */
  96009. MultiPointerScaleBehavior.prototype.init = function () { };
  96010. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  96011. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  96012. };
  96013. /**
  96014. * Attaches the scale behavior the passed in mesh
  96015. * @param ownerNode The mesh that will be scaled around once attached
  96016. */
  96017. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  96018. var _this = this;
  96019. this._ownerNode = ownerNode;
  96020. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  96021. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  96022. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96023. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  96024. _this._dragBehaviorA.releaseDrag();
  96025. }
  96026. else {
  96027. _this._initialScale.copyFrom(ownerNode.scaling);
  96028. _this._startDistance = _this._getCurrentDistance();
  96029. }
  96030. }
  96031. });
  96032. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  96033. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96034. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  96035. _this._dragBehaviorB.releaseDrag();
  96036. }
  96037. else {
  96038. _this._initialScale.copyFrom(ownerNode.scaling);
  96039. _this._startDistance = _this._getCurrentDistance();
  96040. }
  96041. }
  96042. });
  96043. // Once both drag behaviors are active scale based on the distance between the two pointers
  96044. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  96045. behavior.onDragObservable.add(function () {
  96046. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96047. var ratio = _this._getCurrentDistance() / _this._startDistance;
  96048. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  96049. }
  96050. });
  96051. });
  96052. ownerNode.addBehavior(this._dragBehaviorA);
  96053. ownerNode.addBehavior(this._dragBehaviorB);
  96054. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  96055. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  96056. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96057. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  96058. if (change.length() > 0.01) {
  96059. ownerNode.scaling.addInPlace(change);
  96060. }
  96061. }
  96062. });
  96063. };
  96064. /**
  96065. * Detaches the behavior from the mesh
  96066. */
  96067. MultiPointerScaleBehavior.prototype.detach = function () {
  96068. var _this = this;
  96069. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  96070. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  96071. behavior.onDragStartObservable.clear();
  96072. behavior.onDragObservable.clear();
  96073. _this._ownerNode.removeBehavior(behavior);
  96074. });
  96075. };
  96076. return MultiPointerScaleBehavior;
  96077. }());
  96078. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  96079. })(BABYLON || (BABYLON = {}));
  96080. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  96081. var BABYLON;
  96082. (function (BABYLON) {
  96083. /**
  96084. * 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
  96085. */
  96086. var SixDofDragBehavior = /** @class */ (function () {
  96087. /**
  96088. * Instantiates a behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  96089. */
  96090. function SixDofDragBehavior() {
  96091. this._sceneRenderObserver = null;
  96092. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  96093. this._moving = false;
  96094. this._startingOrientation = new BABYLON.Quaternion();
  96095. /**
  96096. * 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)
  96097. */
  96098. this.zDragFactor = 3;
  96099. /**
  96100. * If the behavior is currently in a dragging state
  96101. */
  96102. this.dragging = false;
  96103. /**
  96104. * 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)
  96105. */
  96106. this.dragDeltaRatio = 0.2;
  96107. /**
  96108. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  96109. */
  96110. this.currentDraggingPointerID = -1;
  96111. /**
  96112. * If camera controls should be detached during the drag
  96113. */
  96114. this.detachCameraControls = true;
  96115. /**
  96116. * Fires each time a drag starts
  96117. */
  96118. this.onDragStartObservable = new BABYLON.Observable();
  96119. /**
  96120. * Fires each time a drag ends (eg. mouse release after drag)
  96121. */
  96122. this.onDragEndObservable = new BABYLON.Observable();
  96123. }
  96124. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  96125. /**
  96126. * The name of the behavior
  96127. */
  96128. get: function () {
  96129. return "SixDofDrag";
  96130. },
  96131. enumerable: true,
  96132. configurable: true
  96133. });
  96134. /**
  96135. * Initializes the behavior
  96136. */
  96137. SixDofDragBehavior.prototype.init = function () { };
  96138. /**
  96139. * Attaches the scale behavior the passed in mesh
  96140. * @param ownerNode The mesh that will be scaled around once attached
  96141. */
  96142. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  96143. var _this = this;
  96144. this._ownerNode = ownerNode;
  96145. this._scene = this._ownerNode.getScene();
  96146. if (!SixDofDragBehavior._virtualScene) {
  96147. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  96148. this._scene.getEngine().scenes.pop();
  96149. }
  96150. var pickedMesh = null;
  96151. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  96152. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  96153. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  96154. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  96155. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  96156. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  96157. var pickPredicate = function (m) {
  96158. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  96159. };
  96160. var attachedElement = null;
  96161. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  96162. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  96163. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  96164. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  96165. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  96166. }
  96167. pickedMesh = _this._ownerNode;
  96168. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  96169. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  96170. // Set position and orientation of the controller
  96171. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  96172. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  96173. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  96174. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96175. pickedMesh.computeWorldMatrix();
  96176. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  96177. if (!pickedMesh.rotationQuaternion) {
  96178. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  96179. }
  96180. var oldParent = pickedMesh.parent;
  96181. pickedMesh.setParent(null);
  96182. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  96183. pickedMesh.setParent(oldParent);
  96184. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  96185. // Update state
  96186. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  96187. _this.dragging = true;
  96188. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  96189. // Detatch camera controls
  96190. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  96191. if (_this._scene.activeCamera.inputs.attachedElement) {
  96192. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  96193. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  96194. }
  96195. else {
  96196. attachedElement = null;
  96197. }
  96198. }
  96199. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  96200. _this.onDragStartObservable.notifyObservers({});
  96201. }
  96202. }
  96203. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  96204. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  96205. _this.dragging = false;
  96206. _this._moving = false;
  96207. _this.currentDraggingPointerID = -1;
  96208. pickedMesh = null;
  96209. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96210. // Reattach camera controls
  96211. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  96212. _this._scene.activeCamera.attachControl(attachedElement, true);
  96213. }
  96214. _this.onDragEndObservable.notifyObservers({});
  96215. }
  96216. }
  96217. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  96218. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  96219. var zDragFactor = _this.zDragFactor;
  96220. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  96221. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  96222. zDragFactor = 0;
  96223. }
  96224. // Calculate controller drag distance in controller space
  96225. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  96226. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  96227. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  96228. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  96229. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  96230. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  96231. if (_this._virtualDragMesh.position.z < 0) {
  96232. _this._virtualDragMesh.position.z = 0;
  96233. }
  96234. // Update the controller position
  96235. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  96236. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  96237. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96238. // Move the virtualObjectsPosition into the picked mesh's space if needed
  96239. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  96240. if (pickedMesh.parent) {
  96241. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  96242. }
  96243. if (!_this._moving) {
  96244. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  96245. }
  96246. _this._moving = true;
  96247. }
  96248. }
  96249. });
  96250. var tmpQuaternion = new BABYLON.Quaternion();
  96251. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  96252. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  96253. if (_this.dragging && _this._moving && pickedMesh) {
  96254. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  96255. // Slowly move mesh to avoid jitter
  96256. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  96257. // Get change in rotation
  96258. tmpQuaternion.copyFrom(_this._startingOrientation);
  96259. tmpQuaternion.x = -tmpQuaternion.x;
  96260. tmpQuaternion.y = -tmpQuaternion.y;
  96261. tmpQuaternion.z = -tmpQuaternion.z;
  96262. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  96263. // Convert change in rotation to only y axis rotation
  96264. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  96265. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  96266. // Slowly move mesh to avoid jitter
  96267. var oldParent = pickedMesh.parent;
  96268. pickedMesh.setParent(null);
  96269. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  96270. pickedMesh.setParent(oldParent);
  96271. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  96272. }
  96273. });
  96274. };
  96275. /**
  96276. * Detaches the behavior from the mesh
  96277. */
  96278. SixDofDragBehavior.prototype.detach = function () {
  96279. if (this._scene) {
  96280. this._scene.onPointerObservable.remove(this._pointerObserver);
  96281. }
  96282. if (this._ownerNode) {
  96283. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  96284. }
  96285. if (this._virtualOriginMesh) {
  96286. this._virtualOriginMesh.dispose();
  96287. }
  96288. if (this._virtualDragMesh) {
  96289. this._virtualDragMesh.dispose();
  96290. }
  96291. this.onDragEndObservable.clear();
  96292. this.onDragStartObservable.clear();
  96293. };
  96294. return SixDofDragBehavior;
  96295. }());
  96296. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  96297. })(BABYLON || (BABYLON = {}));
  96298. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  96299. var BABYLON;
  96300. (function (BABYLON) {
  96301. /**
  96302. * @hidden
  96303. */
  96304. var FaceDirectionInfo = /** @class */ (function () {
  96305. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  96306. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  96307. if (diff === void 0) { diff = 0; }
  96308. if (ignore === void 0) { ignore = false; }
  96309. this.direction = direction;
  96310. this.rotatedDirection = rotatedDirection;
  96311. this.diff = diff;
  96312. this.ignore = ignore;
  96313. }
  96314. return FaceDirectionInfo;
  96315. }());
  96316. /**
  96317. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  96318. */
  96319. var AttachToBoxBehavior = /** @class */ (function () {
  96320. /**
  96321. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  96322. * @param ui The transform node that should be attched to the mesh
  96323. */
  96324. function AttachToBoxBehavior(ui) {
  96325. this.ui = ui;
  96326. /**
  96327. * The name of the behavior
  96328. */
  96329. this.name = "AttachToBoxBehavior";
  96330. /**
  96331. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  96332. */
  96333. this.distanceAwayFromFace = 0.15;
  96334. /**
  96335. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  96336. */
  96337. this.distanceAwayFromBottomOfFace = 0.15;
  96338. 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))];
  96339. this._tmpMatrix = new BABYLON.Matrix();
  96340. this._tmpVector = new BABYLON.Vector3();
  96341. this._zeroVector = BABYLON.Vector3.Zero();
  96342. this._lookAtTmpMatrix = new BABYLON.Matrix();
  96343. /* Does nothing */
  96344. }
  96345. /**
  96346. * Initializes the behavior
  96347. */
  96348. AttachToBoxBehavior.prototype.init = function () {
  96349. /* Does nothing */
  96350. };
  96351. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  96352. var _this = this;
  96353. // Go over each face and calculate the angle between the face's normal and targetDirection
  96354. this._faceVectors.forEach(function (v) {
  96355. if (!_this._target.rotationQuaternion) {
  96356. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  96357. }
  96358. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  96359. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  96360. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  96361. });
  96362. // Return the face information of the one with the normal closeset to target direction
  96363. return this._faceVectors.reduce(function (min, p) {
  96364. if (min.ignore) {
  96365. return p;
  96366. }
  96367. else if (p.ignore) {
  96368. return min;
  96369. }
  96370. else {
  96371. return min.diff < p.diff ? min : p;
  96372. }
  96373. }, this._faceVectors[0]);
  96374. };
  96375. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  96376. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  96377. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  96378. this._lookAtTmpMatrix.invert();
  96379. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  96380. };
  96381. /**
  96382. * Attaches the AttachToBoxBehavior to the passed in mesh
  96383. * @param target The mesh that the specified node will be attached to
  96384. */
  96385. AttachToBoxBehavior.prototype.attach = function (target) {
  96386. var _this = this;
  96387. this._target = target;
  96388. this._scene = this._target.getScene();
  96389. // Every frame, update the app bars position
  96390. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  96391. if (!_this._scene.activeCamera) {
  96392. return;
  96393. }
  96394. // Find the face closest to the cameras position
  96395. var cameraPos = _this._scene.activeCamera.position;
  96396. if (_this._scene.activeCamera.devicePosition) {
  96397. cameraPos = _this._scene.activeCamera.devicePosition;
  96398. }
  96399. var facing = _this._closestFace(cameraPos.subtract(target.position));
  96400. if (_this._scene.activeCamera.leftCamera) {
  96401. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  96402. }
  96403. else {
  96404. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  96405. }
  96406. // Get camera up direction
  96407. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  96408. // Ignore faces to not select a parrelel face for the up vector of the UI
  96409. _this._faceVectors.forEach(function (v) {
  96410. if (facing.direction.x && v.direction.x) {
  96411. v.ignore = true;
  96412. }
  96413. if (facing.direction.y && v.direction.y) {
  96414. v.ignore = true;
  96415. }
  96416. if (facing.direction.z && v.direction.z) {
  96417. v.ignore = true;
  96418. }
  96419. });
  96420. var facingUp = _this._closestFace(_this._tmpVector);
  96421. // Unignore faces
  96422. _this._faceVectors.forEach(function (v) {
  96423. v.ignore = false;
  96424. });
  96425. // Position the app bar on that face
  96426. _this.ui.position.copyFrom(target.position);
  96427. if (facing.direction.x) {
  96428. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96429. _this.ui.position.addInPlace(_this._tmpVector);
  96430. }
  96431. if (facing.direction.y) {
  96432. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96433. _this.ui.position.addInPlace(_this._tmpVector);
  96434. }
  96435. if (facing.direction.z) {
  96436. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96437. _this.ui.position.addInPlace(_this._tmpVector);
  96438. }
  96439. // Rotate to be oriented properly to the camera
  96440. if (!_this.ui.rotationQuaternion) {
  96441. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  96442. }
  96443. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  96444. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  96445. // Place ui the correct distance from the bottom of the mesh
  96446. if (facingUp.direction.x) {
  96447. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  96448. }
  96449. if (facingUp.direction.y) {
  96450. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  96451. }
  96452. if (facingUp.direction.z) {
  96453. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  96454. }
  96455. _this.ui.position.addInPlace(_this._tmpVector);
  96456. });
  96457. };
  96458. /**
  96459. * Detaches the behavior from the mesh
  96460. */
  96461. AttachToBoxBehavior.prototype.detach = function () {
  96462. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  96463. };
  96464. return AttachToBoxBehavior;
  96465. }());
  96466. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  96467. })(BABYLON || (BABYLON = {}));
  96468. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  96469. var BABYLON;
  96470. (function (BABYLON) {
  96471. /**
  96472. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  96473. */
  96474. var FadeInOutBehavior = /** @class */ (function () {
  96475. /**
  96476. * Instatiates the FadeInOutBehavior
  96477. */
  96478. function FadeInOutBehavior() {
  96479. var _this = this;
  96480. /**
  96481. * Time in milliseconds to delay before fading in (Default: 0)
  96482. */
  96483. this.delay = 0;
  96484. /**
  96485. * Time in milliseconds for the mesh to fade in (Default: 300)
  96486. */
  96487. this.fadeInTime = 300;
  96488. this._millisecondsPerFrame = 1000 / 60;
  96489. this._hovered = false;
  96490. this._hoverValue = 0;
  96491. this._ownerNode = null;
  96492. this._update = function () {
  96493. if (_this._ownerNode) {
  96494. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  96495. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  96496. if (_this._ownerNode.visibility > 1) {
  96497. _this._setAllVisibility(_this._ownerNode, 1);
  96498. _this._hoverValue = _this.fadeInTime + _this.delay;
  96499. return;
  96500. }
  96501. else if (_this._ownerNode.visibility < 0) {
  96502. _this._setAllVisibility(_this._ownerNode, 0);
  96503. if (_this._hoverValue < 0) {
  96504. _this._hoverValue = 0;
  96505. return;
  96506. }
  96507. }
  96508. setTimeout(_this._update, _this._millisecondsPerFrame);
  96509. }
  96510. };
  96511. }
  96512. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  96513. /**
  96514. * The name of the behavior
  96515. */
  96516. get: function () {
  96517. return "FadeInOut";
  96518. },
  96519. enumerable: true,
  96520. configurable: true
  96521. });
  96522. /**
  96523. * Initializes the behavior
  96524. */
  96525. FadeInOutBehavior.prototype.init = function () {
  96526. };
  96527. /**
  96528. * Attaches the fade behavior on the passed in mesh
  96529. * @param ownerNode The mesh that will be faded in/out once attached
  96530. */
  96531. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  96532. this._ownerNode = ownerNode;
  96533. this._setAllVisibility(this._ownerNode, 0);
  96534. };
  96535. /**
  96536. * Detaches the behavior from the mesh
  96537. */
  96538. FadeInOutBehavior.prototype.detach = function () {
  96539. this._ownerNode = null;
  96540. };
  96541. /**
  96542. * Triggers the mesh to begin fading in or out
  96543. * @param value if the object should fade in or out (true to fade in)
  96544. */
  96545. FadeInOutBehavior.prototype.fadeIn = function (value) {
  96546. this._hovered = value;
  96547. this._update();
  96548. };
  96549. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  96550. var _this = this;
  96551. mesh.visibility = value;
  96552. mesh.getChildMeshes().forEach(function (c) {
  96553. _this._setAllVisibility(c, value);
  96554. });
  96555. };
  96556. return FadeInOutBehavior;
  96557. }());
  96558. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  96559. })(BABYLON || (BABYLON = {}));
  96560. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  96561. var BABYLON;
  96562. (function (BABYLON) {
  96563. /**
  96564. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  96565. */
  96566. var Gizmo = /** @class */ (function () {
  96567. /**
  96568. * Creates a gizmo
  96569. * @param gizmoLayer The utility layer the gizmo will be added to
  96570. */
  96571. function Gizmo(
  96572. /** The utility layer the gizmo will be added to */
  96573. gizmoLayer) {
  96574. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96575. var _this = this;
  96576. this.gizmoLayer = gizmoLayer;
  96577. /**
  96578. * Ratio for the scale of the gizmo (Default: 1)
  96579. */
  96580. this.scaleRatio = 1;
  96581. this._tmpMatrix = new BABYLON.Matrix();
  96582. /**
  96583. * If a custom mesh has been set (Default: false)
  96584. */
  96585. this._customMeshSet = false;
  96586. /**
  96587. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  96588. */
  96589. this.updateGizmoRotationToMatchAttachedMesh = true;
  96590. /**
  96591. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  96592. */
  96593. this.updateGizmoPositionToMatchAttachedMesh = true;
  96594. /**
  96595. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  96596. */
  96597. this._updateScale = true;
  96598. this._interactionsEnabled = true;
  96599. this._tempVector = new BABYLON.Vector3();
  96600. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  96601. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  96602. _this._update();
  96603. });
  96604. this.attachedMesh = null;
  96605. }
  96606. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  96607. /**
  96608. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  96609. * * When set, interactions will be enabled
  96610. */
  96611. get: function () {
  96612. return this._attachedMesh;
  96613. },
  96614. set: function (value) {
  96615. this._attachedMesh = value;
  96616. this._rootMesh.setEnabled(value ? true : false);
  96617. this._attachedMeshChanged(value);
  96618. },
  96619. enumerable: true,
  96620. configurable: true
  96621. });
  96622. /**
  96623. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  96624. * @param mesh The mesh to replace the default mesh of the gizmo
  96625. */
  96626. Gizmo.prototype.setCustomMesh = function (mesh) {
  96627. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  96628. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  96629. }
  96630. this._rootMesh.getChildMeshes().forEach(function (c) {
  96631. c.dispose();
  96632. });
  96633. mesh.parent = this._rootMesh;
  96634. this._customMeshSet = true;
  96635. };
  96636. Gizmo.prototype._attachedMeshChanged = function (value) {
  96637. };
  96638. /**
  96639. * @hidden
  96640. * Updates the gizmo to match the attached mesh's position/rotation
  96641. */
  96642. Gizmo.prototype._update = function () {
  96643. if (this.attachedMesh) {
  96644. if (this.updateGizmoRotationToMatchAttachedMesh) {
  96645. if (!this._rootMesh.rotationQuaternion) {
  96646. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  96647. }
  96648. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  96649. this._tempVector.copyFrom(this.attachedMesh.scaling);
  96650. if (this.attachedMesh.scaling.x < 0) {
  96651. this.attachedMesh.scaling.x *= -1;
  96652. }
  96653. if (this.attachedMesh.scaling.y < 0) {
  96654. this.attachedMesh.scaling.y *= -1;
  96655. }
  96656. if (this.attachedMesh.scaling.z < 0) {
  96657. this.attachedMesh.scaling.z *= -1;
  96658. }
  96659. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  96660. this.attachedMesh.scaling.copyFrom(this._tempVector);
  96661. this.attachedMesh.computeWorldMatrix();
  96662. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  96663. }
  96664. else if (this._rootMesh.rotationQuaternion) {
  96665. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  96666. }
  96667. if (this.updateGizmoPositionToMatchAttachedMesh) {
  96668. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  96669. }
  96670. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  96671. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  96672. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  96673. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  96674. }
  96675. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  96676. var dist = this._tempVector.length() * this.scaleRatio;
  96677. this._rootMesh.scaling.set(dist, dist, dist);
  96678. }
  96679. }
  96680. };
  96681. /**
  96682. * Disposes of the gizmo
  96683. */
  96684. Gizmo.prototype.dispose = function () {
  96685. this._rootMesh.dispose();
  96686. if (this._beforeRenderObserver) {
  96687. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  96688. }
  96689. };
  96690. return Gizmo;
  96691. }());
  96692. BABYLON.Gizmo = Gizmo;
  96693. })(BABYLON || (BABYLON = {}));
  96694. //# sourceMappingURL=babylon.gizmo.js.map
  96695. var BABYLON;
  96696. (function (BABYLON) {
  96697. /**
  96698. * Single axis drag gizmo
  96699. */
  96700. var AxisDragGizmo = /** @class */ (function (_super) {
  96701. __extends(AxisDragGizmo, _super);
  96702. /**
  96703. * Creates an AxisDragGizmo
  96704. * @param gizmoLayer The utility layer the gizmo will be added to
  96705. * @param dragAxis The axis which the gizmo will be able to drag on
  96706. * @param color The color of the gizmo
  96707. */
  96708. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  96709. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96710. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96711. var _this = _super.call(this, gizmoLayer) || this;
  96712. _this._pointerObserver = null;
  96713. /**
  96714. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96715. */
  96716. _this.snapDistance = 0;
  96717. /**
  96718. * Event that fires each time the gizmo snaps to a new location.
  96719. * * snapDistance is the the change in distance
  96720. */
  96721. _this.onSnapObservable = new BABYLON.Observable();
  96722. // Create Material
  96723. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96724. coloredMaterial.disableLighting = true;
  96725. coloredMaterial.emissiveColor = color;
  96726. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96727. hoverMaterial.disableLighting = true;
  96728. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96729. // Build mesh on root node
  96730. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96731. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  96732. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  96733. arrowTail.color = coloredMaterial.emissiveColor;
  96734. arrow.addChild(arrowMesh);
  96735. arrow.addChild(arrowTail);
  96736. // Position arrow pointing in its drag axis
  96737. arrowMesh.scaling.scaleInPlace(0.05);
  96738. arrowMesh.material = coloredMaterial;
  96739. arrowMesh.rotation.x = Math.PI / 2;
  96740. arrowMesh.position.z += 0.3;
  96741. arrowTail.scaling.scaleInPlace(0.26);
  96742. arrowTail.rotation.x = Math.PI / 2;
  96743. arrowTail.material = coloredMaterial;
  96744. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  96745. arrow.scaling.scaleInPlace(1 / 3);
  96746. _this._rootMesh.addChild(arrow);
  96747. var currentSnapDragDistance = 0;
  96748. var tmpVector = new BABYLON.Vector3();
  96749. var tmpSnapEvent = { snapDistance: 0 };
  96750. // Add drag behavior to handle events when the gizmo is dragged
  96751. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96752. _this.dragBehavior.moveAttached = false;
  96753. _this._rootMesh.addBehavior(_this.dragBehavior);
  96754. var localDelta = new BABYLON.Vector3();
  96755. var tmpMatrix = new BABYLON.Matrix();
  96756. _this.dragBehavior.onDragObservable.add(function (event) {
  96757. if (_this.attachedMesh) {
  96758. // Convert delta to local translation if it has a parent
  96759. if (_this.attachedMesh.parent) {
  96760. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  96761. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  96762. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  96763. }
  96764. else {
  96765. localDelta.copyFrom(event.delta);
  96766. }
  96767. // Snapping logic
  96768. if (_this.snapDistance == 0) {
  96769. _this.attachedMesh.position.addInPlace(localDelta);
  96770. }
  96771. else {
  96772. currentSnapDragDistance += event.dragDistance;
  96773. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96774. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  96775. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96776. localDelta.normalizeToRef(tmpVector);
  96777. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  96778. _this.attachedMesh.position.addInPlace(tmpVector);
  96779. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  96780. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96781. }
  96782. }
  96783. }
  96784. });
  96785. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96786. if (_this._customMeshSet) {
  96787. return;
  96788. }
  96789. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96790. var material = isHovered ? hoverMaterial : coloredMaterial;
  96791. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96792. m.material = material;
  96793. if (m.color) {
  96794. m.color = material.emissiveColor;
  96795. }
  96796. });
  96797. });
  96798. return _this;
  96799. }
  96800. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  96801. if (this.dragBehavior) {
  96802. this.dragBehavior.enabled = value ? true : false;
  96803. }
  96804. };
  96805. /**
  96806. * Disposes of the gizmo
  96807. */
  96808. AxisDragGizmo.prototype.dispose = function () {
  96809. this.onSnapObservable.clear();
  96810. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96811. this.dragBehavior.detach();
  96812. _super.prototype.dispose.call(this);
  96813. };
  96814. return AxisDragGizmo;
  96815. }(BABYLON.Gizmo));
  96816. BABYLON.AxisDragGizmo = AxisDragGizmo;
  96817. })(BABYLON || (BABYLON = {}));
  96818. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  96819. var BABYLON;
  96820. (function (BABYLON) {
  96821. /**
  96822. * Single axis scale gizmo
  96823. */
  96824. var AxisScaleGizmo = /** @class */ (function (_super) {
  96825. __extends(AxisScaleGizmo, _super);
  96826. /**
  96827. * Creates an AxisScaleGizmo
  96828. * @param gizmoLayer The utility layer the gizmo will be added to
  96829. * @param dragAxis The axis which the gizmo will be able to scale on
  96830. * @param color The color of the gizmo
  96831. */
  96832. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  96833. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96834. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96835. var _this = _super.call(this, gizmoLayer) || this;
  96836. _this._pointerObserver = null;
  96837. /**
  96838. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96839. */
  96840. _this.snapDistance = 0;
  96841. /**
  96842. * Event that fires each time the gizmo snaps to a new location.
  96843. * * snapDistance is the the change in distance
  96844. */
  96845. _this.onSnapObservable = new BABYLON.Observable();
  96846. /**
  96847. * If the scaling operation should be done on all axis (default: false)
  96848. */
  96849. _this.uniformScaling = false;
  96850. // Create Material
  96851. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96852. _this._coloredMaterial.disableLighting = true;
  96853. _this._coloredMaterial.emissiveColor = color;
  96854. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96855. hoverMaterial.disableLighting = true;
  96856. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96857. // Build mesh on root node
  96858. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96859. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  96860. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  96861. arrowTail.color = _this._coloredMaterial.emissiveColor;
  96862. arrow.addChild(arrowMesh);
  96863. arrow.addChild(arrowTail);
  96864. // Position arrow pointing in its drag axis
  96865. arrowMesh.scaling.scaleInPlace(0.1);
  96866. arrowMesh.material = _this._coloredMaterial;
  96867. arrowMesh.rotation.x = Math.PI / 2;
  96868. arrowMesh.position.z += 0.3;
  96869. arrowTail.scaling.scaleInPlace(0.26);
  96870. arrowTail.rotation.x = Math.PI / 2;
  96871. arrowTail.material = _this._coloredMaterial;
  96872. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  96873. _this._rootMesh.addChild(arrow);
  96874. arrow.scaling.scaleInPlace(1 / 3);
  96875. // Add drag behavior to handle events when the gizmo is dragged
  96876. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96877. _this.dragBehavior.moveAttached = false;
  96878. _this._rootMesh.addBehavior(_this.dragBehavior);
  96879. var currentSnapDragDistance = 0;
  96880. var tmpVector = new BABYLON.Vector3();
  96881. var tmpSnapEvent = { snapDistance: 0 };
  96882. _this.dragBehavior.onDragObservable.add(function (event) {
  96883. if (_this.attachedMesh) {
  96884. // Snapping logic
  96885. var snapped = false;
  96886. var dragSteps = 0;
  96887. if (_this.uniformScaling) {
  96888. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  96889. if (tmpVector.y < 0) {
  96890. tmpVector.scaleInPlace(-1);
  96891. }
  96892. }
  96893. else {
  96894. tmpVector.copyFrom(dragAxis);
  96895. }
  96896. if (_this.snapDistance == 0) {
  96897. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  96898. }
  96899. else {
  96900. currentSnapDragDistance += event.dragDistance;
  96901. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96902. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  96903. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96904. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  96905. snapped = true;
  96906. }
  96907. else {
  96908. tmpVector.scaleInPlace(0);
  96909. }
  96910. }
  96911. _this.attachedMesh.scaling.addInPlace(tmpVector);
  96912. if (snapped) {
  96913. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  96914. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96915. }
  96916. }
  96917. });
  96918. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96919. if (_this._customMeshSet) {
  96920. return;
  96921. }
  96922. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96923. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  96924. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96925. m.material = material;
  96926. if (m.color) {
  96927. m.color = material.emissiveColor;
  96928. }
  96929. });
  96930. });
  96931. return _this;
  96932. }
  96933. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  96934. if (this.dragBehavior) {
  96935. this.dragBehavior.enabled = value ? true : false;
  96936. }
  96937. };
  96938. /**
  96939. * Disposes of the gizmo
  96940. */
  96941. AxisScaleGizmo.prototype.dispose = function () {
  96942. this.onSnapObservable.clear();
  96943. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96944. this.dragBehavior.detach();
  96945. _super.prototype.dispose.call(this);
  96946. };
  96947. /**
  96948. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  96949. * @param mesh The mesh to replace the default mesh of the gizmo
  96950. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  96951. */
  96952. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  96953. var _this = this;
  96954. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  96955. _super.prototype.setCustomMesh.call(this, mesh);
  96956. if (useGizmoMaterial) {
  96957. this._rootMesh.getChildMeshes().forEach(function (m) {
  96958. m.material = _this._coloredMaterial;
  96959. if (m.color) {
  96960. m.color = _this._coloredMaterial.emissiveColor;
  96961. }
  96962. });
  96963. this._customMeshSet = false;
  96964. }
  96965. };
  96966. return AxisScaleGizmo;
  96967. }(BABYLON.Gizmo));
  96968. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  96969. })(BABYLON || (BABYLON = {}));
  96970. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  96971. var BABYLON;
  96972. (function (BABYLON) {
  96973. /**
  96974. * Single plane rotation gizmo
  96975. */
  96976. var PlaneRotationGizmo = /** @class */ (function (_super) {
  96977. __extends(PlaneRotationGizmo, _super);
  96978. /**
  96979. * Creates a PlaneRotationGizmo
  96980. * @param gizmoLayer The utility layer the gizmo will be added to
  96981. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  96982. * @param color The color of the gizmo
  96983. */
  96984. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  96985. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96986. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96987. var _this = _super.call(this, gizmoLayer) || this;
  96988. _this._pointerObserver = null;
  96989. /**
  96990. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  96991. */
  96992. _this.snapDistance = 0;
  96993. /**
  96994. * Event that fires each time the gizmo snaps to a new location.
  96995. * * snapDistance is the the change in distance
  96996. */
  96997. _this.onSnapObservable = new BABYLON.Observable();
  96998. // Create Material
  96999. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97000. coloredMaterial.disableLighting = true;
  97001. coloredMaterial.emissiveColor = color;
  97002. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97003. hoverMaterial.disableLighting = true;
  97004. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97005. // Build mesh on root node
  97006. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97007. // Create circle out of lines
  97008. var tessellation = 20;
  97009. var radius = 0.8;
  97010. var points = new Array();
  97011. for (var i = 0; i < tessellation; i++) {
  97012. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  97013. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  97014. }
  97015. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  97016. rotationMesh.color = coloredMaterial.emissiveColor;
  97017. // Position arrow pointing in its drag axis
  97018. rotationMesh.scaling.scaleInPlace(0.26);
  97019. rotationMesh.material = coloredMaterial;
  97020. rotationMesh.rotation.x = Math.PI / 2;
  97021. parentMesh.addChild(rotationMesh);
  97022. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  97023. _this._rootMesh.addChild(parentMesh);
  97024. parentMesh.scaling.scaleInPlace(1 / 3);
  97025. // Add drag behavior to handle events when the gizmo is dragged
  97026. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  97027. _this.dragBehavior.moveAttached = false;
  97028. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  97029. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  97030. _this._rootMesh.addBehavior(_this.dragBehavior);
  97031. var lastDragPosition = new BABYLON.Vector3();
  97032. _this.dragBehavior.onDragStartObservable.add(function (e) {
  97033. if (_this.attachedMesh) {
  97034. lastDragPosition.copyFrom(e.dragPlanePoint);
  97035. }
  97036. });
  97037. var rotationMatrix = new BABYLON.Matrix();
  97038. var planeNormalTowardsCamera = new BABYLON.Vector3();
  97039. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  97040. var tmpSnapEvent = { snapDistance: 0 };
  97041. var currentSnapDragDistance = 0;
  97042. var tmpMatrix = new BABYLON.Matrix();
  97043. var tmpVector = new BABYLON.Vector3();
  97044. var amountToRotate = new BABYLON.Quaternion();
  97045. _this.dragBehavior.onDragObservable.add(function (event) {
  97046. if (_this.attachedMesh) {
  97047. if (!_this.attachedMesh.rotationQuaternion) {
  97048. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  97049. }
  97050. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  97051. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  97052. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  97053. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  97054. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  97055. var angle = Math.atan2(cross.length(), dot);
  97056. planeNormalTowardsCamera.copyFrom(planeNormal);
  97057. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  97058. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  97059. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  97060. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  97061. }
  97062. // Flip up vector depending on which side the camera is on
  97063. if (gizmoLayer.utilityLayerScene.activeCamera) {
  97064. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  97065. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  97066. planeNormalTowardsCamera.scaleInPlace(-1);
  97067. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  97068. }
  97069. }
  97070. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  97071. if (halfCircleSide)
  97072. angle = -angle;
  97073. // Snapping logic
  97074. var snapped = false;
  97075. if (_this.snapDistance != 0) {
  97076. currentSnapDragDistance += angle;
  97077. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  97078. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  97079. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  97080. angle = _this.snapDistance * dragSteps;
  97081. snapped = true;
  97082. }
  97083. else {
  97084. angle = 0;
  97085. }
  97086. }
  97087. // If the mesh has a parent, convert needed world rotation to local rotation
  97088. tmpMatrix.reset();
  97089. if (_this.attachedMesh.parent) {
  97090. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  97091. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  97092. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  97093. }
  97094. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  97095. var quaternionCoefficient = Math.sin(angle / 2);
  97096. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  97097. // 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
  97098. if (tmpMatrix.determinant() > 0) {
  97099. amountToRotate.toEulerAnglesToRef(tmpVector);
  97100. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  97101. }
  97102. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  97103. // Rotate selected mesh quaternion over fixed axis
  97104. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  97105. }
  97106. else {
  97107. // Rotate selected mesh quaternion over rotated axis
  97108. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  97109. }
  97110. lastDragPosition.copyFrom(event.dragPlanePoint);
  97111. if (snapped) {
  97112. tmpSnapEvent.snapDistance = angle;
  97113. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  97114. }
  97115. }
  97116. });
  97117. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97118. if (_this._customMeshSet) {
  97119. return;
  97120. }
  97121. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  97122. var material = isHovered ? hoverMaterial : coloredMaterial;
  97123. _this._rootMesh.getChildMeshes().forEach(function (m) {
  97124. m.material = material;
  97125. if (m.color) {
  97126. m.color = material.emissiveColor;
  97127. }
  97128. });
  97129. });
  97130. return _this;
  97131. }
  97132. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  97133. if (this.dragBehavior) {
  97134. this.dragBehavior.enabled = value ? true : false;
  97135. }
  97136. };
  97137. /**
  97138. * Disposes of the gizmo
  97139. */
  97140. PlaneRotationGizmo.prototype.dispose = function () {
  97141. this.onSnapObservable.clear();
  97142. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97143. this.dragBehavior.detach();
  97144. _super.prototype.dispose.call(this);
  97145. };
  97146. return PlaneRotationGizmo;
  97147. }(BABYLON.Gizmo));
  97148. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  97149. })(BABYLON || (BABYLON = {}));
  97150. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  97151. var BABYLON;
  97152. (function (BABYLON) {
  97153. /**
  97154. * Gizmo that enables dragging a mesh along 3 axis
  97155. */
  97156. var PositionGizmo = /** @class */ (function (_super) {
  97157. __extends(PositionGizmo, _super);
  97158. /**
  97159. * Creates a PositionGizmo
  97160. * @param gizmoLayer The utility layer the gizmo will be added to
  97161. */
  97162. function PositionGizmo(gizmoLayer) {
  97163. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97164. var _this = _super.call(this, gizmoLayer) || this;
  97165. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97166. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97167. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97168. _this.attachedMesh = null;
  97169. return _this;
  97170. }
  97171. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  97172. set: function (mesh) {
  97173. if (this.xGizmo) {
  97174. this.xGizmo.attachedMesh = mesh;
  97175. this.yGizmo.attachedMesh = mesh;
  97176. this.zGizmo.attachedMesh = mesh;
  97177. }
  97178. },
  97179. enumerable: true,
  97180. configurable: true
  97181. });
  97182. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97183. get: function () {
  97184. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97185. },
  97186. set: function (value) {
  97187. if (this.xGizmo) {
  97188. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97189. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97190. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97191. }
  97192. },
  97193. enumerable: true,
  97194. configurable: true
  97195. });
  97196. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  97197. get: function () {
  97198. return this.xGizmo.snapDistance;
  97199. },
  97200. /**
  97201. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97202. */
  97203. set: function (value) {
  97204. if (this.xGizmo) {
  97205. this.xGizmo.snapDistance = value;
  97206. this.yGizmo.snapDistance = value;
  97207. this.zGizmo.snapDistance = value;
  97208. }
  97209. },
  97210. enumerable: true,
  97211. configurable: true
  97212. });
  97213. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  97214. get: function () {
  97215. return this.xGizmo.scaleRatio;
  97216. },
  97217. /**
  97218. * Ratio for the scale of the gizmo (Default: 1)
  97219. */
  97220. set: function (value) {
  97221. if (this.xGizmo) {
  97222. this.xGizmo.scaleRatio = value;
  97223. this.yGizmo.scaleRatio = value;
  97224. this.zGizmo.scaleRatio = value;
  97225. }
  97226. },
  97227. enumerable: true,
  97228. configurable: true
  97229. });
  97230. /**
  97231. * Disposes of the gizmo
  97232. */
  97233. PositionGizmo.prototype.dispose = function () {
  97234. this.xGizmo.dispose();
  97235. this.yGizmo.dispose();
  97236. this.zGizmo.dispose();
  97237. };
  97238. /**
  97239. * CustomMeshes are not supported by this gizmo
  97240. * @param mesh The mesh to replace the default mesh of the gizmo
  97241. */
  97242. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  97243. 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)");
  97244. };
  97245. return PositionGizmo;
  97246. }(BABYLON.Gizmo));
  97247. BABYLON.PositionGizmo = PositionGizmo;
  97248. })(BABYLON || (BABYLON = {}));
  97249. //# sourceMappingURL=babylon.positionGizmo.js.map
  97250. var BABYLON;
  97251. (function (BABYLON) {
  97252. /**
  97253. * Gizmo that enables rotating a mesh along 3 axis
  97254. */
  97255. var RotationGizmo = /** @class */ (function (_super) {
  97256. __extends(RotationGizmo, _super);
  97257. /**
  97258. * Creates a RotationGizmo
  97259. * @param gizmoLayer The utility layer the gizmo will be added to
  97260. */
  97261. function RotationGizmo(gizmoLayer) {
  97262. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97263. var _this = _super.call(this, gizmoLayer) || this;
  97264. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97265. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97266. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97267. _this.attachedMesh = null;
  97268. return _this;
  97269. }
  97270. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  97271. set: function (mesh) {
  97272. if (this.xGizmo) {
  97273. this.xGizmo.attachedMesh = mesh;
  97274. this.yGizmo.attachedMesh = mesh;
  97275. this.zGizmo.attachedMesh = mesh;
  97276. }
  97277. },
  97278. enumerable: true,
  97279. configurable: true
  97280. });
  97281. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97282. get: function () {
  97283. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97284. },
  97285. set: function (value) {
  97286. if (this.xGizmo) {
  97287. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97288. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97289. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97290. }
  97291. },
  97292. enumerable: true,
  97293. configurable: true
  97294. });
  97295. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  97296. get: function () {
  97297. return this.xGizmo.snapDistance;
  97298. },
  97299. /**
  97300. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97301. */
  97302. set: function (value) {
  97303. if (this.xGizmo) {
  97304. this.xGizmo.snapDistance = value;
  97305. this.yGizmo.snapDistance = value;
  97306. this.zGizmo.snapDistance = value;
  97307. }
  97308. },
  97309. enumerable: true,
  97310. configurable: true
  97311. });
  97312. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  97313. get: function () {
  97314. return this.xGizmo.scaleRatio;
  97315. },
  97316. /**
  97317. * Ratio for the scale of the gizmo (Default: 1)
  97318. */
  97319. set: function (value) {
  97320. if (this.xGizmo) {
  97321. this.xGizmo.scaleRatio = value;
  97322. this.yGizmo.scaleRatio = value;
  97323. this.zGizmo.scaleRatio = value;
  97324. }
  97325. },
  97326. enumerable: true,
  97327. configurable: true
  97328. });
  97329. /**
  97330. * Disposes of the gizmo
  97331. */
  97332. RotationGizmo.prototype.dispose = function () {
  97333. this.xGizmo.dispose();
  97334. this.yGizmo.dispose();
  97335. this.zGizmo.dispose();
  97336. };
  97337. /**
  97338. * CustomMeshes are not supported by this gizmo
  97339. * @param mesh The mesh to replace the default mesh of the gizmo
  97340. */
  97341. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  97342. 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)");
  97343. };
  97344. return RotationGizmo;
  97345. }(BABYLON.Gizmo));
  97346. BABYLON.RotationGizmo = RotationGizmo;
  97347. })(BABYLON || (BABYLON = {}));
  97348. //# sourceMappingURL=babylon.rotationGizmo.js.map
  97349. var BABYLON;
  97350. (function (BABYLON) {
  97351. /**
  97352. * Gizmo that enables scaling a mesh along 3 axis
  97353. */
  97354. var ScaleGizmo = /** @class */ (function (_super) {
  97355. __extends(ScaleGizmo, _super);
  97356. /**
  97357. * Creates a ScaleGizmo
  97358. * @param gizmoLayer The utility layer the gizmo will be added to
  97359. */
  97360. function ScaleGizmo(gizmoLayer) {
  97361. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97362. var _this = _super.call(this, gizmoLayer) || this;
  97363. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97364. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97365. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97366. // Create uniform scale gizmo
  97367. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  97368. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97369. _this.uniformScaleGizmo.uniformScaling = true;
  97370. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  97371. octahedron.scaling.scaleInPlace(0.007);
  97372. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  97373. _this.attachedMesh = null;
  97374. return _this;
  97375. }
  97376. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  97377. set: function (mesh) {
  97378. if (this.xGizmo) {
  97379. this.xGizmo.attachedMesh = mesh;
  97380. this.yGizmo.attachedMesh = mesh;
  97381. this.zGizmo.attachedMesh = mesh;
  97382. this.uniformScaleGizmo.attachedMesh = mesh;
  97383. }
  97384. },
  97385. enumerable: true,
  97386. configurable: true
  97387. });
  97388. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97389. get: function () {
  97390. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97391. },
  97392. set: function (value) {
  97393. if (this.xGizmo) {
  97394. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97395. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97396. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97397. }
  97398. },
  97399. enumerable: true,
  97400. configurable: true
  97401. });
  97402. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  97403. get: function () {
  97404. return this.xGizmo.snapDistance;
  97405. },
  97406. /**
  97407. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97408. */
  97409. set: function (value) {
  97410. if (this.xGizmo) {
  97411. this.xGizmo.snapDistance = value;
  97412. this.yGizmo.snapDistance = value;
  97413. this.zGizmo.snapDistance = value;
  97414. this.uniformScaleGizmo.snapDistance = value;
  97415. }
  97416. },
  97417. enumerable: true,
  97418. configurable: true
  97419. });
  97420. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  97421. get: function () {
  97422. return this.xGizmo.scaleRatio;
  97423. },
  97424. /**
  97425. * Ratio for the scale of the gizmo (Default: 1)
  97426. */
  97427. set: function (value) {
  97428. if (this.xGizmo) {
  97429. this.xGizmo.scaleRatio = value;
  97430. this.yGizmo.scaleRatio = value;
  97431. this.zGizmo.scaleRatio = value;
  97432. this.uniformScaleGizmo.scaleRatio = value;
  97433. }
  97434. },
  97435. enumerable: true,
  97436. configurable: true
  97437. });
  97438. /**
  97439. * Disposes of the gizmo
  97440. */
  97441. ScaleGizmo.prototype.dispose = function () {
  97442. this.xGizmo.dispose();
  97443. this.yGizmo.dispose();
  97444. this.zGizmo.dispose();
  97445. this.uniformScaleGizmo.dispose();
  97446. };
  97447. return ScaleGizmo;
  97448. }(BABYLON.Gizmo));
  97449. BABYLON.ScaleGizmo = ScaleGizmo;
  97450. })(BABYLON || (BABYLON = {}));
  97451. //# sourceMappingURL=babylon.scaleGizmo.js.map
  97452. var BABYLON;
  97453. (function (BABYLON) {
  97454. /**
  97455. * Bounding box gizmo
  97456. */
  97457. var BoundingBoxGizmo = /** @class */ (function (_super) {
  97458. __extends(BoundingBoxGizmo, _super);
  97459. /**
  97460. * Creates an BoundingBoxGizmo
  97461. * @param gizmoLayer The utility layer the gizmo will be added to
  97462. * @param color The color of the gizmo
  97463. */
  97464. function BoundingBoxGizmo(color, gizmoLayer) {
  97465. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  97466. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  97467. var _this = _super.call(this, gizmoLayer) || this;
  97468. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  97469. _this._renderObserver = null;
  97470. _this._pointerObserver = null;
  97471. _this._scaleDragSpeed = 0.2;
  97472. _this._tmpQuaternion = new BABYLON.Quaternion();
  97473. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  97474. _this._tmpRotationMatrix = new BABYLON.Matrix();
  97475. /**
  97476. * 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)
  97477. */
  97478. _this.ignoreChildren = false;
  97479. /**
  97480. * 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)
  97481. */
  97482. _this.includeChildPredicate = null;
  97483. /**
  97484. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  97485. */
  97486. _this.rotationSphereSize = 0.1;
  97487. /**
  97488. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  97489. */
  97490. _this.scaleBoxSize = 0.1;
  97491. /**
  97492. * 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)
  97493. */
  97494. _this.fixedDragMeshScreenSize = false;
  97495. /**
  97496. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  97497. */
  97498. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  97499. /**
  97500. * Fired when a rotation sphere or scale box is dragged
  97501. */
  97502. _this.onDragStartObservable = new BABYLON.Observable();
  97503. /**
  97504. * Fired when a scale box is dragged
  97505. */
  97506. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  97507. /**
  97508. * Fired when a scale box drag is ended
  97509. */
  97510. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  97511. /**
  97512. * Fired when a rotation sphere is dragged
  97513. */
  97514. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  97515. /**
  97516. * Fired when a rotation sphere drag is ended
  97517. */
  97518. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  97519. /**
  97520. * 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)
  97521. */
  97522. _this.scalePivot = null;
  97523. _this._existingMeshScale = new BABYLON.Vector3();
  97524. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  97525. _this._updateScale = false;
  97526. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  97527. // Create Materials
  97528. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97529. coloredMaterial.disableLighting = true;
  97530. coloredMaterial.emissiveColor = color;
  97531. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97532. hoverColoredMaterial.disableLighting = true;
  97533. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97534. // Build bounding box out of lines
  97535. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97536. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  97537. var lines = [];
  97538. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  97539. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  97540. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  97541. 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));
  97542. 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));
  97543. 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));
  97544. 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));
  97545. 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));
  97546. 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));
  97547. 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));
  97548. 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));
  97549. 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));
  97550. lines.forEach(function (l) {
  97551. l.color = color;
  97552. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  97553. l.isPickable = false;
  97554. _this._lineBoundingBox.addChild(l);
  97555. });
  97556. _this._rootMesh.addChild(_this._lineBoundingBox);
  97557. // Create rotation spheres
  97558. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97559. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  97560. var _loop_1 = function (i_1) {
  97561. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  97562. sphere.rotationQuaternion = new BABYLON.Quaternion();
  97563. sphere.material = coloredMaterial;
  97564. // Drag behavior
  97565. _dragBehavior = new BABYLON.PointerDragBehavior({});
  97566. _dragBehavior.moveAttached = false;
  97567. _dragBehavior.updateDragPlane = false;
  97568. sphere.addBehavior(_dragBehavior);
  97569. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  97570. var totalTurnAmountOfDrag = 0;
  97571. _dragBehavior.onDragStartObservable.add(function (event) {
  97572. startingTurnDirection.copyFrom(sphere.forward);
  97573. totalTurnAmountOfDrag = 0;
  97574. });
  97575. _dragBehavior.onDragObservable.add(function (event) {
  97576. _this.onRotationSphereDragObservable.notifyObservers({});
  97577. if (_this.attachedMesh) {
  97578. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  97579. var worldDragDirection = startingTurnDirection;
  97580. // Project the world right on to the drag plane
  97581. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  97582. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  97583. // project drag delta on to the resulting drag axis and rotate based on that
  97584. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  97585. // Make rotation relative to size of mesh.
  97586. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  97587. // Rotate based on axis
  97588. if (!_this.attachedMesh.rotationQuaternion) {
  97589. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  97590. }
  97591. if (!_this._anchorMesh.rotationQuaternion) {
  97592. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  97593. }
  97594. // Do not allow the object to turn more than a full circle
  97595. totalTurnAmountOfDrag += projectDist;
  97596. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  97597. if (i_1 >= 8) {
  97598. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  97599. }
  97600. else if (i_1 >= 4) {
  97601. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  97602. }
  97603. else {
  97604. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  97605. }
  97606. // Rotate around center of bounding box
  97607. _this._anchorMesh.addChild(_this.attachedMesh);
  97608. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  97609. _this._anchorMesh.removeChild(_this.attachedMesh);
  97610. }
  97611. _this.updateBoundingBox();
  97612. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  97613. }
  97614. });
  97615. // Selection/deselection
  97616. _dragBehavior.onDragStartObservable.add(function () {
  97617. _this.onDragStartObservable.notifyObservers({});
  97618. _this._selectNode(sphere);
  97619. });
  97620. _dragBehavior.onDragEndObservable.add(function () {
  97621. _this.onRotationSphereDragEndObservable.notifyObservers({});
  97622. _this._selectNode(null);
  97623. });
  97624. this_1._rotateSpheresParent.addChild(sphere);
  97625. };
  97626. var this_1 = this, _dragBehavior;
  97627. for (var i_1 = 0; i_1 < 12; i_1++) {
  97628. _loop_1(i_1);
  97629. }
  97630. _this._rootMesh.addChild(_this._rotateSpheresParent);
  97631. // Create scale cubes
  97632. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97633. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  97634. for (var i = 0; i < 2; i++) {
  97635. for (var j = 0; j < 2; j++) {
  97636. var _loop_2 = function () {
  97637. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  97638. box.material = coloredMaterial;
  97639. // Dragging logic
  97640. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  97641. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  97642. _dragBehavior.moveAttached = false;
  97643. box.addBehavior(_dragBehavior);
  97644. _dragBehavior.onDragObservable.add(function (event) {
  97645. _this.onScaleBoxDragObservable.notifyObservers({});
  97646. if (_this.attachedMesh) {
  97647. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  97648. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  97649. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  97650. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  97651. _this.updateBoundingBox();
  97652. if (_this.scalePivot) {
  97653. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  97654. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  97655. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  97656. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  97657. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  97658. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  97659. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  97660. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  97661. }
  97662. else {
  97663. // Scale from the position of the opposite corner
  97664. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  97665. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  97666. }
  97667. _this._anchorMesh.addChild(_this.attachedMesh);
  97668. _this._anchorMesh.scaling.addInPlace(deltaScale);
  97669. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  97670. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  97671. }
  97672. _this._anchorMesh.removeChild(_this.attachedMesh);
  97673. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  97674. }
  97675. });
  97676. // Selection/deselection
  97677. _dragBehavior.onDragStartObservable.add(function () {
  97678. _this.onDragStartObservable.notifyObservers({});
  97679. _this._selectNode(box);
  97680. });
  97681. _dragBehavior.onDragEndObservable.add(function () {
  97682. _this.onScaleBoxDragEndObservable.notifyObservers({});
  97683. _this._selectNode(null);
  97684. });
  97685. this_2._scaleBoxesParent.addChild(box);
  97686. };
  97687. var this_2 = this, _dragBehavior;
  97688. for (var k = 0; k < 2; k++) {
  97689. _loop_2();
  97690. }
  97691. }
  97692. }
  97693. _this._rootMesh.addChild(_this._scaleBoxesParent);
  97694. // Hover color change
  97695. var pointerIds = new Array();
  97696. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97697. if (!pointerIds[pointerInfo.event.pointerId]) {
  97698. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  97699. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  97700. pointerIds[pointerInfo.event.pointerId] = mesh;
  97701. mesh.material = hoverColoredMaterial;
  97702. }
  97703. });
  97704. }
  97705. else {
  97706. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  97707. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  97708. delete pointerIds[pointerInfo.event.pointerId];
  97709. }
  97710. }
  97711. });
  97712. // Update bounding box positions
  97713. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  97714. // Only update the bouding box if scaling has changed
  97715. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  97716. _this.updateBoundingBox();
  97717. }
  97718. });
  97719. _this.updateBoundingBox();
  97720. return _this;
  97721. }
  97722. /** @hidden */
  97723. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  97724. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  97725. // Save old pivot and set pivot to 0,0,0
  97726. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  97727. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  97728. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  97729. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  97730. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  97731. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  97732. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  97733. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  97734. }
  97735. }
  97736. BoundingBoxGizmo._PivotCached++;
  97737. };
  97738. /** @hidden */
  97739. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  97740. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  97741. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  97742. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  97743. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  97744. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  97745. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  97746. }
  97747. this._PivotCached--;
  97748. };
  97749. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  97750. if (value) {
  97751. // Reset anchor mesh to match attached mesh's scale
  97752. // This is needed to avoid invalid box/sphere position on first drag
  97753. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  97754. this._anchorMesh.addChild(value);
  97755. this._anchorMesh.removeChild(value);
  97756. BoundingBoxGizmo._RestorePivotPoint(value);
  97757. this.updateBoundingBox();
  97758. }
  97759. };
  97760. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  97761. this._rotateSpheresParent.getChildMeshes()
  97762. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  97763. m.isVisible = (!selectedMesh || m == selectedMesh);
  97764. });
  97765. };
  97766. /**
  97767. * Updates the bounding box information for the Gizmo
  97768. */
  97769. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  97770. if (this.attachedMesh) {
  97771. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  97772. this._update();
  97773. // Rotate based on axis
  97774. if (!this.attachedMesh.rotationQuaternion) {
  97775. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  97776. }
  97777. if (!this._anchorMesh.rotationQuaternion) {
  97778. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  97779. }
  97780. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  97781. // Store original position and reset mesh to origin before computing the bounding box
  97782. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  97783. this._tmpVector.copyFrom(this.attachedMesh.position);
  97784. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  97785. this.attachedMesh.position.set(0, 0, 0);
  97786. // Update bounding dimensions/positions
  97787. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  97788. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  97789. // Update gizmo to match bounding box scaling and rotation
  97790. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  97791. 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);
  97792. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  97793. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  97794. this._lineBoundingBox.computeWorldMatrix();
  97795. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  97796. // restore position/rotation values
  97797. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  97798. this.attachedMesh.position.copyFrom(this._tmpVector);
  97799. }
  97800. // Update rotation sphere locations
  97801. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  97802. for (var i = 0; i < 3; i++) {
  97803. for (var j = 0; j < 2; j++) {
  97804. for (var k = 0; k < 2; k++) {
  97805. var index = ((i * 4) + (j * 2)) + k;
  97806. if (i == 0) {
  97807. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  97808. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97809. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97810. }
  97811. if (i == 1) {
  97812. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  97813. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97814. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97815. }
  97816. if (i == 2) {
  97817. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  97818. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97819. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97820. }
  97821. if (this.fixedDragMeshScreenSize) {
  97822. this._rootMesh.computeWorldMatrix();
  97823. this._rotateSpheresParent.computeWorldMatrix();
  97824. rotateSpheres[index].computeWorldMatrix();
  97825. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  97826. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  97827. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  97828. }
  97829. else {
  97830. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  97831. }
  97832. }
  97833. }
  97834. }
  97835. // Update scale box locations
  97836. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  97837. for (var i = 0; i < 2; i++) {
  97838. for (var j = 0; j < 2; j++) {
  97839. for (var k = 0; k < 2; k++) {
  97840. var index = ((i * 4) + (j * 2)) + k;
  97841. if (scaleBoxes[index]) {
  97842. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  97843. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97844. if (this.fixedDragMeshScreenSize) {
  97845. this._rootMesh.computeWorldMatrix();
  97846. this._scaleBoxesParent.computeWorldMatrix();
  97847. scaleBoxes[index].computeWorldMatrix();
  97848. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  97849. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  97850. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  97851. }
  97852. else {
  97853. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  97854. }
  97855. }
  97856. }
  97857. }
  97858. }
  97859. if (this.attachedMesh) {
  97860. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  97861. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  97862. }
  97863. };
  97864. /**
  97865. * Enables rotation on the specified axis and disables rotation on the others
  97866. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  97867. */
  97868. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  97869. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  97870. if (i < 4) {
  97871. m.setEnabled(axis.indexOf("x") != -1);
  97872. }
  97873. else if (i < 8) {
  97874. m.setEnabled(axis.indexOf("y") != -1);
  97875. }
  97876. else {
  97877. m.setEnabled(axis.indexOf("z") != -1);
  97878. }
  97879. });
  97880. };
  97881. /**
  97882. * Disposes of the gizmo
  97883. */
  97884. BoundingBoxGizmo.prototype.dispose = function () {
  97885. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97886. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  97887. this._lineBoundingBox.dispose();
  97888. this._rotateSpheresParent.dispose();
  97889. this._scaleBoxesParent.dispose();
  97890. _super.prototype.dispose.call(this);
  97891. };
  97892. /**
  97893. * 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)
  97894. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  97895. * @returns the bounding box mesh with the passed in mesh as a child
  97896. */
  97897. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  97898. var makeNotPickable = function (root) {
  97899. root.isPickable = false;
  97900. root.getChildMeshes().forEach(function (c) {
  97901. makeNotPickable(c);
  97902. });
  97903. };
  97904. makeNotPickable(mesh);
  97905. // Reset position to get boudning box from origin with no rotation
  97906. if (!mesh.rotationQuaternion) {
  97907. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  97908. }
  97909. var oldPos = mesh.position.clone();
  97910. var oldRot = mesh.rotationQuaternion.clone();
  97911. mesh.rotationQuaternion.set(0, 0, 0, 1);
  97912. mesh.position.set(0, 0, 0);
  97913. // Update bounding dimensions/positions
  97914. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  97915. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  97916. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  97917. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  97918. // Restore original positions
  97919. mesh.addChild(box);
  97920. mesh.rotationQuaternion.copyFrom(oldRot);
  97921. mesh.position.copyFrom(oldPos);
  97922. // Reverse parenting
  97923. mesh.removeChild(box);
  97924. box.addChild(mesh);
  97925. box.visibility = 0;
  97926. return box;
  97927. };
  97928. /**
  97929. * CustomMeshes are not supported by this gizmo
  97930. * @param mesh The mesh to replace the default mesh of the gizmo
  97931. */
  97932. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  97933. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  97934. };
  97935. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  97936. // store/remove pivot point should only be applied during their outermost calls
  97937. BoundingBoxGizmo._PivotCached = 0;
  97938. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  97939. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  97940. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  97941. return BoundingBoxGizmo;
  97942. }(BABYLON.Gizmo));
  97943. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  97944. })(BABYLON || (BABYLON = {}));
  97945. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  97946. var BABYLON;
  97947. (function (BABYLON) {
  97948. /**
  97949. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  97950. */
  97951. var GizmoManager = /** @class */ (function () {
  97952. /**
  97953. * Instatiates a gizmo manager
  97954. * @param scene the scene to overlay the gizmos on top of
  97955. */
  97956. function GizmoManager(scene) {
  97957. var _this = this;
  97958. this.scene = scene;
  97959. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  97960. this._pointerObserver = null;
  97961. this._attachedMesh = null;
  97962. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  97963. /**
  97964. * When bounding box gizmo is enabled, this can be used to track drag/end events
  97965. */
  97966. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  97967. /**
  97968. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  97969. */
  97970. this.attachableMeshes = null;
  97971. /**
  97972. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  97973. */
  97974. this.usePointerToAttachGizmos = true;
  97975. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  97976. // Instatiate/dispose gizmos based on pointer actions
  97977. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  97978. if (!_this.usePointerToAttachGizmos) {
  97979. return;
  97980. }
  97981. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  97982. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  97983. var node = pointerInfo.pickInfo.pickedMesh;
  97984. if (_this.attachableMeshes == null) {
  97985. // Attach to the most parent node
  97986. while (node && node.parent != null) {
  97987. node = node.parent;
  97988. }
  97989. }
  97990. else {
  97991. // Attach to the parent node that is an attachableMesh
  97992. var found = false;
  97993. _this.attachableMeshes.forEach(function (mesh) {
  97994. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  97995. node = mesh;
  97996. found = true;
  97997. }
  97998. });
  97999. if (!found) {
  98000. node = null;
  98001. }
  98002. }
  98003. if (node instanceof BABYLON.AbstractMesh) {
  98004. _this.attachToMesh(node);
  98005. }
  98006. else {
  98007. _this.attachToMesh(null);
  98008. }
  98009. }
  98010. else {
  98011. _this.attachToMesh(null);
  98012. }
  98013. }
  98014. });
  98015. }
  98016. /**
  98017. * Attaches a set of gizmos to the specified mesh
  98018. * @param mesh The mesh the gizmo's should be attached to
  98019. */
  98020. GizmoManager.prototype.attachToMesh = function (mesh) {
  98021. if (this._attachedMesh) {
  98022. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  98023. }
  98024. this._attachedMesh = mesh;
  98025. for (var key in this.gizmos) {
  98026. var gizmo = (this.gizmos[key]);
  98027. if (gizmo && this._gizmosEnabled[key]) {
  98028. gizmo.attachedMesh = mesh;
  98029. }
  98030. }
  98031. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  98032. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  98033. }
  98034. };
  98035. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  98036. get: function () {
  98037. return this._gizmosEnabled.positionGizmo;
  98038. },
  98039. /**
  98040. * If the position gizmo is enabled
  98041. */
  98042. set: function (value) {
  98043. if (value) {
  98044. if (!this.gizmos.positionGizmo) {
  98045. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  98046. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98047. }
  98048. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  98049. }
  98050. else if (this.gizmos.positionGizmo) {
  98051. this.gizmos.positionGizmo.attachedMesh = null;
  98052. }
  98053. this._gizmosEnabled.positionGizmo = value;
  98054. },
  98055. enumerable: true,
  98056. configurable: true
  98057. });
  98058. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  98059. get: function () {
  98060. return this._gizmosEnabled.rotationGizmo;
  98061. },
  98062. /**
  98063. * If the rotation gizmo is enabled
  98064. */
  98065. set: function (value) {
  98066. if (value) {
  98067. if (!this.gizmos.rotationGizmo) {
  98068. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  98069. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98070. }
  98071. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  98072. }
  98073. else if (this.gizmos.rotationGizmo) {
  98074. this.gizmos.rotationGizmo.attachedMesh = null;
  98075. }
  98076. this._gizmosEnabled.rotationGizmo = value;
  98077. },
  98078. enumerable: true,
  98079. configurable: true
  98080. });
  98081. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  98082. get: function () {
  98083. return this._gizmosEnabled.scaleGizmo;
  98084. },
  98085. /**
  98086. * If the scale gizmo is enabled
  98087. */
  98088. set: function (value) {
  98089. if (value) {
  98090. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  98091. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  98092. }
  98093. else if (this.gizmos.scaleGizmo) {
  98094. this.gizmos.scaleGizmo.attachedMesh = null;
  98095. }
  98096. this._gizmosEnabled.scaleGizmo = value;
  98097. },
  98098. enumerable: true,
  98099. configurable: true
  98100. });
  98101. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  98102. get: function () {
  98103. return this._gizmosEnabled.boundingBoxGizmo;
  98104. },
  98105. /**
  98106. * If the boundingBox gizmo is enabled
  98107. */
  98108. set: function (value) {
  98109. if (value) {
  98110. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  98111. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  98112. if (this._attachedMesh) {
  98113. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  98114. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  98115. }
  98116. }
  98117. else if (this.gizmos.boundingBoxGizmo) {
  98118. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  98119. }
  98120. this._gizmosEnabled.boundingBoxGizmo = value;
  98121. },
  98122. enumerable: true,
  98123. configurable: true
  98124. });
  98125. /**
  98126. * Disposes of the gizmo manager
  98127. */
  98128. GizmoManager.prototype.dispose = function () {
  98129. this.scene.onPointerObservable.remove(this._pointerObserver);
  98130. for (var key in this.gizmos) {
  98131. var gizmo = (this.gizmos[key]);
  98132. if (gizmo) {
  98133. gizmo.dispose();
  98134. }
  98135. }
  98136. this.boundingBoxDragBehavior.detach();
  98137. };
  98138. return GizmoManager;
  98139. }());
  98140. BABYLON.GizmoManager = GizmoManager;
  98141. })(BABYLON || (BABYLON = {}));
  98142. //# sourceMappingURL=babylon.gizmoManager.js.map
  98143. var BABYLON;
  98144. (function (BABYLON) {
  98145. /**
  98146. * Defines a target to use with MorphTargetManager
  98147. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  98148. */
  98149. var MorphTarget = /** @class */ (function () {
  98150. /**
  98151. * Creates a new MorphTarget
  98152. * @param name defines the name of the target
  98153. * @param influence defines the influence to use
  98154. */
  98155. function MorphTarget(
  98156. /** defines the name of the target */
  98157. name, influence, scene) {
  98158. if (influence === void 0) { influence = 0; }
  98159. if (scene === void 0) { scene = null; }
  98160. this.name = name;
  98161. /**
  98162. * Gets or sets the list of animations
  98163. */
  98164. this.animations = new Array();
  98165. this._positions = null;
  98166. this._normals = null;
  98167. this._tangents = null;
  98168. /**
  98169. * Observable raised when the influence changes
  98170. */
  98171. this.onInfluenceChanged = new BABYLON.Observable();
  98172. this._animationPropertiesOverride = null;
  98173. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98174. this.influence = influence;
  98175. }
  98176. Object.defineProperty(MorphTarget.prototype, "influence", {
  98177. /**
  98178. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  98179. */
  98180. get: function () {
  98181. return this._influence;
  98182. },
  98183. set: function (influence) {
  98184. if (this._influence === influence) {
  98185. return;
  98186. }
  98187. var previous = this._influence;
  98188. this._influence = influence;
  98189. if (this.onInfluenceChanged.hasObservers) {
  98190. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  98191. }
  98192. },
  98193. enumerable: true,
  98194. configurable: true
  98195. });
  98196. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  98197. /**
  98198. * Gets or sets the animation properties override
  98199. */
  98200. get: function () {
  98201. if (!this._animationPropertiesOverride && this._scene) {
  98202. return this._scene.animationPropertiesOverride;
  98203. }
  98204. return this._animationPropertiesOverride;
  98205. },
  98206. set: function (value) {
  98207. this._animationPropertiesOverride = value;
  98208. },
  98209. enumerable: true,
  98210. configurable: true
  98211. });
  98212. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  98213. /**
  98214. * Gets a boolean defining if the target contains position data
  98215. */
  98216. get: function () {
  98217. return !!this._positions;
  98218. },
  98219. enumerable: true,
  98220. configurable: true
  98221. });
  98222. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  98223. /**
  98224. * Gets a boolean defining if the target contains normal data
  98225. */
  98226. get: function () {
  98227. return !!this._normals;
  98228. },
  98229. enumerable: true,
  98230. configurable: true
  98231. });
  98232. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  98233. /**
  98234. * Gets a boolean defining if the target contains tangent data
  98235. */
  98236. get: function () {
  98237. return !!this._tangents;
  98238. },
  98239. enumerable: true,
  98240. configurable: true
  98241. });
  98242. /**
  98243. * Affects position data to this target
  98244. * @param data defines the position data to use
  98245. */
  98246. MorphTarget.prototype.setPositions = function (data) {
  98247. this._positions = data;
  98248. };
  98249. /**
  98250. * Gets the position data stored in this target
  98251. * @returns a FloatArray containing the position data (or null if not present)
  98252. */
  98253. MorphTarget.prototype.getPositions = function () {
  98254. return this._positions;
  98255. };
  98256. /**
  98257. * Affects normal data to this target
  98258. * @param data defines the normal data to use
  98259. */
  98260. MorphTarget.prototype.setNormals = function (data) {
  98261. this._normals = data;
  98262. };
  98263. /**
  98264. * Gets the normal data stored in this target
  98265. * @returns a FloatArray containing the normal data (or null if not present)
  98266. */
  98267. MorphTarget.prototype.getNormals = function () {
  98268. return this._normals;
  98269. };
  98270. /**
  98271. * Affects tangent data to this target
  98272. * @param data defines the tangent data to use
  98273. */
  98274. MorphTarget.prototype.setTangents = function (data) {
  98275. this._tangents = data;
  98276. };
  98277. /**
  98278. * Gets the tangent data stored in this target
  98279. * @returns a FloatArray containing the tangent data (or null if not present)
  98280. */
  98281. MorphTarget.prototype.getTangents = function () {
  98282. return this._tangents;
  98283. };
  98284. /**
  98285. * Serializes the current target into a Serialization object
  98286. * @returns the serialized object
  98287. */
  98288. MorphTarget.prototype.serialize = function () {
  98289. var serializationObject = {};
  98290. serializationObject.name = this.name;
  98291. serializationObject.influence = this.influence;
  98292. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  98293. if (this.hasNormals) {
  98294. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  98295. }
  98296. if (this.hasTangents) {
  98297. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  98298. }
  98299. // Animations
  98300. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  98301. return serializationObject;
  98302. };
  98303. // Statics
  98304. /**
  98305. * Creates a new target from serialized data
  98306. * @param serializationObject defines the serialized data to use
  98307. * @returns a new MorphTarget
  98308. */
  98309. MorphTarget.Parse = function (serializationObject) {
  98310. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  98311. result.setPositions(serializationObject.positions);
  98312. if (serializationObject.normals) {
  98313. result.setNormals(serializationObject.normals);
  98314. }
  98315. if (serializationObject.tangents) {
  98316. result.setTangents(serializationObject.tangents);
  98317. }
  98318. // Animations
  98319. if (serializationObject.animations) {
  98320. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  98321. var parsedAnimation = serializationObject.animations[animationIndex];
  98322. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  98323. }
  98324. }
  98325. return result;
  98326. };
  98327. /**
  98328. * Creates a MorphTarget from mesh data
  98329. * @param mesh defines the source mesh
  98330. * @param name defines the name to use for the new target
  98331. * @param influence defines the influence to attach to the target
  98332. * @returns a new MorphTarget
  98333. */
  98334. MorphTarget.FromMesh = function (mesh, name, influence) {
  98335. if (!name) {
  98336. name = mesh.name;
  98337. }
  98338. var result = new MorphTarget(name, influence, mesh.getScene());
  98339. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  98340. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  98341. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  98342. }
  98343. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  98344. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  98345. }
  98346. return result;
  98347. };
  98348. return MorphTarget;
  98349. }());
  98350. BABYLON.MorphTarget = MorphTarget;
  98351. })(BABYLON || (BABYLON = {}));
  98352. //# sourceMappingURL=babylon.morphTarget.js.map
  98353. var BABYLON;
  98354. (function (BABYLON) {
  98355. /**
  98356. * This class is used to deform meshes using morphing between different targets
  98357. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  98358. */
  98359. var MorphTargetManager = /** @class */ (function () {
  98360. /**
  98361. * Creates a new MorphTargetManager
  98362. * @param scene defines the current scene
  98363. */
  98364. function MorphTargetManager(scene) {
  98365. if (scene === void 0) { scene = null; }
  98366. this._targets = new Array();
  98367. this._targetObservable = new Array();
  98368. this._activeTargets = new BABYLON.SmartArray(16);
  98369. this._supportsNormals = false;
  98370. this._supportsTangents = false;
  98371. this._vertexCount = 0;
  98372. this._uniqueId = 0;
  98373. this._tempInfluences = new Array();
  98374. if (!scene) {
  98375. scene = BABYLON.Engine.LastCreatedScene;
  98376. }
  98377. this._scene = scene;
  98378. if (this._scene) {
  98379. this._scene.morphTargetManagers.push(this);
  98380. this._uniqueId = this._scene.getUniqueId();
  98381. }
  98382. }
  98383. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  98384. /**
  98385. * Gets the unique ID of this manager
  98386. */
  98387. get: function () {
  98388. return this._uniqueId;
  98389. },
  98390. enumerable: true,
  98391. configurable: true
  98392. });
  98393. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  98394. /**
  98395. * Gets the number of vertices handled by this manager
  98396. */
  98397. get: function () {
  98398. return this._vertexCount;
  98399. },
  98400. enumerable: true,
  98401. configurable: true
  98402. });
  98403. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  98404. /**
  98405. * Gets a boolean indicating if this manager supports morphing of normals
  98406. */
  98407. get: function () {
  98408. return this._supportsNormals;
  98409. },
  98410. enumerable: true,
  98411. configurable: true
  98412. });
  98413. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  98414. /**
  98415. * Gets a boolean indicating if this manager supports morphing of tangents
  98416. */
  98417. get: function () {
  98418. return this._supportsTangents;
  98419. },
  98420. enumerable: true,
  98421. configurable: true
  98422. });
  98423. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  98424. /**
  98425. * Gets the number of targets stored in this manager
  98426. */
  98427. get: function () {
  98428. return this._targets.length;
  98429. },
  98430. enumerable: true,
  98431. configurable: true
  98432. });
  98433. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  98434. /**
  98435. * Gets the number of influencers (ie. the number of targets with influences > 0)
  98436. */
  98437. get: function () {
  98438. return this._activeTargets.length;
  98439. },
  98440. enumerable: true,
  98441. configurable: true
  98442. });
  98443. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  98444. /**
  98445. * Gets the list of influences (one per target)
  98446. */
  98447. get: function () {
  98448. return this._influences;
  98449. },
  98450. enumerable: true,
  98451. configurable: true
  98452. });
  98453. /**
  98454. * Gets the active target at specified index. An active target is a target with an influence > 0
  98455. * @param index defines the index to check
  98456. * @returns the requested target
  98457. */
  98458. MorphTargetManager.prototype.getActiveTarget = function (index) {
  98459. return this._activeTargets.data[index];
  98460. };
  98461. /**
  98462. * Gets the target at specified index
  98463. * @param index defines the index to check
  98464. * @returns the requested target
  98465. */
  98466. MorphTargetManager.prototype.getTarget = function (index) {
  98467. return this._targets[index];
  98468. };
  98469. /**
  98470. * Add a new target to this manager
  98471. * @param target defines the target to add
  98472. */
  98473. MorphTargetManager.prototype.addTarget = function (target) {
  98474. var _this = this;
  98475. this._targets.push(target);
  98476. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  98477. _this._syncActiveTargets(needUpdate);
  98478. }));
  98479. this._syncActiveTargets(true);
  98480. };
  98481. /**
  98482. * Removes a target from the manager
  98483. * @param target defines the target to remove
  98484. */
  98485. MorphTargetManager.prototype.removeTarget = function (target) {
  98486. var index = this._targets.indexOf(target);
  98487. if (index >= 0) {
  98488. this._targets.splice(index, 1);
  98489. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  98490. this._syncActiveTargets(true);
  98491. }
  98492. };
  98493. /**
  98494. * Serializes the current manager into a Serialization object
  98495. * @returns the serialized object
  98496. */
  98497. MorphTargetManager.prototype.serialize = function () {
  98498. var serializationObject = {};
  98499. serializationObject.id = this.uniqueId;
  98500. serializationObject.targets = [];
  98501. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  98502. var target = _a[_i];
  98503. serializationObject.targets.push(target.serialize());
  98504. }
  98505. return serializationObject;
  98506. };
  98507. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  98508. var influenceCount = 0;
  98509. this._activeTargets.reset();
  98510. this._supportsNormals = true;
  98511. this._supportsTangents = true;
  98512. this._vertexCount = 0;
  98513. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  98514. var target = _a[_i];
  98515. this._activeTargets.push(target);
  98516. this._tempInfluences[influenceCount++] = target.influence;
  98517. var positions = target.getPositions();
  98518. if (positions) {
  98519. this._supportsNormals = this._supportsNormals && target.hasNormals;
  98520. this._supportsTangents = this._supportsTangents && target.hasTangents;
  98521. var vertexCount = positions.length / 3;
  98522. if (this._vertexCount === 0) {
  98523. this._vertexCount = vertexCount;
  98524. }
  98525. else if (this._vertexCount !== vertexCount) {
  98526. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  98527. return;
  98528. }
  98529. }
  98530. }
  98531. if (!this._influences || this._influences.length !== influenceCount) {
  98532. this._influences = new Float32Array(influenceCount);
  98533. }
  98534. for (var index = 0; index < influenceCount; index++) {
  98535. this._influences[index] = this._tempInfluences[index];
  98536. }
  98537. if (needUpdate) {
  98538. this.synchronize();
  98539. }
  98540. };
  98541. /**
  98542. * Syncrhonize the targets with all the meshes using this morph target manager
  98543. */
  98544. MorphTargetManager.prototype.synchronize = function () {
  98545. if (!this._scene) {
  98546. return;
  98547. }
  98548. // Flag meshes as dirty to resync with the active targets
  98549. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  98550. var mesh = _a[_i];
  98551. if (mesh.morphTargetManager === this) {
  98552. mesh._syncGeometryWithMorphTargetManager();
  98553. }
  98554. }
  98555. };
  98556. // Statics
  98557. /**
  98558. * Creates a new MorphTargetManager from serialized data
  98559. * @param serializationObject defines the serialized data
  98560. * @param scene defines the hosting scene
  98561. * @returns the new MorphTargetManager
  98562. */
  98563. MorphTargetManager.Parse = function (serializationObject, scene) {
  98564. var result = new MorphTargetManager(scene);
  98565. result._uniqueId = serializationObject.id;
  98566. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  98567. var targetData = _a[_i];
  98568. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  98569. }
  98570. return result;
  98571. };
  98572. return MorphTargetManager;
  98573. }());
  98574. BABYLON.MorphTargetManager = MorphTargetManager;
  98575. })(BABYLON || (BABYLON = {}));
  98576. //# sourceMappingURL=babylon.morphTargetManager.js.map
  98577. var BABYLON;
  98578. (function (BABYLON) {
  98579. var Octree = /** @class */ (function () {
  98580. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  98581. if (maxDepth === void 0) { maxDepth = 2; }
  98582. this.maxDepth = maxDepth;
  98583. this.dynamicContent = new Array();
  98584. this._maxBlockCapacity = maxBlockCapacity || 64;
  98585. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  98586. this._creationFunc = creationFunc;
  98587. }
  98588. // Methods
  98589. Octree.prototype.update = function (worldMin, worldMax, entries) {
  98590. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  98591. };
  98592. Octree.prototype.addMesh = function (entry) {
  98593. for (var index = 0; index < this.blocks.length; index++) {
  98594. var block = this.blocks[index];
  98595. block.addEntry(entry);
  98596. }
  98597. };
  98598. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  98599. this._selectionContent.reset();
  98600. for (var index = 0; index < this.blocks.length; index++) {
  98601. var block = this.blocks[index];
  98602. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  98603. }
  98604. if (allowDuplicate) {
  98605. this._selectionContent.concat(this.dynamicContent);
  98606. }
  98607. else {
  98608. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98609. }
  98610. return this._selectionContent;
  98611. };
  98612. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  98613. this._selectionContent.reset();
  98614. for (var index = 0; index < this.blocks.length; index++) {
  98615. var block = this.blocks[index];
  98616. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  98617. }
  98618. if (allowDuplicate) {
  98619. this._selectionContent.concat(this.dynamicContent);
  98620. }
  98621. else {
  98622. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98623. }
  98624. return this._selectionContent;
  98625. };
  98626. Octree.prototype.intersectsRay = function (ray) {
  98627. this._selectionContent.reset();
  98628. for (var index = 0; index < this.blocks.length; index++) {
  98629. var block = this.blocks[index];
  98630. block.intersectsRay(ray, this._selectionContent);
  98631. }
  98632. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98633. return this._selectionContent;
  98634. };
  98635. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  98636. target.blocks = new Array();
  98637. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  98638. // Segmenting space
  98639. for (var x = 0; x < 2; x++) {
  98640. for (var y = 0; y < 2; y++) {
  98641. for (var z = 0; z < 2; z++) {
  98642. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  98643. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  98644. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  98645. block.addEntries(entries);
  98646. target.blocks.push(block);
  98647. }
  98648. }
  98649. }
  98650. };
  98651. Octree.CreationFuncForMeshes = function (entry, block) {
  98652. var boundingInfo = entry.getBoundingInfo();
  98653. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  98654. block.entries.push(entry);
  98655. }
  98656. };
  98657. Octree.CreationFuncForSubMeshes = function (entry, block) {
  98658. var boundingInfo = entry.getBoundingInfo();
  98659. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  98660. block.entries.push(entry);
  98661. }
  98662. };
  98663. return Octree;
  98664. }());
  98665. BABYLON.Octree = Octree;
  98666. })(BABYLON || (BABYLON = {}));
  98667. //# sourceMappingURL=babylon.octree.js.map
  98668. var BABYLON;
  98669. (function (BABYLON) {
  98670. /**
  98671. * Class used to store a cell in an octree
  98672. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  98673. */
  98674. var OctreeBlock = /** @class */ (function () {
  98675. /**
  98676. * Creates a new block
  98677. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  98678. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  98679. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  98680. * @param depth defines the current depth of this block in the octree
  98681. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  98682. * @param creationFunc defines a callback to call when an element is added to the block
  98683. */
  98684. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  98685. /**
  98686. * Gets the content of the current block
  98687. */
  98688. this.entries = new Array();
  98689. this._boundingVectors = new Array();
  98690. this._capacity = capacity;
  98691. this._depth = depth;
  98692. this._maxDepth = maxDepth;
  98693. this._creationFunc = creationFunc;
  98694. this._minPoint = minPoint;
  98695. this._maxPoint = maxPoint;
  98696. this._boundingVectors.push(minPoint.clone());
  98697. this._boundingVectors.push(maxPoint.clone());
  98698. this._boundingVectors.push(minPoint.clone());
  98699. this._boundingVectors[2].x = maxPoint.x;
  98700. this._boundingVectors.push(minPoint.clone());
  98701. this._boundingVectors[3].y = maxPoint.y;
  98702. this._boundingVectors.push(minPoint.clone());
  98703. this._boundingVectors[4].z = maxPoint.z;
  98704. this._boundingVectors.push(maxPoint.clone());
  98705. this._boundingVectors[5].z = minPoint.z;
  98706. this._boundingVectors.push(maxPoint.clone());
  98707. this._boundingVectors[6].x = minPoint.x;
  98708. this._boundingVectors.push(maxPoint.clone());
  98709. this._boundingVectors[7].y = minPoint.y;
  98710. }
  98711. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  98712. // Property
  98713. /**
  98714. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  98715. */
  98716. get: function () {
  98717. return this._capacity;
  98718. },
  98719. enumerable: true,
  98720. configurable: true
  98721. });
  98722. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  98723. /**
  98724. * Gets the minimum vector (in world space) of the block's bounding box
  98725. */
  98726. get: function () {
  98727. return this._minPoint;
  98728. },
  98729. enumerable: true,
  98730. configurable: true
  98731. });
  98732. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  98733. /**
  98734. * Gets the maximum vector (in world space) of the block's bounding box
  98735. */
  98736. get: function () {
  98737. return this._maxPoint;
  98738. },
  98739. enumerable: true,
  98740. configurable: true
  98741. });
  98742. // Methods
  98743. /**
  98744. * Add a new element to this block
  98745. * @param entry defines the element to add
  98746. */
  98747. OctreeBlock.prototype.addEntry = function (entry) {
  98748. if (this.blocks) {
  98749. for (var index = 0; index < this.blocks.length; index++) {
  98750. var block = this.blocks[index];
  98751. block.addEntry(entry);
  98752. }
  98753. return;
  98754. }
  98755. this._creationFunc(entry, this);
  98756. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  98757. this.createInnerBlocks();
  98758. }
  98759. };
  98760. /**
  98761. * Add an array of elements to this block
  98762. * @param entries defines the array of elements to add
  98763. */
  98764. OctreeBlock.prototype.addEntries = function (entries) {
  98765. for (var index = 0; index < entries.length; index++) {
  98766. var mesh = entries[index];
  98767. this.addEntry(mesh);
  98768. }
  98769. };
  98770. /**
  98771. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  98772. * @param frustumPlanes defines the frustum planes to test
  98773. * @param selection defines the array to store current content if selection is positive
  98774. * @param allowDuplicate defines if the selection array can contains duplicated entries
  98775. */
  98776. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  98777. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  98778. if (this.blocks) {
  98779. for (var index = 0; index < this.blocks.length; index++) {
  98780. var block = this.blocks[index];
  98781. block.select(frustumPlanes, selection, allowDuplicate);
  98782. }
  98783. return;
  98784. }
  98785. if (allowDuplicate) {
  98786. selection.concat(this.entries);
  98787. }
  98788. else {
  98789. selection.concatWithNoDuplicate(this.entries);
  98790. }
  98791. }
  98792. };
  98793. /**
  98794. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  98795. * @param sphereCenter defines the bounding sphere center
  98796. * @param sphereRadius defines the bounding sphere radius
  98797. * @param selection defines the array to store current content if selection is positive
  98798. * @param allowDuplicate defines if the selection array can contains duplicated entries
  98799. */
  98800. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  98801. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  98802. if (this.blocks) {
  98803. for (var index = 0; index < this.blocks.length; index++) {
  98804. var block = this.blocks[index];
  98805. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  98806. }
  98807. return;
  98808. }
  98809. if (allowDuplicate) {
  98810. selection.concat(this.entries);
  98811. }
  98812. else {
  98813. selection.concatWithNoDuplicate(this.entries);
  98814. }
  98815. }
  98816. };
  98817. /**
  98818. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  98819. * @param ray defines the ray to test with
  98820. * @param selection defines the array to store current content if selection is positive
  98821. */
  98822. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  98823. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  98824. if (this.blocks) {
  98825. for (var index = 0; index < this.blocks.length; index++) {
  98826. var block = this.blocks[index];
  98827. block.intersectsRay(ray, selection);
  98828. }
  98829. return;
  98830. }
  98831. selection.concatWithNoDuplicate(this.entries);
  98832. }
  98833. };
  98834. /**
  98835. * Subdivide the content into child blocks (this block will then be empty)
  98836. */
  98837. OctreeBlock.prototype.createInnerBlocks = function () {
  98838. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  98839. };
  98840. return OctreeBlock;
  98841. }());
  98842. BABYLON.OctreeBlock = OctreeBlock;
  98843. })(BABYLON || (BABYLON = {}));
  98844. //# sourceMappingURL=babylon.octreeBlock.js.map
  98845. var BABYLON;
  98846. (function (BABYLON) {
  98847. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  98848. if (maxCapacity === void 0) { maxCapacity = 64; }
  98849. if (maxDepth === void 0) { maxDepth = 2; }
  98850. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  98851. if (!component) {
  98852. component = new OctreeSceneComponent(this);
  98853. this._addComponent(component);
  98854. }
  98855. if (!this._selectionOctree) {
  98856. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  98857. }
  98858. var worldExtends = this.getWorldExtends();
  98859. // Update octree
  98860. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  98861. return this._selectionOctree;
  98862. };
  98863. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  98864. get: function () {
  98865. return this._selectionOctree;
  98866. },
  98867. enumerable: true,
  98868. configurable: true
  98869. });
  98870. /**
  98871. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  98872. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  98873. * @param maxCapacity defines the maximum size of each block (64 by default)
  98874. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  98875. * @returns the new octree
  98876. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  98877. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  98878. */
  98879. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  98880. if (maxCapacity === void 0) { maxCapacity = 64; }
  98881. if (maxDepth === void 0) { maxDepth = 2; }
  98882. var scene = this.getScene();
  98883. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  98884. if (!component) {
  98885. component = new OctreeSceneComponent(scene);
  98886. scene._addComponent(component);
  98887. }
  98888. if (!this._submeshesOctree) {
  98889. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  98890. }
  98891. this.computeWorldMatrix(true);
  98892. var boundingInfo = this.getBoundingInfo();
  98893. // Update octree
  98894. var bbox = boundingInfo.boundingBox;
  98895. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  98896. return this._submeshesOctree;
  98897. };
  98898. /**
  98899. * Defines the octree scene component responsible to manage any octrees
  98900. * in a given scene.
  98901. */
  98902. var OctreeSceneComponent = /** @class */ (function () {
  98903. /**
  98904. * Creates a new instance of the component for the given scene
  98905. * @param scene Defines the scene to register the component in
  98906. */
  98907. function OctreeSceneComponent(scene) {
  98908. /**
  98909. * The component name helpfull to identify the component in the list of scene components.
  98910. */
  98911. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  98912. /**
  98913. * Indicates if the meshes have been checked to make sure they are isEnabled()
  98914. */
  98915. this.checksIsEnabled = true;
  98916. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  98917. this.scene = scene;
  98918. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  98919. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  98920. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  98921. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  98922. }
  98923. /**
  98924. * Registers the component in a given scene
  98925. */
  98926. OctreeSceneComponent.prototype.register = function () {
  98927. var _this = this;
  98928. this.scene.onMeshRemovedObservable.add(function (mesh) {
  98929. var sceneOctree = _this.scene.selectionOctree;
  98930. if (sceneOctree !== undefined && sceneOctree !== null) {
  98931. var index = sceneOctree.dynamicContent.indexOf(mesh);
  98932. if (index !== -1) {
  98933. sceneOctree.dynamicContent.splice(index, 1);
  98934. }
  98935. }
  98936. });
  98937. this.scene.onMeshImportedObservable.add(function (mesh) {
  98938. var sceneOctree = _this.scene.selectionOctree;
  98939. if (sceneOctree !== undefined && sceneOctree !== null) {
  98940. sceneOctree.addMesh(mesh);
  98941. }
  98942. });
  98943. };
  98944. /**
  98945. * Return the list of active meshes
  98946. * @returns the list of active meshes
  98947. */
  98948. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  98949. if (this.scene._selectionOctree) {
  98950. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  98951. return selection;
  98952. }
  98953. return this.scene._getDefaultMeshCandidates();
  98954. };
  98955. /**
  98956. * Return the list of active sub meshes
  98957. * @param mesh The mesh to get the candidates sub meshes from
  98958. * @returns the list of active sub meshes
  98959. */
  98960. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  98961. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  98962. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  98963. return intersections;
  98964. }
  98965. return this.scene._getDefaultSubMeshCandidates(mesh);
  98966. };
  98967. /**
  98968. * Return the list of sub meshes intersecting with a given local ray
  98969. * @param mesh defines the mesh to find the submesh for
  98970. * @param localRay defines the ray in local space
  98971. * @returns the list of intersecting sub meshes
  98972. */
  98973. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  98974. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  98975. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  98976. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  98977. return intersections;
  98978. }
  98979. return this.scene._getDefaultSubMeshCandidates(mesh);
  98980. };
  98981. /**
  98982. * Return the list of sub meshes colliding with a collider
  98983. * @param mesh defines the mesh to find the submesh for
  98984. * @param collider defines the collider to evaluate the collision against
  98985. * @returns the list of colliding sub meshes
  98986. */
  98987. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  98988. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  98989. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  98990. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  98991. return intersections;
  98992. }
  98993. return this.scene._getDefaultSubMeshCandidates(mesh);
  98994. };
  98995. /**
  98996. * Rebuilds the elements related to this component in case of
  98997. * context lost for instance.
  98998. */
  98999. OctreeSceneComponent.prototype.rebuild = function () {
  99000. // Nothing to do here.
  99001. };
  99002. /**
  99003. * Disposes the component and the associated ressources.
  99004. */
  99005. OctreeSceneComponent.prototype.dispose = function () {
  99006. // Nothing to do here.
  99007. };
  99008. return OctreeSceneComponent;
  99009. }());
  99010. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  99011. })(BABYLON || (BABYLON = {}));
  99012. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  99013. var BABYLON;
  99014. (function (BABYLON) {
  99015. /**
  99016. * Postprocess used to generate anaglyphic rendering
  99017. */
  99018. var AnaglyphPostProcess = /** @class */ (function (_super) {
  99019. __extends(AnaglyphPostProcess, _super);
  99020. /**
  99021. * Creates a new AnaglyphPostProcess
  99022. * @param name defines postprocess name
  99023. * @param options defines creation options or target ratio scale
  99024. * @param rigCameras defines cameras using this postprocess
  99025. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  99026. * @param engine defines hosting engine
  99027. * @param reusable defines if the postprocess will be reused multiple times per frame
  99028. */
  99029. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  99030. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  99031. _this._passedProcess = rigCameras[0]._rigPostProcess;
  99032. _this.onApplyObservable.add(function (effect) {
  99033. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  99034. });
  99035. return _this;
  99036. }
  99037. return AnaglyphPostProcess;
  99038. }(BABYLON.PostProcess));
  99039. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  99040. })(BABYLON || (BABYLON = {}));
  99041. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  99042. var BABYLON;
  99043. (function (BABYLON) {
  99044. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  99045. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99046. });
  99047. /**
  99048. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  99049. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99050. */
  99051. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  99052. __extends(AnaglyphArcRotateCamera, _super);
  99053. /**
  99054. * Creates a new AnaglyphArcRotateCamera
  99055. * @param name defines camera name
  99056. * @param alpha defines alpha angle (in radians)
  99057. * @param beta defines beta angle (in radians)
  99058. * @param radius defines radius
  99059. * @param target defines camera target
  99060. * @param interaxialDistance defines distance between each color axis
  99061. * @param scene defines the hosting scene
  99062. */
  99063. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  99064. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99065. _this.interaxialDistance = interaxialDistance;
  99066. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99067. return _this;
  99068. }
  99069. /**
  99070. * Gets camera class name
  99071. * @returns AnaglyphArcRotateCamera
  99072. */
  99073. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  99074. return "AnaglyphArcRotateCamera";
  99075. };
  99076. return AnaglyphArcRotateCamera;
  99077. }(BABYLON.ArcRotateCamera));
  99078. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  99079. })(BABYLON || (BABYLON = {}));
  99080. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  99081. var BABYLON;
  99082. (function (BABYLON) {
  99083. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  99084. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99085. });
  99086. /**
  99087. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  99088. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99089. */
  99090. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  99091. __extends(AnaglyphFreeCamera, _super);
  99092. /**
  99093. * Creates a new AnaglyphFreeCamera
  99094. * @param name defines camera name
  99095. * @param position defines initial position
  99096. * @param interaxialDistance defines distance between each color axis
  99097. * @param scene defines the hosting scene
  99098. */
  99099. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  99100. var _this = _super.call(this, name, position, scene) || this;
  99101. _this.interaxialDistance = interaxialDistance;
  99102. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99103. return _this;
  99104. }
  99105. /**
  99106. * Gets camera class name
  99107. * @returns AnaglyphFreeCamera
  99108. */
  99109. AnaglyphFreeCamera.prototype.getClassName = function () {
  99110. return "AnaglyphFreeCamera";
  99111. };
  99112. return AnaglyphFreeCamera;
  99113. }(BABYLON.FreeCamera));
  99114. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  99115. })(BABYLON || (BABYLON = {}));
  99116. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  99117. var BABYLON;
  99118. (function (BABYLON) {
  99119. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  99120. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99121. });
  99122. /**
  99123. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  99124. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99125. */
  99126. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  99127. __extends(AnaglyphGamepadCamera, _super);
  99128. /**
  99129. * Creates a new AnaglyphGamepadCamera
  99130. * @param name defines camera name
  99131. * @param position defines initial position
  99132. * @param interaxialDistance defines distance between each color axis
  99133. * @param scene defines the hosting scene
  99134. */
  99135. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  99136. var _this = _super.call(this, name, position, scene) || this;
  99137. _this.interaxialDistance = interaxialDistance;
  99138. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99139. return _this;
  99140. }
  99141. /**
  99142. * Gets camera class name
  99143. * @returns AnaglyphGamepadCamera
  99144. */
  99145. AnaglyphGamepadCamera.prototype.getClassName = function () {
  99146. return "AnaglyphGamepadCamera";
  99147. };
  99148. return AnaglyphGamepadCamera;
  99149. }(BABYLON.GamepadCamera));
  99150. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  99151. })(BABYLON || (BABYLON = {}));
  99152. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  99153. var BABYLON;
  99154. (function (BABYLON) {
  99155. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  99156. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99157. });
  99158. /**
  99159. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  99160. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99161. */
  99162. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  99163. __extends(AnaglyphUniversalCamera, _super);
  99164. /**
  99165. * Creates a new AnaglyphUniversalCamera
  99166. * @param name defines camera name
  99167. * @param position defines initial position
  99168. * @param interaxialDistance defines distance between each color axis
  99169. * @param scene defines the hosting scene
  99170. */
  99171. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  99172. var _this = _super.call(this, name, position, scene) || this;
  99173. _this.interaxialDistance = interaxialDistance;
  99174. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99175. return _this;
  99176. }
  99177. /**
  99178. * Gets camera class name
  99179. * @returns AnaglyphUniversalCamera
  99180. */
  99181. AnaglyphUniversalCamera.prototype.getClassName = function () {
  99182. return "AnaglyphUniversalCamera";
  99183. };
  99184. return AnaglyphUniversalCamera;
  99185. }(BABYLON.UniversalCamera));
  99186. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  99187. })(BABYLON || (BABYLON = {}));
  99188. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  99189. var BABYLON;
  99190. (function (BABYLON) {
  99191. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  99192. __extends(StereoscopicInterlacePostProcess, _super);
  99193. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  99194. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  99195. _this._passedProcess = rigCameras[0]._rigPostProcess;
  99196. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  99197. _this.onSizeChangedObservable.add(function () {
  99198. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  99199. });
  99200. _this.onApplyObservable.add(function (effect) {
  99201. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  99202. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  99203. });
  99204. return _this;
  99205. }
  99206. return StereoscopicInterlacePostProcess;
  99207. }(BABYLON.PostProcess));
  99208. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  99209. })(BABYLON || (BABYLON = {}));
  99210. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  99211. var BABYLON;
  99212. (function (BABYLON) {
  99213. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  99214. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99215. });
  99216. /**
  99217. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  99218. * @see http://doc.babylonjs.com/features/cameras
  99219. */
  99220. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  99221. __extends(StereoscopicArcRotateCamera, _super);
  99222. /**
  99223. * Creates a new StereoscopicArcRotateCamera
  99224. * @param name defines camera name
  99225. * @param alpha defines alpha angle (in radians)
  99226. * @param beta defines beta angle (in radians)
  99227. * @param radius defines radius
  99228. * @param target defines camera target
  99229. * @param interaxialDistance defines distance between each color axis
  99230. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99231. * @param scene defines the hosting scene
  99232. */
  99233. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  99234. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99235. _this.interaxialDistance = interaxialDistance;
  99236. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99237. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99238. return _this;
  99239. }
  99240. /**
  99241. * Gets camera class name
  99242. * @returns StereoscopicArcRotateCamera
  99243. */
  99244. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  99245. return "StereoscopicArcRotateCamera";
  99246. };
  99247. return StereoscopicArcRotateCamera;
  99248. }(BABYLON.ArcRotateCamera));
  99249. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  99250. })(BABYLON || (BABYLON = {}));
  99251. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  99252. var BABYLON;
  99253. (function (BABYLON) {
  99254. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  99255. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99256. });
  99257. /**
  99258. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  99259. * @see http://doc.babylonjs.com/features/cameras
  99260. */
  99261. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  99262. __extends(StereoscopicFreeCamera, _super);
  99263. /**
  99264. * Creates a new StereoscopicFreeCamera
  99265. * @param name defines camera name
  99266. * @param position defines initial position
  99267. * @param interaxialDistance defines distance between each color axis
  99268. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99269. * @param scene defines the hosting scene
  99270. */
  99271. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99272. var _this = _super.call(this, name, position, scene) || this;
  99273. _this.interaxialDistance = interaxialDistance;
  99274. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99275. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99276. return _this;
  99277. }
  99278. /**
  99279. * Gets camera class name
  99280. * @returns StereoscopicFreeCamera
  99281. */
  99282. StereoscopicFreeCamera.prototype.getClassName = function () {
  99283. return "StereoscopicFreeCamera";
  99284. };
  99285. return StereoscopicFreeCamera;
  99286. }(BABYLON.FreeCamera));
  99287. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  99288. })(BABYLON || (BABYLON = {}));
  99289. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  99290. var BABYLON;
  99291. (function (BABYLON) {
  99292. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  99293. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99294. });
  99295. /**
  99296. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  99297. * @see http://doc.babylonjs.com/features/cameras
  99298. */
  99299. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  99300. __extends(StereoscopicGamepadCamera, _super);
  99301. /**
  99302. * Creates a new StereoscopicGamepadCamera
  99303. * @param name defines camera name
  99304. * @param position defines initial position
  99305. * @param interaxialDistance defines distance between each color axis
  99306. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99307. * @param scene defines the hosting scene
  99308. */
  99309. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99310. var _this = _super.call(this, name, position, scene) || this;
  99311. _this.interaxialDistance = interaxialDistance;
  99312. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99313. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99314. return _this;
  99315. }
  99316. /**
  99317. * Gets camera class name
  99318. * @returns StereoscopicGamepadCamera
  99319. */
  99320. StereoscopicGamepadCamera.prototype.getClassName = function () {
  99321. return "StereoscopicGamepadCamera";
  99322. };
  99323. return StereoscopicGamepadCamera;
  99324. }(BABYLON.GamepadCamera));
  99325. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  99326. })(BABYLON || (BABYLON = {}));
  99327. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  99328. var BABYLON;
  99329. (function (BABYLON) {
  99330. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  99331. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99332. });
  99333. /**
  99334. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  99335. * @see http://doc.babylonjs.com/features/cameras
  99336. */
  99337. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  99338. __extends(StereoscopicUniversalCamera, _super);
  99339. /**
  99340. * Creates a new StereoscopicUniversalCamera
  99341. * @param name defines camera name
  99342. * @param position defines initial position
  99343. * @param interaxialDistance defines distance between each color axis
  99344. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99345. * @param scene defines the hosting scene
  99346. */
  99347. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99348. var _this = _super.call(this, name, position, scene) || this;
  99349. _this.interaxialDistance = interaxialDistance;
  99350. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99351. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99352. return _this;
  99353. }
  99354. /**
  99355. * Gets camera class name
  99356. * @returns StereoscopicUniversalCamera
  99357. */
  99358. StereoscopicUniversalCamera.prototype.getClassName = function () {
  99359. return "StereoscopicUniversalCamera";
  99360. };
  99361. return StereoscopicUniversalCamera;
  99362. }(BABYLON.UniversalCamera));
  99363. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  99364. })(BABYLON || (BABYLON = {}));
  99365. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  99366. var BABYLON;
  99367. (function (BABYLON) {
  99368. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  99369. __extends(VRDistortionCorrectionPostProcess, _super);
  99370. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  99371. var _this = _super.call(this, name, "vrDistortionCorrection", [
  99372. 'LensCenter',
  99373. 'Scale',
  99374. 'ScaleIn',
  99375. 'HmdWarpParam'
  99376. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  99377. _this._isRightEye = isRightEye;
  99378. _this._distortionFactors = vrMetrics.distortionK;
  99379. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  99380. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  99381. _this.adaptScaleToCurrentViewport = true;
  99382. _this.onSizeChangedObservable.add(function () {
  99383. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  99384. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  99385. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  99386. });
  99387. _this.onApplyObservable.add(function (effect) {
  99388. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  99389. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  99390. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  99391. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  99392. });
  99393. return _this;
  99394. }
  99395. return VRDistortionCorrectionPostProcess;
  99396. }(BABYLON.PostProcess));
  99397. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  99398. })(BABYLON || (BABYLON = {}));
  99399. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  99400. var BABYLON;
  99401. (function (BABYLON) {
  99402. /**
  99403. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  99404. * Screen rotation is taken into account.
  99405. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99406. */
  99407. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  99408. /**
  99409. * Instantiates a new input
  99410. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99411. */
  99412. function FreeCameraDeviceOrientationInput() {
  99413. var _this = this;
  99414. this._screenOrientationAngle = 0;
  99415. this._screenQuaternion = new BABYLON.Quaternion();
  99416. this._alpha = 0;
  99417. this._beta = 0;
  99418. this._gamma = 0;
  99419. this._orientationChanged = function () {
  99420. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  99421. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  99422. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  99423. };
  99424. this._deviceOrientation = function (evt) {
  99425. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  99426. _this._beta = evt.beta !== null ? evt.beta : 0;
  99427. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  99428. };
  99429. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  99430. this._orientationChanged();
  99431. }
  99432. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  99433. /**
  99434. * Define the camera controlled by the input.
  99435. */
  99436. get: function () {
  99437. return this._camera;
  99438. },
  99439. set: function (camera) {
  99440. this._camera = camera;
  99441. if (this._camera != null && !this._camera.rotationQuaternion) {
  99442. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  99443. }
  99444. },
  99445. enumerable: true,
  99446. configurable: true
  99447. });
  99448. /**
  99449. * Attach the input controls to a specific dom element to get the input from.
  99450. * @param element Defines the element the controls should be listened from
  99451. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  99452. */
  99453. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  99454. window.addEventListener("orientationchange", this._orientationChanged);
  99455. window.addEventListener("deviceorientation", this._deviceOrientation);
  99456. //In certain cases, the attach control is called AFTER orientation was changed,
  99457. //So this is needed.
  99458. this._orientationChanged();
  99459. };
  99460. /**
  99461. * Detach the current controls from the specified dom element.
  99462. * @param element Defines the element to stop listening the inputs from
  99463. */
  99464. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  99465. window.removeEventListener("orientationchange", this._orientationChanged);
  99466. window.removeEventListener("deviceorientation", this._deviceOrientation);
  99467. };
  99468. /**
  99469. * Update the current camera state depending on the inputs that have been used this frame.
  99470. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  99471. */
  99472. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  99473. //if no device orientation provided, don't update the rotation.
  99474. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  99475. if (!this._alpha)
  99476. return;
  99477. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  99478. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  99479. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  99480. //Mirror on XY Plane
  99481. this._camera.rotationQuaternion.z *= -1;
  99482. this._camera.rotationQuaternion.w *= -1;
  99483. };
  99484. /**
  99485. * Gets the class name of the current intput.
  99486. * @returns the class name
  99487. */
  99488. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  99489. return "FreeCameraDeviceOrientationInput";
  99490. };
  99491. /**
  99492. * Get the friendly name associated with the input class.
  99493. * @returns the input friendly name
  99494. */
  99495. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  99496. return "deviceOrientation";
  99497. };
  99498. return FreeCameraDeviceOrientationInput;
  99499. }());
  99500. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  99501. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  99502. })(BABYLON || (BABYLON = {}));
  99503. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  99504. var BABYLON;
  99505. (function (BABYLON) {
  99506. /**
  99507. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  99508. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99509. */
  99510. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  99511. /**
  99512. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  99513. */
  99514. function ArcRotateCameraVRDeviceOrientationInput() {
  99515. /**
  99516. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  99517. */
  99518. this.alphaCorrection = 1;
  99519. /**
  99520. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  99521. */
  99522. this.betaCorrection = 1;
  99523. /**
  99524. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  99525. */
  99526. this.gammaCorrection = 1;
  99527. this._alpha = 0;
  99528. this._gamma = 0;
  99529. this._dirty = false;
  99530. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  99531. }
  99532. /**
  99533. * Attach the input controls to a specific dom element to get the input from.
  99534. * @param element Defines the element the controls should be listened from
  99535. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  99536. */
  99537. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  99538. this.camera.attachControl(element, noPreventDefault);
  99539. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  99540. };
  99541. /** @hidden */
  99542. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  99543. if (evt.alpha !== null) {
  99544. this._alpha = +evt.alpha | 0;
  99545. }
  99546. if (evt.gamma !== null) {
  99547. this._gamma = +evt.gamma | 0;
  99548. }
  99549. this._dirty = true;
  99550. };
  99551. /**
  99552. * Update the current camera state depending on the inputs that have been used this frame.
  99553. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  99554. */
  99555. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  99556. if (this._dirty) {
  99557. this._dirty = false;
  99558. if (this._gamma < 0) {
  99559. this._gamma = 180 + this._gamma;
  99560. }
  99561. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  99562. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  99563. }
  99564. };
  99565. /**
  99566. * Detach the current controls from the specified dom element.
  99567. * @param element Defines the element to stop listening the inputs from
  99568. */
  99569. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  99570. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  99571. };
  99572. /**
  99573. * Gets the class name of the current intput.
  99574. * @returns the class name
  99575. */
  99576. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  99577. return "ArcRotateCameraVRDeviceOrientationInput";
  99578. };
  99579. /**
  99580. * Get the friendly name associated with the input class.
  99581. * @returns the input friendly name
  99582. */
  99583. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  99584. return "VRDeviceOrientation";
  99585. };
  99586. return ArcRotateCameraVRDeviceOrientationInput;
  99587. }());
  99588. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  99589. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  99590. })(BABYLON || (BABYLON = {}));
  99591. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  99592. var BABYLON;
  99593. (function (BABYLON) {
  99594. /**
  99595. * This represents all the required metrics to create a VR camera.
  99596. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  99597. */
  99598. var VRCameraMetrics = /** @class */ (function () {
  99599. function VRCameraMetrics() {
  99600. /**
  99601. * Define if the current vr camera should compensate the distortion of the lense or not.
  99602. */
  99603. this.compensateDistortion = true;
  99604. }
  99605. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  99606. /**
  99607. * Gets the rendering aspect ratio based on the provided resolutions.
  99608. */
  99609. get: function () {
  99610. return this.hResolution / (2 * this.vResolution);
  99611. },
  99612. enumerable: true,
  99613. configurable: true
  99614. });
  99615. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  99616. /**
  99617. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  99618. */
  99619. get: function () {
  99620. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  99621. },
  99622. enumerable: true,
  99623. configurable: true
  99624. });
  99625. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  99626. /**
  99627. * @hidden
  99628. */
  99629. get: function () {
  99630. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  99631. var h = (4 * meters) / this.hScreenSize;
  99632. return BABYLON.Matrix.Translation(h, 0, 0);
  99633. },
  99634. enumerable: true,
  99635. configurable: true
  99636. });
  99637. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  99638. /**
  99639. * @hidden
  99640. */
  99641. get: function () {
  99642. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  99643. var h = (4 * meters) / this.hScreenSize;
  99644. return BABYLON.Matrix.Translation(-h, 0, 0);
  99645. },
  99646. enumerable: true,
  99647. configurable: true
  99648. });
  99649. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  99650. /**
  99651. * @hidden
  99652. */
  99653. get: function () {
  99654. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  99655. },
  99656. enumerable: true,
  99657. configurable: true
  99658. });
  99659. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  99660. /**
  99661. * @hidden
  99662. */
  99663. get: function () {
  99664. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  99665. },
  99666. enumerable: true,
  99667. configurable: true
  99668. });
  99669. /**
  99670. * Get the default VRMetrics based on the most generic setup.
  99671. * @returns the default vr metrics
  99672. */
  99673. VRCameraMetrics.GetDefault = function () {
  99674. var result = new VRCameraMetrics();
  99675. result.hResolution = 1280;
  99676. result.vResolution = 800;
  99677. result.hScreenSize = 0.149759993;
  99678. result.vScreenSize = 0.0935999975;
  99679. result.vScreenCenter = 0.0467999987;
  99680. result.eyeToScreenDistance = 0.0410000011;
  99681. result.lensSeparationDistance = 0.0635000020;
  99682. result.interpupillaryDistance = 0.0640000030;
  99683. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  99684. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  99685. result.postProcessScaleFactor = 1.714605507808412;
  99686. result.lensCenterOffset = 0.151976421;
  99687. return result;
  99688. };
  99689. return VRCameraMetrics;
  99690. }());
  99691. BABYLON.VRCameraMetrics = VRCameraMetrics;
  99692. })(BABYLON || (BABYLON = {}));
  99693. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  99694. var BABYLON;
  99695. (function (BABYLON) {
  99696. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  99697. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99698. });
  99699. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  99700. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99701. });
  99702. /**
  99703. * This represents a WebVR camera.
  99704. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  99705. * @example http://doc.babylonjs.com/how_to/webvr_camera
  99706. */
  99707. var WebVRFreeCamera = /** @class */ (function (_super) {
  99708. __extends(WebVRFreeCamera, _super);
  99709. /**
  99710. * Instantiates a WebVRFreeCamera.
  99711. * @param name The name of the WebVRFreeCamera
  99712. * @param position The starting anchor position for the camera
  99713. * @param scene The scene the camera belongs to
  99714. * @param webVROptions a set of customizable options for the webVRCamera
  99715. */
  99716. function WebVRFreeCamera(name, position, scene, webVROptions) {
  99717. if (webVROptions === void 0) { webVROptions = {}; }
  99718. var _this = _super.call(this, name, position, scene) || this;
  99719. _this.webVROptions = webVROptions;
  99720. /**
  99721. * @hidden
  99722. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  99723. */
  99724. _this._vrDevice = null;
  99725. /**
  99726. * The rawPose of the vrDevice.
  99727. */
  99728. _this.rawPose = null;
  99729. _this._specsVersion = "1.1";
  99730. _this._attached = false;
  99731. _this._descendants = [];
  99732. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  99733. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  99734. /** @hidden */
  99735. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  99736. _this._standingMatrix = null;
  99737. /**
  99738. * Represents device position in babylon space.
  99739. */
  99740. _this.devicePosition = BABYLON.Vector3.Zero();
  99741. /**
  99742. * Represents device rotation in babylon space.
  99743. */
  99744. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  99745. /**
  99746. * The scale of the device to be used when translating from device space to babylon space.
  99747. */
  99748. _this.deviceScaleFactor = 1;
  99749. _this._deviceToWorld = BABYLON.Matrix.Identity();
  99750. _this._worldToDevice = BABYLON.Matrix.Identity();
  99751. /**
  99752. * References to the webVR controllers for the vrDevice.
  99753. */
  99754. _this.controllers = [];
  99755. /**
  99756. * Emits an event when a controller is attached.
  99757. */
  99758. _this.onControllersAttachedObservable = new BABYLON.Observable();
  99759. /**
  99760. * Emits an event when a controller's mesh has been loaded;
  99761. */
  99762. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  99763. /**
  99764. * Emits an event when the HMD's pose has been updated.
  99765. */
  99766. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  99767. _this._poseSet = false;
  99768. /**
  99769. * If the rig cameras be used as parent instead of this camera.
  99770. */
  99771. _this.rigParenting = true;
  99772. _this._defaultHeight = undefined;
  99773. _this._htmlElementAttached = null;
  99774. _this._detachIfAttached = function () {
  99775. var vrDisplay = _this.getEngine().getVRDevice();
  99776. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  99777. _this.detachControl(_this._htmlElementAttached);
  99778. }
  99779. };
  99780. _this._workingVector = BABYLON.Vector3.Zero();
  99781. _this._oneVector = BABYLON.Vector3.One();
  99782. _this._workingMatrix = BABYLON.Matrix.Identity();
  99783. _this._tmpMatrix = new BABYLON.Matrix();
  99784. _this._cache.position = BABYLON.Vector3.Zero();
  99785. if (webVROptions.defaultHeight) {
  99786. _this._defaultHeight = webVROptions.defaultHeight;
  99787. _this.position.y = _this._defaultHeight;
  99788. }
  99789. _this.minZ = 0.1;
  99790. //legacy support - the compensation boolean was removed.
  99791. if (arguments.length === 5) {
  99792. _this.webVROptions = arguments[4];
  99793. }
  99794. // default webVR options
  99795. if (_this.webVROptions.trackPosition == undefined) {
  99796. _this.webVROptions.trackPosition = true;
  99797. }
  99798. if (_this.webVROptions.controllerMeshes == undefined) {
  99799. _this.webVROptions.controllerMeshes = true;
  99800. }
  99801. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  99802. _this.webVROptions.defaultLightingOnControllers = true;
  99803. }
  99804. _this.rotationQuaternion = new BABYLON.Quaternion();
  99805. if (_this.webVROptions && _this.webVROptions.positionScale) {
  99806. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  99807. }
  99808. //enable VR
  99809. var engine = _this.getEngine();
  99810. _this._onVREnabled = function (success) { if (success) {
  99811. _this.initControllers();
  99812. } };
  99813. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  99814. engine.initWebVR().add(function (event) {
  99815. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  99816. return;
  99817. }
  99818. _this._vrDevice = event.vrDisplay;
  99819. //reset the rig parameters.
  99820. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  99821. if (_this._attached) {
  99822. _this.getEngine().enableVR();
  99823. }
  99824. });
  99825. if (typeof (VRFrameData) !== "undefined")
  99826. _this._frameData = new VRFrameData();
  99827. /**
  99828. * The idea behind the following lines:
  99829. * objects that have the camera as parent should actually have the rig cameras as a parent.
  99830. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  99831. * the second will not show it correctly.
  99832. *
  99833. * To solve this - each object that has the camera as parent will be added to a protected array.
  99834. * When the rig camera renders, it will take this array and set all of those to be its children.
  99835. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  99836. * Amazing!
  99837. */
  99838. scene.onBeforeCameraRenderObservable.add(function (camera) {
  99839. if (camera.parent === _this && _this.rigParenting) {
  99840. _this._descendants = _this.getDescendants(true, function (n) {
  99841. // don't take the cameras or the controllers!
  99842. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  99843. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  99844. return !isController && !isRigCamera;
  99845. });
  99846. _this._descendants.forEach(function (node) {
  99847. node.parent = camera;
  99848. });
  99849. }
  99850. });
  99851. scene.onAfterCameraRenderObservable.add(function (camera) {
  99852. if (camera.parent === _this && _this.rigParenting) {
  99853. _this._descendants.forEach(function (node) {
  99854. node.parent = _this;
  99855. });
  99856. }
  99857. });
  99858. return _this;
  99859. }
  99860. /**
  99861. * Gets the device distance from the ground in meters.
  99862. * @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.
  99863. */
  99864. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  99865. if (this._standingMatrix) {
  99866. // Add standing matrix offset to get real offset from ground in room
  99867. this._standingMatrix.getTranslationToRef(this._workingVector);
  99868. return this._deviceRoomPosition.y + this._workingVector.y;
  99869. }
  99870. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  99871. return this._defaultHeight || 0;
  99872. };
  99873. /**
  99874. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  99875. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  99876. */
  99877. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  99878. var _this = this;
  99879. if (callback === void 0) { callback = function (bool) { }; }
  99880. // Use standing matrix if available
  99881. this.getEngine().initWebVRAsync().then(function (result) {
  99882. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  99883. callback(false);
  99884. }
  99885. else {
  99886. _this._standingMatrix = new BABYLON.Matrix();
  99887. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  99888. if (!_this.getScene().useRightHandedSystem) {
  99889. [2, 6, 8, 9, 14].forEach(function (num) {
  99890. if (_this._standingMatrix) {
  99891. _this._standingMatrix.m[num] *= -1;
  99892. }
  99893. });
  99894. }
  99895. callback(true);
  99896. }
  99897. });
  99898. };
  99899. /**
  99900. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  99901. * @returns A promise with a boolean set to if the standing matrix is supported.
  99902. */
  99903. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  99904. var _this = this;
  99905. return new Promise(function (res, rej) {
  99906. _this.useStandingMatrix(function (supported) {
  99907. res(supported);
  99908. });
  99909. });
  99910. };
  99911. /**
  99912. * Disposes the camera
  99913. */
  99914. WebVRFreeCamera.prototype.dispose = function () {
  99915. this._detachIfAttached();
  99916. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  99917. if (this._updateCacheWhenTrackingDisabledObserver) {
  99918. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  99919. }
  99920. _super.prototype.dispose.call(this);
  99921. };
  99922. /**
  99923. * Gets a vrController by name.
  99924. * @param name The name of the controller to retreive
  99925. * @returns the controller matching the name specified or null if not found
  99926. */
  99927. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  99928. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  99929. var gp = _a[_i];
  99930. if (gp.hand === name) {
  99931. return gp;
  99932. }
  99933. }
  99934. return null;
  99935. };
  99936. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  99937. /**
  99938. * The controller corrisponding to the users left hand.
  99939. */
  99940. get: function () {
  99941. if (!this._leftController) {
  99942. this._leftController = this.getControllerByName("left");
  99943. }
  99944. return this._leftController;
  99945. },
  99946. enumerable: true,
  99947. configurable: true
  99948. });
  99949. ;
  99950. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  99951. /**
  99952. * The controller corrisponding to the users right hand.
  99953. */
  99954. get: function () {
  99955. if (!this._rightController) {
  99956. this._rightController = this.getControllerByName("right");
  99957. }
  99958. return this._rightController;
  99959. },
  99960. enumerable: true,
  99961. configurable: true
  99962. });
  99963. ;
  99964. /**
  99965. * Casts a ray forward from the vrCamera's gaze.
  99966. * @param length Length of the ray (default: 100)
  99967. * @returns the ray corrisponding to the gaze
  99968. */
  99969. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  99970. if (length === void 0) { length = 100; }
  99971. if (this.leftCamera) {
  99972. // Use left eye to avoid computation to compute center on every call
  99973. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  99974. }
  99975. else {
  99976. return _super.prototype.getForwardRay.call(this, length);
  99977. }
  99978. };
  99979. /**
  99980. * @hidden
  99981. * Updates the camera based on device's frame data
  99982. */
  99983. WebVRFreeCamera.prototype._checkInputs = function () {
  99984. if (this._vrDevice && this._vrDevice.isPresenting) {
  99985. this._vrDevice.getFrameData(this._frameData);
  99986. this.updateFromDevice(this._frameData.pose);
  99987. }
  99988. _super.prototype._checkInputs.call(this);
  99989. };
  99990. /**
  99991. * Updates the poseControlled values based on the input device pose.
  99992. * @param poseData Pose coming from the device
  99993. */
  99994. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  99995. if (poseData && poseData.orientation) {
  99996. this.rawPose = poseData;
  99997. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  99998. if (this.getScene().useRightHandedSystem) {
  99999. this._deviceRoomRotationQuaternion.z *= -1;
  100000. this._deviceRoomRotationQuaternion.w *= -1;
  100001. }
  100002. if (this.webVROptions.trackPosition && this.rawPose.position) {
  100003. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  100004. if (this.getScene().useRightHandedSystem) {
  100005. this._deviceRoomPosition.z *= -1;
  100006. }
  100007. }
  100008. this._poseSet = true;
  100009. }
  100010. };
  100011. /**
  100012. * WebVR's attach control will start broadcasting frames to the device.
  100013. * Note that in certain browsers (chrome for example) this function must be called
  100014. * within a user-interaction callback. Example:
  100015. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  100016. *
  100017. * @param element html element to attach the vrDevice to
  100018. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  100019. */
  100020. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  100021. _super.prototype.attachControl.call(this, element, noPreventDefault);
  100022. this._attached = true;
  100023. this._htmlElementAttached = element;
  100024. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  100025. if (this._vrDevice) {
  100026. this.getEngine().enableVR();
  100027. }
  100028. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  100029. };
  100030. /**
  100031. * Detaches the camera from the html element and disables VR
  100032. *
  100033. * @param element html element to detach from
  100034. */
  100035. WebVRFreeCamera.prototype.detachControl = function (element) {
  100036. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  100037. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  100038. _super.prototype.detachControl.call(this, element);
  100039. this._attached = false;
  100040. this.getEngine().disableVR();
  100041. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  100042. };
  100043. /**
  100044. * @returns the name of this class
  100045. */
  100046. WebVRFreeCamera.prototype.getClassName = function () {
  100047. return "WebVRFreeCamera";
  100048. };
  100049. /**
  100050. * Calls resetPose on the vrDisplay
  100051. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  100052. */
  100053. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  100054. //uses the vrDisplay's "resetPose()".
  100055. //pitch and roll won't be affected.
  100056. this._vrDevice.resetPose();
  100057. };
  100058. /**
  100059. * @hidden
  100060. * Updates the rig cameras (left and right eye)
  100061. */
  100062. WebVRFreeCamera.prototype._updateRigCameras = function () {
  100063. var camLeft = this._rigCameras[0];
  100064. var camRight = this._rigCameras[1];
  100065. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  100066. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  100067. camLeft.position.copyFrom(this._deviceRoomPosition);
  100068. camRight.position.copyFrom(this._deviceRoomPosition);
  100069. };
  100070. // Remove translation from 6dof headset if trackposition is set to false
  100071. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  100072. if (isViewMatrix === void 0) { isViewMatrix = false; }
  100073. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  100074. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  100075. if (!isViewMatrix) {
  100076. this._tmpMatrix.invert();
  100077. }
  100078. this._tmpMatrix.multiplyToRef(matrix, matrix);
  100079. }
  100080. };
  100081. /**
  100082. * @hidden
  100083. * Updates the cached values of the camera
  100084. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  100085. */
  100086. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  100087. var _this = this;
  100088. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  100089. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  100090. if (!this.updateCacheCalled) {
  100091. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  100092. this.updateCacheCalled = true;
  100093. this.update();
  100094. }
  100095. // Set working vector to the device position in room space rotated by the new rotation
  100096. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  100097. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  100098. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  100099. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  100100. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  100101. // Add translation from anchor position
  100102. this._deviceToWorld.getTranslationToRef(this._workingVector);
  100103. this._workingVector.addInPlace(this.position);
  100104. this._workingVector.subtractInPlace(this._cache.position);
  100105. this._deviceToWorld.setTranslation(this._workingVector);
  100106. // Set an inverted matrix to be used when updating the camera
  100107. this._deviceToWorld.invertToRef(this._worldToDevice);
  100108. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  100109. this.controllers.forEach(function (controller) {
  100110. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  100111. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  100112. controller.update();
  100113. });
  100114. }
  100115. if (!ignoreParentClass) {
  100116. _super.prototype._updateCache.call(this);
  100117. }
  100118. this.updateCacheCalled = false;
  100119. };
  100120. /**
  100121. * @hidden
  100122. * Get current device position in babylon world
  100123. */
  100124. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  100125. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  100126. };
  100127. /**
  100128. * Updates the current device position and rotation in the babylon world
  100129. */
  100130. WebVRFreeCamera.prototype.update = function () {
  100131. this._computeDevicePosition();
  100132. // Get current device rotation in babylon world
  100133. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  100134. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  100135. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  100136. if (this._poseSet) {
  100137. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  100138. }
  100139. _super.prototype.update.call(this);
  100140. };
  100141. /**
  100142. * @hidden
  100143. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  100144. * @returns an identity matrix
  100145. */
  100146. WebVRFreeCamera.prototype._getViewMatrix = function () {
  100147. return BABYLON.Matrix.Identity();
  100148. };
  100149. /**
  100150. * This function is called by the two RIG cameras.
  100151. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  100152. */
  100153. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  100154. var _this = this;
  100155. // Update the parent camera prior to using a child camera to avoid desynchronization
  100156. var parentCamera = this._cameraRigParams["parentCamera"];
  100157. parentCamera._updateCache();
  100158. //WebVR 1.1
  100159. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  100160. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  100161. if (!this.getScene().useRightHandedSystem) {
  100162. [2, 6, 8, 9, 14].forEach(function (num) {
  100163. _this._webvrViewMatrix.m[num] *= -1;
  100164. });
  100165. }
  100166. // update the camera rotation matrix
  100167. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  100168. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  100169. // Computing target and final matrix
  100170. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  100171. // should the view matrix be updated with scale and position offset?
  100172. if (parentCamera.deviceScaleFactor !== 1) {
  100173. this._webvrViewMatrix.invert();
  100174. // scale the position, if set
  100175. if (parentCamera.deviceScaleFactor) {
  100176. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  100177. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  100178. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  100179. }
  100180. this._webvrViewMatrix.invert();
  100181. }
  100182. // Remove translation from 6dof headset if trackposition is set to false
  100183. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  100184. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  100185. // Compute global position
  100186. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  100187. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  100188. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  100189. this._workingMatrix.getTranslationToRef(this._globalPosition);
  100190. this._markSyncedWithParent();
  100191. return this._webvrViewMatrix;
  100192. };
  100193. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  100194. var _this = this;
  100195. var parentCamera = this.parent;
  100196. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  100197. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  100198. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  100199. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  100200. //babylon compatible matrix
  100201. if (!this.getScene().useRightHandedSystem) {
  100202. [8, 9, 10, 11].forEach(function (num) {
  100203. _this._projectionMatrix.m[num] *= -1;
  100204. });
  100205. }
  100206. return this._projectionMatrix;
  100207. };
  100208. /**
  100209. * Initializes the controllers and their meshes
  100210. */
  100211. WebVRFreeCamera.prototype.initControllers = function () {
  100212. var _this = this;
  100213. this.controllers = [];
  100214. var manager = this.getScene().gamepadManager;
  100215. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  100216. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  100217. var webVrController = gamepad;
  100218. if (webVrController.defaultModel) {
  100219. webVrController.defaultModel.setEnabled(false);
  100220. }
  100221. if (webVrController.hand === "right") {
  100222. _this._rightController = null;
  100223. }
  100224. if (webVrController.hand === "left") {
  100225. _this._leftController = null;
  100226. }
  100227. var controllerIndex = _this.controllers.indexOf(webVrController);
  100228. if (controllerIndex !== -1) {
  100229. _this.controllers.splice(controllerIndex, 1);
  100230. }
  100231. }
  100232. });
  100233. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  100234. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  100235. var webVrController_1 = gamepad;
  100236. if (!_this.webVROptions.trackPosition) {
  100237. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  100238. // Cache must be updated before rendering controllers to avoid them being one frame behind
  100239. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  100240. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  100241. _this._updateCache();
  100242. });
  100243. }
  100244. }
  100245. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  100246. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  100247. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  100248. if (_this.webVROptions.controllerMeshes) {
  100249. if (webVrController_1.defaultModel) {
  100250. webVrController_1.defaultModel.setEnabled(true);
  100251. }
  100252. else {
  100253. // Load the meshes
  100254. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  100255. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  100256. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  100257. if (_this.webVROptions.defaultLightingOnControllers) {
  100258. if (!_this._lightOnControllers) {
  100259. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  100260. }
  100261. var activateLightOnSubMeshes_1 = function (mesh, light) {
  100262. var children = mesh.getChildren();
  100263. if (children && children.length !== 0) {
  100264. children.forEach(function (mesh) {
  100265. light.includedOnlyMeshes.push(mesh);
  100266. activateLightOnSubMeshes_1(mesh, light);
  100267. });
  100268. }
  100269. };
  100270. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  100271. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  100272. }
  100273. });
  100274. }
  100275. }
  100276. webVrController_1.attachToPoseControlledCamera(_this);
  100277. // since this is async - sanity check. Is the controller already stored?
  100278. if (_this.controllers.indexOf(webVrController_1) === -1) {
  100279. //add to the controllers array
  100280. _this.controllers.push(webVrController_1);
  100281. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  100282. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  100283. // So we're overriding setting left & right manually to be sure
  100284. var firstViveWandDetected = false;
  100285. for (var i = 0; i < _this.controllers.length; i++) {
  100286. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  100287. if (!firstViveWandDetected) {
  100288. firstViveWandDetected = true;
  100289. _this.controllers[i].hand = "left";
  100290. }
  100291. else {
  100292. _this.controllers[i].hand = "right";
  100293. }
  100294. }
  100295. }
  100296. //did we find enough controllers? Great! let the developer know.
  100297. if (_this.controllers.length >= 2) {
  100298. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  100299. }
  100300. }
  100301. }
  100302. });
  100303. };
  100304. return WebVRFreeCamera;
  100305. }(BABYLON.FreeCamera));
  100306. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  100307. })(BABYLON || (BABYLON = {}));
  100308. //# sourceMappingURL=babylon.webVRCamera.js.map
  100309. var BABYLON;
  100310. (function (BABYLON) {
  100311. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  100312. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  100313. });
  100314. // We're mainly based on the logic defined into the FreeCamera code
  100315. /**
  100316. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  100317. * being tilted forward or back and left or right.
  100318. */
  100319. var DeviceOrientationCamera = /** @class */ (function (_super) {
  100320. __extends(DeviceOrientationCamera, _super);
  100321. /**
  100322. * Creates a new device orientation camera
  100323. * @param name The name of the camera
  100324. * @param position The start position camera
  100325. * @param scene The scene the camera belongs to
  100326. */
  100327. function DeviceOrientationCamera(name, position, scene) {
  100328. var _this = _super.call(this, name, position, scene) || this;
  100329. _this._quaternionCache = new BABYLON.Quaternion();
  100330. _this.inputs.addDeviceOrientation();
  100331. return _this;
  100332. }
  100333. /**
  100334. * Gets the current instance class name ("DeviceOrientationCamera").
  100335. * This helps avoiding instanceof at run time.
  100336. * @returns the class name
  100337. */
  100338. DeviceOrientationCamera.prototype.getClassName = function () {
  100339. return "DeviceOrientationCamera";
  100340. };
  100341. /**
  100342. * @hidden
  100343. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  100344. */
  100345. DeviceOrientationCamera.prototype._checkInputs = function () {
  100346. _super.prototype._checkInputs.call(this);
  100347. this._quaternionCache.copyFrom(this.rotationQuaternion);
  100348. if (this._initialQuaternion) {
  100349. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  100350. }
  100351. };
  100352. /**
  100353. * Reset the camera to its default orientation on the specified axis only.
  100354. * @param axis The axis to reset
  100355. */
  100356. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  100357. var _this = this;
  100358. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  100359. //can only work if this camera has a rotation quaternion already.
  100360. if (!this.rotationQuaternion)
  100361. return;
  100362. if (!this._initialQuaternion) {
  100363. this._initialQuaternion = new BABYLON.Quaternion();
  100364. }
  100365. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  100366. ['x', 'y', 'z'].forEach(function (axisName) {
  100367. if (!axis[axisName]) {
  100368. _this._initialQuaternion[axisName] = 0;
  100369. }
  100370. else {
  100371. _this._initialQuaternion[axisName] *= -1;
  100372. }
  100373. });
  100374. this._initialQuaternion.normalize();
  100375. //force rotation update
  100376. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  100377. };
  100378. return DeviceOrientationCamera;
  100379. }(BABYLON.FreeCamera));
  100380. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  100381. })(BABYLON || (BABYLON = {}));
  100382. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  100383. var BABYLON;
  100384. (function (BABYLON) {
  100385. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  100386. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  100387. });
  100388. /**
  100389. * Camera used to simulate VR rendering (based on FreeCamera)
  100390. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100391. */
  100392. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  100393. __extends(VRDeviceOrientationFreeCamera, _super);
  100394. /**
  100395. * Creates a new VRDeviceOrientationFreeCamera
  100396. * @param name defines camera name
  100397. * @param position defines the start position of the camera
  100398. * @param scene defines the scene the camera belongs to
  100399. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100400. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100401. */
  100402. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  100403. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100404. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100405. var _this = _super.call(this, name, position, scene) || this;
  100406. vrCameraMetrics.compensateDistortion = compensateDistortion;
  100407. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  100408. return _this;
  100409. }
  100410. /**
  100411. * Gets camera class name
  100412. * @returns VRDeviceOrientationFreeCamera
  100413. */
  100414. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  100415. return "VRDeviceOrientationFreeCamera";
  100416. };
  100417. return VRDeviceOrientationFreeCamera;
  100418. }(BABYLON.DeviceOrientationCamera));
  100419. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  100420. })(BABYLON || (BABYLON = {}));
  100421. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  100422. var BABYLON;
  100423. (function (BABYLON) {
  100424. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  100425. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  100426. });
  100427. /**
  100428. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  100429. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100430. */
  100431. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  100432. __extends(VRDeviceOrientationArcRotateCamera, _super);
  100433. /**
  100434. * Creates a new VRDeviceOrientationArcRotateCamera
  100435. * @param name defines camera name
  100436. * @param alpha defines the camera rotation along the logitudinal axis
  100437. * @param beta defines the camera rotation along the latitudinal axis
  100438. * @param radius defines the camera distance from its target
  100439. * @param target defines the camera target
  100440. * @param scene defines the scene the camera belongs to
  100441. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100442. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100443. */
  100444. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  100445. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100446. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100447. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  100448. vrCameraMetrics.compensateDistortion = compensateDistortion;
  100449. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  100450. _this.inputs.addVRDeviceOrientation();
  100451. return _this;
  100452. }
  100453. /**
  100454. * Gets camera class name
  100455. * @returns VRDeviceOrientationArcRotateCamera
  100456. */
  100457. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  100458. return "VRDeviceOrientationArcRotateCamera";
  100459. };
  100460. return VRDeviceOrientationArcRotateCamera;
  100461. }(BABYLON.ArcRotateCamera));
  100462. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  100463. })(BABYLON || (BABYLON = {}));
  100464. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  100465. var BABYLON;
  100466. (function (BABYLON) {
  100467. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  100468. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  100469. });
  100470. /**
  100471. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  100472. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100473. */
  100474. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  100475. __extends(VRDeviceOrientationGamepadCamera, _super);
  100476. /**
  100477. * Creates a new VRDeviceOrientationGamepadCamera
  100478. * @param name defines camera name
  100479. * @param position defines the start position of the camera
  100480. * @param scene defines the scene the camera belongs to
  100481. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100482. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100483. */
  100484. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  100485. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100486. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100487. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  100488. _this.inputs.addGamepad();
  100489. return _this;
  100490. }
  100491. /**
  100492. * Gets camera class name
  100493. * @returns VRDeviceOrientationGamepadCamera
  100494. */
  100495. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  100496. return "VRDeviceOrientationGamepadCamera";
  100497. };
  100498. return VRDeviceOrientationGamepadCamera;
  100499. }(BABYLON.VRDeviceOrientationFreeCamera));
  100500. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  100501. })(BABYLON || (BABYLON = {}));
  100502. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  100503. var BABYLON;
  100504. (function (BABYLON) {
  100505. var VRExperienceHelperGazer = /** @class */ (function () {
  100506. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  100507. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  100508. this.scene = scene;
  100509. /** @hidden */
  100510. this._pointerDownOnMeshAsked = false;
  100511. /** @hidden */
  100512. this._isActionableMesh = false;
  100513. /** @hidden */
  100514. this._teleportationRequestInitiated = false;
  100515. /** @hidden */
  100516. this._teleportationBackRequestInitiated = false;
  100517. /** @hidden */
  100518. this._rotationRightAsked = false;
  100519. /** @hidden */
  100520. this._rotationLeftAsked = false;
  100521. /** @hidden */
  100522. this._dpadPressed = true;
  100523. /** @hidden */
  100524. this._activePointer = false;
  100525. this._id = VRExperienceHelperGazer._idCounter++;
  100526. // Gaze tracker
  100527. if (!gazeTrackerToClone) {
  100528. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  100529. this._gazeTracker.bakeCurrentTransformIntoVertices();
  100530. this._gazeTracker.isPickable = false;
  100531. this._gazeTracker.isVisible = false;
  100532. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  100533. targetMat.specularColor = BABYLON.Color3.Black();
  100534. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  100535. targetMat.backFaceCulling = false;
  100536. this._gazeTracker.material = targetMat;
  100537. }
  100538. else {
  100539. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  100540. }
  100541. }
  100542. /** @hidden */
  100543. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  100544. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  100545. };
  100546. /** @hidden */
  100547. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  100548. this._pointerDownOnMeshAsked = true;
  100549. if (this._currentHit) {
  100550. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  100551. }
  100552. };
  100553. /** @hidden */
  100554. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  100555. if (this._currentHit) {
  100556. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  100557. }
  100558. this._pointerDownOnMeshAsked = false;
  100559. };
  100560. /** @hidden */
  100561. VRExperienceHelperGazer.prototype._activatePointer = function () {
  100562. this._activePointer = true;
  100563. };
  100564. /** @hidden */
  100565. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  100566. this._activePointer = false;
  100567. };
  100568. /** @hidden */
  100569. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  100570. if (distance === void 0) { distance = 100; }
  100571. };
  100572. VRExperienceHelperGazer.prototype.dispose = function () {
  100573. this._interactionsEnabled = false;
  100574. this._teleportationEnabled = false;
  100575. if (this._gazeTracker) {
  100576. this._gazeTracker.dispose();
  100577. }
  100578. };
  100579. VRExperienceHelperGazer._idCounter = 0;
  100580. return VRExperienceHelperGazer;
  100581. }());
  100582. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  100583. __extends(VRExperienceHelperControllerGazer, _super);
  100584. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  100585. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  100586. _this.webVRController = webVRController;
  100587. // Laser pointer
  100588. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  100589. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  100590. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  100591. laserPointerMaterial.alpha = 0.6;
  100592. _this._laserPointer.material = laserPointerMaterial;
  100593. _this._laserPointer.rotation.x = Math.PI / 2;
  100594. _this._laserPointer.position.z = -0.5;
  100595. _this._laserPointer.isVisible = false;
  100596. _this._laserPointer.isPickable = false;
  100597. if (!webVRController.mesh) {
  100598. // Create an empty mesh that is used prior to loading the high quality model
  100599. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  100600. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  100601. preloadPointerPose.rotation.x = -0.7;
  100602. preloadMesh.addChild(preloadPointerPose);
  100603. webVRController.attachToMesh(preloadMesh);
  100604. }
  100605. _this._setLaserPointerParent(webVRController.mesh);
  100606. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  100607. _this._setLaserPointerParent(mesh);
  100608. });
  100609. return _this;
  100610. }
  100611. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  100612. return this.webVRController.getForwardRay(length);
  100613. };
  100614. /** @hidden */
  100615. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  100616. _super.prototype._activatePointer.call(this);
  100617. this._laserPointer.isVisible = true;
  100618. };
  100619. /** @hidden */
  100620. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  100621. _super.prototype._deactivatePointer.call(this);
  100622. this._laserPointer.isVisible = false;
  100623. };
  100624. /** @hidden */
  100625. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  100626. this._laserPointer.material.emissiveColor = color;
  100627. };
  100628. /** @hidden */
  100629. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  100630. var makeNotPick = function (root) {
  100631. root.isPickable = false;
  100632. root.getChildMeshes().forEach(function (c) {
  100633. makeNotPick(c);
  100634. });
  100635. };
  100636. makeNotPick(mesh);
  100637. var childMeshes = mesh.getChildMeshes();
  100638. this.webVRController._pointingPoseNode = null;
  100639. for (var i = 0; i < childMeshes.length; i++) {
  100640. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  100641. mesh = childMeshes[i];
  100642. this.webVRController._pointingPoseNode = mesh;
  100643. break;
  100644. }
  100645. }
  100646. this._laserPointer.parent = mesh;
  100647. };
  100648. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  100649. if (distance === void 0) { distance = 100; }
  100650. this._laserPointer.scaling.y = distance;
  100651. this._laserPointer.position.z = -distance / 2;
  100652. };
  100653. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  100654. _super.prototype.dispose.call(this);
  100655. this._laserPointer.dispose();
  100656. if (this._meshAttachedObserver) {
  100657. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  100658. }
  100659. };
  100660. return VRExperienceHelperControllerGazer;
  100661. }(VRExperienceHelperGazer));
  100662. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  100663. __extends(VRExperienceHelperCameraGazer, _super);
  100664. function VRExperienceHelperCameraGazer(getCamera, scene) {
  100665. var _this = _super.call(this, scene) || this;
  100666. _this.getCamera = getCamera;
  100667. return _this;
  100668. }
  100669. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  100670. var camera = this.getCamera();
  100671. if (camera) {
  100672. return camera.getForwardRay(length);
  100673. }
  100674. else {
  100675. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  100676. }
  100677. };
  100678. return VRExperienceHelperCameraGazer;
  100679. }(VRExperienceHelperGazer));
  100680. /**
  100681. * Helps to quickly add VR support to an existing scene.
  100682. * See http://doc.babylonjs.com/how_to/webvr_helper
  100683. */
  100684. var VRExperienceHelper = /** @class */ (function () {
  100685. /**
  100686. * Instantiates a VRExperienceHelper.
  100687. * Helps to quickly add VR support to an existing scene.
  100688. * @param scene The scene the VRExperienceHelper belongs to.
  100689. * @param webVROptions Options to modify the vr experience helper's behavior.
  100690. */
  100691. function VRExperienceHelper(scene,
  100692. /** Options to modify the vr experience helper's behavior. */
  100693. webVROptions) {
  100694. if (webVROptions === void 0) { webVROptions = {}; }
  100695. var _this = this;
  100696. this.webVROptions = webVROptions;
  100697. // Can the system support WebVR, even if a headset isn't plugged in?
  100698. this._webVRsupported = false;
  100699. // If WebVR is supported, is a headset plugged in and are we ready to present?
  100700. this._webVRready = false;
  100701. // Are we waiting for the requestPresent callback to complete?
  100702. this._webVRrequesting = false;
  100703. // Are we presenting to the headset right now? (this is the vrDevice state)
  100704. this._webVRpresenting = false;
  100705. // Are we presenting in the fullscreen fallback?
  100706. this._fullscreenVRpresenting = false;
  100707. /**
  100708. * Observable raised when entering VR.
  100709. */
  100710. this.onEnteringVRObservable = new BABYLON.Observable();
  100711. /**
  100712. * Observable raised when exiting VR.
  100713. */
  100714. this.onExitingVRObservable = new BABYLON.Observable();
  100715. /**
  100716. * Observable raised when controller mesh is loaded.
  100717. */
  100718. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  100719. this._useCustomVRButton = false;
  100720. this._teleportationRequested = false;
  100721. this._teleportActive = false;
  100722. this._floorMeshesCollection = [];
  100723. this._rotationAllowed = true;
  100724. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  100725. this._isDefaultTeleportationTarget = true;
  100726. this._teleportationFillColor = "#444444";
  100727. this._teleportationBorderColor = "#FFFFFF";
  100728. this._rotationAngle = 0;
  100729. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  100730. this._padSensibilityUp = 0.65;
  100731. this._padSensibilityDown = 0.35;
  100732. this._leftController = null;
  100733. this._rightController = null;
  100734. /**
  100735. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  100736. */
  100737. this.onNewMeshSelected = new BABYLON.Observable();
  100738. /**
  100739. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  100740. */
  100741. this.onNewMeshPicked = new BABYLON.Observable();
  100742. /**
  100743. * Observable raised before camera teleportation
  100744. */
  100745. this.onBeforeCameraTeleport = new BABYLON.Observable();
  100746. /**
  100747. * Observable raised after camera teleportation
  100748. */
  100749. this.onAfterCameraTeleport = new BABYLON.Observable();
  100750. /**
  100751. * Observable raised when current selected mesh gets unselected
  100752. */
  100753. this.onSelectedMeshUnselected = new BABYLON.Observable();
  100754. /**
  100755. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  100756. */
  100757. this.teleportationEnabled = true;
  100758. this._teleportationInitialized = false;
  100759. this._interactionsEnabled = false;
  100760. this._interactionsRequested = false;
  100761. this._displayGaze = true;
  100762. this._displayLaserPointer = true;
  100763. /**
  100764. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  100765. */
  100766. this.updateGazeTrackerScale = true;
  100767. this._onResize = function () {
  100768. _this.moveButtonToBottomRight();
  100769. if (_this._fullscreenVRpresenting && _this._webVRready) {
  100770. _this.exitVR();
  100771. }
  100772. };
  100773. this._onFullscreenChange = function () {
  100774. if (document.fullscreen !== undefined) {
  100775. _this._fullscreenVRpresenting = document.fullscreen;
  100776. }
  100777. else if (document.mozFullScreen !== undefined) {
  100778. _this._fullscreenVRpresenting = document.mozFullScreen;
  100779. }
  100780. else if (document.webkitIsFullScreen !== undefined) {
  100781. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  100782. }
  100783. else if (document.msIsFullScreen !== undefined) {
  100784. _this._fullscreenVRpresenting = document.msIsFullScreen;
  100785. }
  100786. else if (document.msFullscreenElement !== undefined) {
  100787. _this._fullscreenVRpresenting = document.msFullscreenElement;
  100788. }
  100789. if (!_this._fullscreenVRpresenting && _this._canvas) {
  100790. _this.exitVR();
  100791. if (!_this._useCustomVRButton) {
  100792. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  100793. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  100794. }
  100795. }
  100796. };
  100797. this.beforeRender = function () {
  100798. if (_this._leftController && _this._leftController._activePointer) {
  100799. _this._castRayAndSelectObject(_this._leftController);
  100800. }
  100801. if (_this._rightController && _this._rightController._activePointer) {
  100802. _this._castRayAndSelectObject(_this._rightController);
  100803. }
  100804. if (_this._noControllerIsActive) {
  100805. _this._castRayAndSelectObject(_this._cameraGazer);
  100806. }
  100807. else {
  100808. _this._cameraGazer._gazeTracker.isVisible = false;
  100809. }
  100810. };
  100811. this._onNewGamepadConnected = function (gamepad) {
  100812. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  100813. if (gamepad.leftStick) {
  100814. gamepad.onleftstickchanged(function (stickValues) {
  100815. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  100816. // Listening to classic/xbox gamepad only if no VR controller is active
  100817. if ((!_this._leftController && !_this._rightController) ||
  100818. ((_this._leftController && !_this._leftController._activePointer) &&
  100819. (_this._rightController && !_this._rightController._activePointer))) {
  100820. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  100821. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  100822. }
  100823. }
  100824. });
  100825. }
  100826. if (gamepad.rightStick) {
  100827. gamepad.onrightstickchanged(function (stickValues) {
  100828. if (_this._teleportationInitialized) {
  100829. _this._checkRotate(stickValues, _this._cameraGazer);
  100830. }
  100831. });
  100832. }
  100833. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  100834. gamepad.onbuttondown(function (buttonPressed) {
  100835. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  100836. _this._cameraGazer._selectionPointerDown();
  100837. }
  100838. });
  100839. gamepad.onbuttonup(function (buttonPressed) {
  100840. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  100841. _this._cameraGazer._selectionPointerUp();
  100842. }
  100843. });
  100844. }
  100845. }
  100846. else {
  100847. var webVRController = gamepad;
  100848. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  100849. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  100850. _this._rightController = controller;
  100851. }
  100852. else {
  100853. _this._leftController = controller;
  100854. }
  100855. _this._tryEnableInteractionOnController(controller);
  100856. }
  100857. };
  100858. // 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
  100859. this._tryEnableInteractionOnController = function (controller) {
  100860. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  100861. _this._enableInteractionOnController(controller);
  100862. }
  100863. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  100864. _this._enableTeleportationOnController(controller);
  100865. }
  100866. };
  100867. this._onNewGamepadDisconnected = function (gamepad) {
  100868. if (gamepad instanceof BABYLON.WebVRController) {
  100869. if (gamepad.hand === "left" && _this._leftController != null) {
  100870. _this._leftController.dispose();
  100871. _this._leftController = null;
  100872. }
  100873. if (gamepad.hand === "right" && _this._rightController != null) {
  100874. _this._rightController.dispose();
  100875. _this._rightController = null;
  100876. }
  100877. }
  100878. };
  100879. this._workingVector = BABYLON.Vector3.Zero();
  100880. this._workingQuaternion = BABYLON.Quaternion.Identity();
  100881. this._workingMatrix = BABYLON.Matrix.Identity();
  100882. this._scene = scene;
  100883. this._canvas = scene.getEngine().getRenderingCanvas();
  100884. // Parse options
  100885. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  100886. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  100887. }
  100888. if (webVROptions.createDeviceOrientationCamera === undefined) {
  100889. webVROptions.createDeviceOrientationCamera = true;
  100890. }
  100891. if (webVROptions.laserToggle === undefined) {
  100892. webVROptions.laserToggle = true;
  100893. }
  100894. if (webVROptions.defaultHeight === undefined) {
  100895. webVROptions.defaultHeight = 1.7;
  100896. }
  100897. if (webVROptions.useCustomVRButton) {
  100898. this._useCustomVRButton = true;
  100899. if (webVROptions.customVRButton) {
  100900. this._btnVR = webVROptions.customVRButton;
  100901. }
  100902. }
  100903. if (webVROptions.rayLength) {
  100904. this._rayLength = webVROptions.rayLength;
  100905. }
  100906. this._defaultHeight = webVROptions.defaultHeight;
  100907. if (webVROptions.positionScale) {
  100908. this._rayLength *= webVROptions.positionScale;
  100909. this._defaultHeight *= webVROptions.positionScale;
  100910. }
  100911. this._hasEnteredVR = false;
  100912. // Set position
  100913. if (this._scene.activeCamera) {
  100914. this._position = this._scene.activeCamera.position.clone();
  100915. }
  100916. else {
  100917. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  100918. }
  100919. // Set non-vr camera
  100920. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  100921. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  100922. // Copy data from existing camera
  100923. if (this._scene.activeCamera) {
  100924. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  100925. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  100926. // Set rotation from previous camera
  100927. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  100928. var targetCamera = this._scene.activeCamera;
  100929. if (targetCamera.rotationQuaternion) {
  100930. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  100931. }
  100932. else {
  100933. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  100934. }
  100935. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  100936. }
  100937. }
  100938. this._scene.activeCamera = this._deviceOrientationCamera;
  100939. if (this._canvas) {
  100940. this._scene.activeCamera.attachControl(this._canvas);
  100941. }
  100942. }
  100943. else {
  100944. this._existingCamera = this._scene.activeCamera;
  100945. }
  100946. // Create VR cameras
  100947. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  100948. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  100949. }
  100950. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  100951. this._webVRCamera.useStandingMatrix();
  100952. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  100953. // Create default button
  100954. if (!this._useCustomVRButton) {
  100955. this._btnVR = document.createElement("BUTTON");
  100956. this._btnVR.className = "babylonVRicon";
  100957. this._btnVR.id = "babylonVRiconbtn";
  100958. this._btnVR.title = "Click to switch to VR";
  100959. 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) }";
  100960. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  100961. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  100962. // css += ".babylonVRicon.vrdisplaysupported { }";
  100963. // css += ".babylonVRicon.vrdisplayready { }";
  100964. // css += ".babylonVRicon.vrdisplayrequesting { }";
  100965. var style = document.createElement('style');
  100966. style.appendChild(document.createTextNode(css));
  100967. document.getElementsByTagName('head')[0].appendChild(style);
  100968. this.moveButtonToBottomRight();
  100969. }
  100970. // VR button click event
  100971. if (this._btnVR) {
  100972. this._btnVR.addEventListener("click", function () {
  100973. if (!_this.isInVRMode) {
  100974. _this.enterVR();
  100975. }
  100976. else {
  100977. _this.exitVR();
  100978. }
  100979. });
  100980. }
  100981. // Window events
  100982. window.addEventListener("resize", this._onResize);
  100983. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  100984. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  100985. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  100986. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  100987. document.onmsfullscreenchange = this._onFullscreenChange;
  100988. // Display vr button when headset is connected
  100989. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  100990. this.displayVRButton();
  100991. }
  100992. else {
  100993. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  100994. if (e.vrDisplay) {
  100995. _this.displayVRButton();
  100996. }
  100997. });
  100998. }
  100999. // Exiting VR mode using 'ESC' key on desktop
  101000. this._onKeyDown = function (event) {
  101001. if (event.keyCode === 27 && _this.isInVRMode) {
  101002. _this.exitVR();
  101003. }
  101004. };
  101005. document.addEventListener("keydown", this._onKeyDown);
  101006. // Exiting VR mode double tapping the touch screen
  101007. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  101008. if (_this.isInVRMode) {
  101009. _this.exitVR();
  101010. if (_this._fullscreenVRpresenting) {
  101011. _this._scene.getEngine().switchFullscreen(true);
  101012. }
  101013. }
  101014. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  101015. // Listen for WebVR display changes
  101016. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  101017. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  101018. this._onVRRequestPresentStart = function () {
  101019. _this._webVRrequesting = true;
  101020. _this.updateButtonVisibility();
  101021. };
  101022. this._onVRRequestPresentComplete = function (success) {
  101023. _this._webVRrequesting = false;
  101024. _this.updateButtonVisibility();
  101025. };
  101026. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  101027. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  101028. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  101029. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101030. scene.onDisposeObservable.add(function () {
  101031. _this.dispose();
  101032. });
  101033. // Gamepad connection events
  101034. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  101035. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  101036. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  101037. this.updateButtonVisibility();
  101038. //create easing functions
  101039. this._circleEase = new BABYLON.CircleEase();
  101040. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  101041. if (this.webVROptions.floorMeshes) {
  101042. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  101043. }
  101044. }
  101045. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  101046. /** Return this.onEnteringVRObservable
  101047. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  101048. */
  101049. get: function () {
  101050. return this.onEnteringVRObservable;
  101051. },
  101052. enumerable: true,
  101053. configurable: true
  101054. });
  101055. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  101056. /** Return this.onExitingVRObservable
  101057. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  101058. */
  101059. get: function () {
  101060. return this.onExitingVRObservable;
  101061. },
  101062. enumerable: true,
  101063. configurable: true
  101064. });
  101065. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  101066. /** Return this.onControllerMeshLoadedObservable
  101067. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  101068. */
  101069. get: function () {
  101070. return this.onControllerMeshLoadedObservable;
  101071. },
  101072. enumerable: true,
  101073. configurable: true
  101074. });
  101075. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  101076. /**
  101077. * The mesh used to display where the user is going to teleport.
  101078. */
  101079. get: function () {
  101080. return this._teleportationTarget;
  101081. },
  101082. /**
  101083. * Sets the mesh to be used to display where the user is going to teleport.
  101084. */
  101085. set: function (value) {
  101086. if (value) {
  101087. value.name = "teleportationTarget";
  101088. this._isDefaultTeleportationTarget = false;
  101089. this._teleportationTarget = value;
  101090. }
  101091. },
  101092. enumerable: true,
  101093. configurable: true
  101094. });
  101095. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  101096. /**
  101097. * 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
  101098. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  101099. * See http://doc.babylonjs.com/resources/baking_transformations
  101100. */
  101101. get: function () {
  101102. return this._cameraGazer._gazeTracker;
  101103. },
  101104. set: function (value) {
  101105. if (value) {
  101106. // Dispose of existing meshes
  101107. if (this._cameraGazer._gazeTracker) {
  101108. this._cameraGazer._gazeTracker.dispose();
  101109. }
  101110. if (this._leftController && this._leftController._gazeTracker) {
  101111. this._leftController._gazeTracker.dispose();
  101112. }
  101113. if (this._rightController && this._rightController._gazeTracker) {
  101114. this._rightController._gazeTracker.dispose();
  101115. }
  101116. // Set and create gaze trackers on head and controllers
  101117. this._cameraGazer._gazeTracker = value;
  101118. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  101119. this._cameraGazer._gazeTracker.isPickable = false;
  101120. this._cameraGazer._gazeTracker.isVisible = false;
  101121. this._cameraGazer._gazeTracker.name = "gazeTracker";
  101122. if (this._leftController) {
  101123. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  101124. }
  101125. if (this._rightController) {
  101126. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  101127. }
  101128. }
  101129. },
  101130. enumerable: true,
  101131. configurable: true
  101132. });
  101133. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  101134. /**
  101135. * The gaze tracking mesh corresponding to the left controller
  101136. */
  101137. get: function () {
  101138. if (this._leftController) {
  101139. return this._leftController._gazeTracker;
  101140. }
  101141. return null;
  101142. },
  101143. enumerable: true,
  101144. configurable: true
  101145. });
  101146. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  101147. /**
  101148. * The gaze tracking mesh corresponding to the right controller
  101149. */
  101150. get: function () {
  101151. if (this._rightController) {
  101152. return this._rightController._gazeTracker;
  101153. }
  101154. return null;
  101155. },
  101156. enumerable: true,
  101157. configurable: true
  101158. });
  101159. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  101160. /**
  101161. * If the ray of the gaze should be displayed.
  101162. */
  101163. get: function () {
  101164. return this._displayGaze;
  101165. },
  101166. /**
  101167. * Sets if the ray of the gaze should be displayed.
  101168. */
  101169. set: function (value) {
  101170. this._displayGaze = value;
  101171. if (!value) {
  101172. this._cameraGazer._gazeTracker.isVisible = false;
  101173. if (this._leftController) {
  101174. this._leftController._gazeTracker.isVisible = false;
  101175. }
  101176. if (this._rightController) {
  101177. this._rightController._gazeTracker.isVisible = false;
  101178. }
  101179. }
  101180. },
  101181. enumerable: true,
  101182. configurable: true
  101183. });
  101184. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  101185. /**
  101186. * If the ray of the LaserPointer should be displayed.
  101187. */
  101188. get: function () {
  101189. return this._displayLaserPointer;
  101190. },
  101191. /**
  101192. * Sets if the ray of the LaserPointer should be displayed.
  101193. */
  101194. set: function (value) {
  101195. this._displayLaserPointer = value;
  101196. if (!value) {
  101197. if (this._rightController) {
  101198. this._rightController._deactivatePointer();
  101199. this._rightController._gazeTracker.isVisible = false;
  101200. }
  101201. if (this._leftController) {
  101202. this._leftController._deactivatePointer();
  101203. this._leftController._gazeTracker.isVisible = false;
  101204. }
  101205. }
  101206. else {
  101207. if (this._rightController) {
  101208. this._rightController._activatePointer();
  101209. }
  101210. if (this._leftController) {
  101211. this._leftController._activatePointer();
  101212. }
  101213. }
  101214. },
  101215. enumerable: true,
  101216. configurable: true
  101217. });
  101218. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  101219. /**
  101220. * The deviceOrientationCamera used as the camera when not in VR.
  101221. */
  101222. get: function () {
  101223. return this._deviceOrientationCamera;
  101224. },
  101225. enumerable: true,
  101226. configurable: true
  101227. });
  101228. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  101229. /**
  101230. * Based on the current WebVR support, returns the current VR camera used.
  101231. */
  101232. get: function () {
  101233. if (this._webVRready) {
  101234. return this._webVRCamera;
  101235. }
  101236. else {
  101237. return this._scene.activeCamera;
  101238. }
  101239. },
  101240. enumerable: true,
  101241. configurable: true
  101242. });
  101243. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  101244. /**
  101245. * The webVRCamera which is used when in VR.
  101246. */
  101247. get: function () {
  101248. return this._webVRCamera;
  101249. },
  101250. enumerable: true,
  101251. configurable: true
  101252. });
  101253. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  101254. /**
  101255. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  101256. */
  101257. get: function () {
  101258. return this._vrDeviceOrientationCamera;
  101259. },
  101260. enumerable: true,
  101261. configurable: true
  101262. });
  101263. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  101264. get: function () {
  101265. var result = this._cameraGazer._teleportationRequestInitiated
  101266. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  101267. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  101268. return result;
  101269. },
  101270. enumerable: true,
  101271. configurable: true
  101272. });
  101273. // Raised when one of the controller has loaded successfully its associated default mesh
  101274. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  101275. if (this._leftController && this._leftController.webVRController == webVRController) {
  101276. if (webVRController.mesh) {
  101277. this._leftController._setLaserPointerParent(webVRController.mesh);
  101278. }
  101279. }
  101280. if (this._rightController && this._rightController.webVRController == webVRController) {
  101281. if (webVRController.mesh) {
  101282. this._rightController._setLaserPointerParent(webVRController.mesh);
  101283. }
  101284. }
  101285. try {
  101286. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  101287. }
  101288. catch (err) {
  101289. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  101290. }
  101291. };
  101292. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  101293. /**
  101294. * Gets a value indicating if we are currently in VR mode.
  101295. */
  101296. get: function () {
  101297. return this._webVRpresenting || this._fullscreenVRpresenting;
  101298. },
  101299. enumerable: true,
  101300. configurable: true
  101301. });
  101302. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  101303. var vrDisplay = this._scene.getEngine().getVRDevice();
  101304. if (vrDisplay) {
  101305. var wasPresenting = this._webVRpresenting;
  101306. this._webVRpresenting = vrDisplay.isPresenting;
  101307. if (wasPresenting && !this._webVRpresenting)
  101308. this.exitVR();
  101309. }
  101310. else {
  101311. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  101312. }
  101313. this.updateButtonVisibility();
  101314. };
  101315. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  101316. this._webVRsupported = eventArgs.vrSupported;
  101317. this._webVRready = !!eventArgs.vrDisplay;
  101318. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  101319. this.updateButtonVisibility();
  101320. };
  101321. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  101322. if (this._canvas && !this._useCustomVRButton) {
  101323. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  101324. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  101325. }
  101326. };
  101327. VRExperienceHelper.prototype.displayVRButton = function () {
  101328. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  101329. document.body.appendChild(this._btnVR);
  101330. this._btnVRDisplayed = true;
  101331. }
  101332. };
  101333. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  101334. if (!this._btnVR || this._useCustomVRButton) {
  101335. return;
  101336. }
  101337. this._btnVR.className = "babylonVRicon";
  101338. if (this.isInVRMode) {
  101339. this._btnVR.className += " vrdisplaypresenting";
  101340. }
  101341. else {
  101342. if (this._webVRready)
  101343. this._btnVR.className += " vrdisplayready";
  101344. if (this._webVRsupported)
  101345. this._btnVR.className += " vrdisplaysupported";
  101346. if (this._webVRrequesting)
  101347. this._btnVR.className += " vrdisplayrequesting";
  101348. }
  101349. };
  101350. /**
  101351. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  101352. * Otherwise, will use the fullscreen API.
  101353. */
  101354. VRExperienceHelper.prototype.enterVR = function () {
  101355. if (this.onEnteringVRObservable) {
  101356. try {
  101357. this.onEnteringVRObservable.notifyObservers(this);
  101358. }
  101359. catch (err) {
  101360. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  101361. }
  101362. }
  101363. if (this._scene.activeCamera) {
  101364. this._position = this._scene.activeCamera.position.clone();
  101365. // make sure that we return to the last active camera
  101366. this._existingCamera = this._scene.activeCamera;
  101367. }
  101368. if (this._webVRrequesting)
  101369. return;
  101370. // If WebVR is supported and a headset is connected
  101371. if (this._webVRready) {
  101372. if (!this._webVRpresenting) {
  101373. this._webVRCamera.position = this._position;
  101374. this._scene.activeCamera = this._webVRCamera;
  101375. }
  101376. }
  101377. else if (this._vrDeviceOrientationCamera) {
  101378. this._vrDeviceOrientationCamera.position = this._position;
  101379. if (this._scene.activeCamera) {
  101380. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  101381. }
  101382. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  101383. this._scene.getEngine().switchFullscreen(true);
  101384. this.updateButtonVisibility();
  101385. }
  101386. if (this._scene.activeCamera && this._canvas) {
  101387. this._scene.activeCamera.attachControl(this._canvas);
  101388. }
  101389. if (this._interactionsEnabled) {
  101390. this._scene.registerBeforeRender(this.beforeRender);
  101391. }
  101392. this._hasEnteredVR = true;
  101393. };
  101394. /**
  101395. * Attempt to exit VR, or fullscreen.
  101396. */
  101397. VRExperienceHelper.prototype.exitVR = function () {
  101398. if (this._hasEnteredVR) {
  101399. if (this.onExitingVRObservable) {
  101400. try {
  101401. this.onExitingVRObservable.notifyObservers(this);
  101402. }
  101403. catch (err) {
  101404. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  101405. }
  101406. }
  101407. if (this._webVRpresenting) {
  101408. this._scene.getEngine().disableVR();
  101409. }
  101410. if (this._scene.activeCamera) {
  101411. this._position = this._scene.activeCamera.position.clone();
  101412. }
  101413. if (this._deviceOrientationCamera) {
  101414. this._deviceOrientationCamera.position = this._position;
  101415. this._scene.activeCamera = this._deviceOrientationCamera;
  101416. if (this._canvas) {
  101417. this._scene.activeCamera.attachControl(this._canvas);
  101418. }
  101419. }
  101420. else if (this._existingCamera) {
  101421. this._existingCamera.position = this._position;
  101422. this._scene.activeCamera = this._existingCamera;
  101423. }
  101424. this.updateButtonVisibility();
  101425. if (this._interactionsEnabled) {
  101426. this._scene.unregisterBeforeRender(this.beforeRender);
  101427. this._cameraGazer._gazeTracker.isVisible = false;
  101428. if (this._leftController) {
  101429. this._leftController._gazeTracker.isVisible = false;
  101430. }
  101431. if (this._rightController) {
  101432. this._rightController._gazeTracker.isVisible = false;
  101433. }
  101434. }
  101435. // resize to update width and height when exiting vr exits fullscreen
  101436. this._scene.getEngine().resize();
  101437. this._hasEnteredVR = false;
  101438. }
  101439. };
  101440. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  101441. /**
  101442. * The position of the vr experience helper.
  101443. */
  101444. get: function () {
  101445. return this._position;
  101446. },
  101447. /**
  101448. * Sets the position of the vr experience helper.
  101449. */
  101450. set: function (value) {
  101451. this._position = value;
  101452. if (this._scene.activeCamera) {
  101453. this._scene.activeCamera.position = value;
  101454. }
  101455. },
  101456. enumerable: true,
  101457. configurable: true
  101458. });
  101459. /**
  101460. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  101461. */
  101462. VRExperienceHelper.prototype.enableInteractions = function () {
  101463. var _this = this;
  101464. if (!this._interactionsEnabled) {
  101465. this._interactionsRequested = true;
  101466. if (this._leftController) {
  101467. this._enableInteractionOnController(this._leftController);
  101468. }
  101469. if (this._rightController) {
  101470. this._enableInteractionOnController(this._rightController);
  101471. }
  101472. this.raySelectionPredicate = function (mesh) {
  101473. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  101474. };
  101475. this.meshSelectionPredicate = function (mesh) {
  101476. return true;
  101477. };
  101478. this._raySelectionPredicate = function (mesh) {
  101479. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  101480. && mesh.name.indexOf("teleportationTarget") === -1
  101481. && mesh.name.indexOf("torusTeleportation") === -1)) {
  101482. return _this.raySelectionPredicate(mesh);
  101483. }
  101484. return false;
  101485. };
  101486. this._interactionsEnabled = true;
  101487. }
  101488. };
  101489. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  101490. get: function () {
  101491. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  101492. },
  101493. enumerable: true,
  101494. configurable: true
  101495. });
  101496. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  101497. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  101498. if (this._floorMeshesCollection[i].id === mesh.id) {
  101499. return true;
  101500. }
  101501. }
  101502. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  101503. return true;
  101504. }
  101505. return false;
  101506. };
  101507. /**
  101508. * Adds a floor mesh to be used for teleportation.
  101509. * @param floorMesh the mesh to be used for teleportation.
  101510. */
  101511. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  101512. if (!this._floorMeshesCollection) {
  101513. return;
  101514. }
  101515. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  101516. return;
  101517. }
  101518. this._floorMeshesCollection.push(floorMesh);
  101519. };
  101520. /**
  101521. * Removes a floor mesh from being used for teleportation.
  101522. * @param floorMesh the mesh to be removed.
  101523. */
  101524. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  101525. if (!this._floorMeshesCollection) {
  101526. return;
  101527. }
  101528. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  101529. if (meshIndex !== -1) {
  101530. this._floorMeshesCollection.splice(meshIndex, 1);
  101531. }
  101532. };
  101533. /**
  101534. * Enables interactions and teleportation using the VR controllers and gaze.
  101535. * @param vrTeleportationOptions options to modify teleportation behavior.
  101536. */
  101537. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  101538. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  101539. if (!this._teleportationInitialized) {
  101540. this._teleportationRequested = true;
  101541. this.enableInteractions();
  101542. if (vrTeleportationOptions.floorMeshName) {
  101543. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  101544. }
  101545. if (vrTeleportationOptions.floorMeshes) {
  101546. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  101547. }
  101548. if (this._leftController != null) {
  101549. this._enableTeleportationOnController(this._leftController);
  101550. }
  101551. if (this._rightController != null) {
  101552. this._enableTeleportationOnController(this._rightController);
  101553. }
  101554. // Creates an image processing post process for the vignette not relying
  101555. // on the main scene configuration for image processing to reduce setup and spaces
  101556. // (gamma/linear) conflicts.
  101557. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  101558. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  101559. imageProcessingConfiguration.vignetteEnabled = true;
  101560. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  101561. this._webVRCamera.detachPostProcess(this._postProcessMove);
  101562. this._teleportationInitialized = true;
  101563. if (this._isDefaultTeleportationTarget) {
  101564. this._createTeleportationCircles();
  101565. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  101566. }
  101567. }
  101568. };
  101569. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  101570. var _this = this;
  101571. var controllerMesh = controller.webVRController.mesh;
  101572. if (controllerMesh) {
  101573. controller._interactionsEnabled = true;
  101574. controller._activatePointer();
  101575. if (this.webVROptions.laserToggle) {
  101576. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  101577. // Enabling / disabling laserPointer
  101578. if (_this._displayLaserPointer && stateObject.value === 1) {
  101579. if (controller._activePointer) {
  101580. controller._deactivatePointer();
  101581. }
  101582. else {
  101583. controller._activatePointer();
  101584. }
  101585. if (_this.displayGaze) {
  101586. controller._gazeTracker.isVisible = controller._activePointer;
  101587. }
  101588. }
  101589. });
  101590. }
  101591. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  101592. var gazer = controller;
  101593. if (_this._noControllerIsActive) {
  101594. gazer = _this._cameraGazer;
  101595. }
  101596. if (!gazer._pointerDownOnMeshAsked) {
  101597. if (stateObject.value > _this._padSensibilityUp) {
  101598. gazer._selectionPointerDown();
  101599. }
  101600. }
  101601. else if (stateObject.value < _this._padSensibilityDown) {
  101602. gazer._selectionPointerUp();
  101603. }
  101604. });
  101605. }
  101606. };
  101607. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  101608. // Dont teleport if another gaze already requested teleportation
  101609. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  101610. return;
  101611. }
  101612. if (!gazer._teleportationRequestInitiated) {
  101613. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  101614. gazer._activatePointer();
  101615. gazer._teleportationRequestInitiated = true;
  101616. }
  101617. }
  101618. else {
  101619. // Listening to the proper controller values changes to confirm teleportation
  101620. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  101621. if (this._teleportActive) {
  101622. this.teleportCamera(this._haloCenter);
  101623. }
  101624. gazer._teleportationRequestInitiated = false;
  101625. }
  101626. }
  101627. };
  101628. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  101629. // Only rotate when user is not currently selecting a teleportation location
  101630. if (gazer._teleportationRequestInitiated) {
  101631. return;
  101632. }
  101633. if (!gazer._rotationLeftAsked) {
  101634. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  101635. gazer._rotationLeftAsked = true;
  101636. if (this._rotationAllowed) {
  101637. this._rotateCamera(false);
  101638. }
  101639. }
  101640. }
  101641. else {
  101642. if (stateObject.x > -this._padSensibilityDown) {
  101643. gazer._rotationLeftAsked = false;
  101644. }
  101645. }
  101646. if (!gazer._rotationRightAsked) {
  101647. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  101648. gazer._rotationRightAsked = true;
  101649. if (this._rotationAllowed) {
  101650. this._rotateCamera(true);
  101651. }
  101652. }
  101653. }
  101654. else {
  101655. if (stateObject.x < this._padSensibilityDown) {
  101656. gazer._rotationRightAsked = false;
  101657. }
  101658. }
  101659. };
  101660. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  101661. // Only teleport backwards when user is not currently selecting a teleportation location
  101662. if (gazer._teleportationRequestInitiated) {
  101663. return;
  101664. }
  101665. // Teleport backwards
  101666. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  101667. if (!gazer._teleportationBackRequestInitiated) {
  101668. if (!this.currentVRCamera) {
  101669. return;
  101670. }
  101671. // Get rotation and position of the current camera
  101672. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  101673. var position = this.currentVRCamera.position;
  101674. // If the camera has device position, use that instead
  101675. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  101676. rotation = this.currentVRCamera.deviceRotationQuaternion;
  101677. position = this.currentVRCamera.devicePosition;
  101678. }
  101679. // Get matrix with only the y rotation of the device rotation
  101680. rotation.toEulerAnglesToRef(this._workingVector);
  101681. this._workingVector.z = 0;
  101682. this._workingVector.x = 0;
  101683. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  101684. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  101685. // Rotate backwards ray by device rotation to cast at the ground behind the user
  101686. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  101687. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  101688. var ray = new BABYLON.Ray(position, this._workingVector);
  101689. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  101690. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  101691. this.teleportCamera(hit.pickedPoint);
  101692. }
  101693. gazer._teleportationBackRequestInitiated = true;
  101694. }
  101695. }
  101696. else {
  101697. gazer._teleportationBackRequestInitiated = false;
  101698. }
  101699. };
  101700. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  101701. var _this = this;
  101702. var controllerMesh = controller.webVRController.mesh;
  101703. if (controllerMesh) {
  101704. if (!controller._interactionsEnabled) {
  101705. this._enableInteractionOnController(controller);
  101706. }
  101707. controller._interactionsEnabled = true;
  101708. controller._teleportationEnabled = true;
  101709. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  101710. controller._dpadPressed = false;
  101711. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  101712. controller._dpadPressed = stateObject.pressed;
  101713. if (!controller._dpadPressed) {
  101714. controller._rotationLeftAsked = false;
  101715. controller._rotationRightAsked = false;
  101716. controller._teleportationBackRequestInitiated = false;
  101717. }
  101718. });
  101719. }
  101720. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  101721. if (_this.teleportationEnabled) {
  101722. _this._checkTeleportBackwards(stateObject, controller);
  101723. _this._checkTeleportWithRay(stateObject, controller);
  101724. }
  101725. _this._checkRotate(stateObject, controller);
  101726. });
  101727. }
  101728. };
  101729. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  101730. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  101731. this._teleportationTarget.isPickable = false;
  101732. var length = 512;
  101733. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  101734. dynamicTexture.hasAlpha = true;
  101735. var context = dynamicTexture.getContext();
  101736. var centerX = length / 2;
  101737. var centerY = length / 2;
  101738. var radius = 200;
  101739. context.beginPath();
  101740. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  101741. context.fillStyle = this._teleportationFillColor;
  101742. context.fill();
  101743. context.lineWidth = 10;
  101744. context.strokeStyle = this._teleportationBorderColor;
  101745. context.stroke();
  101746. context.closePath();
  101747. dynamicTexture.update();
  101748. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  101749. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  101750. this._teleportationTarget.material = teleportationCircleMaterial;
  101751. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  101752. torus.isPickable = false;
  101753. torus.parent = this._teleportationTarget;
  101754. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  101755. var keys = [];
  101756. keys.push({
  101757. frame: 0,
  101758. value: 0
  101759. });
  101760. keys.push({
  101761. frame: 30,
  101762. value: 0.4
  101763. });
  101764. keys.push({
  101765. frame: 60,
  101766. value: 0
  101767. });
  101768. animationInnerCircle.setKeys(keys);
  101769. var easingFunction = new BABYLON.SineEase();
  101770. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  101771. animationInnerCircle.setEasingFunction(easingFunction);
  101772. torus.animations = [];
  101773. torus.animations.push(animationInnerCircle);
  101774. this._scene.beginAnimation(torus, 0, 60, true);
  101775. this._hideTeleportationTarget();
  101776. };
  101777. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  101778. this._teleportActive = true;
  101779. if (this._teleportationInitialized) {
  101780. this._teleportationTarget.isVisible = true;
  101781. if (this._isDefaultTeleportationTarget) {
  101782. this._teleportationTarget.getChildren()[0].isVisible = true;
  101783. }
  101784. }
  101785. };
  101786. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  101787. this._teleportActive = false;
  101788. if (this._teleportationInitialized) {
  101789. this._teleportationTarget.isVisible = false;
  101790. if (this._isDefaultTeleportationTarget) {
  101791. this._teleportationTarget.getChildren()[0].isVisible = false;
  101792. }
  101793. }
  101794. };
  101795. VRExperienceHelper.prototype._rotateCamera = function (right) {
  101796. var _this = this;
  101797. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101798. return;
  101799. }
  101800. if (right) {
  101801. this._rotationAngle++;
  101802. }
  101803. else {
  101804. this._rotationAngle--;
  101805. }
  101806. this.currentVRCamera.animations = [];
  101807. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  101808. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101809. var animationRotationKeys = [];
  101810. animationRotationKeys.push({
  101811. frame: 0,
  101812. value: this.currentVRCamera.rotationQuaternion
  101813. });
  101814. animationRotationKeys.push({
  101815. frame: 6,
  101816. value: target
  101817. });
  101818. animationRotation.setKeys(animationRotationKeys);
  101819. animationRotation.setEasingFunction(this._circleEase);
  101820. this.currentVRCamera.animations.push(animationRotation);
  101821. this._postProcessMove.animations = [];
  101822. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101823. var vignetteWeightKeys = [];
  101824. vignetteWeightKeys.push({
  101825. frame: 0,
  101826. value: 0
  101827. });
  101828. vignetteWeightKeys.push({
  101829. frame: 3,
  101830. value: 4
  101831. });
  101832. vignetteWeightKeys.push({
  101833. frame: 6,
  101834. value: 0
  101835. });
  101836. animationPP.setKeys(vignetteWeightKeys);
  101837. animationPP.setEasingFunction(this._circleEase);
  101838. this._postProcessMove.animations.push(animationPP);
  101839. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101840. var vignetteStretchKeys = [];
  101841. vignetteStretchKeys.push({
  101842. frame: 0,
  101843. value: 0
  101844. });
  101845. vignetteStretchKeys.push({
  101846. frame: 3,
  101847. value: 10
  101848. });
  101849. vignetteStretchKeys.push({
  101850. frame: 6,
  101851. value: 0
  101852. });
  101853. animationPP2.setKeys(vignetteStretchKeys);
  101854. animationPP2.setEasingFunction(this._circleEase);
  101855. this._postProcessMove.animations.push(animationPP2);
  101856. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  101857. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  101858. this._postProcessMove.samples = 4;
  101859. this._webVRCamera.attachPostProcess(this._postProcessMove);
  101860. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  101861. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  101862. });
  101863. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  101864. };
  101865. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  101866. if (hit.pickedPoint) {
  101867. if (gazer._teleportationRequestInitiated) {
  101868. this._displayTeleportationTarget();
  101869. this._haloCenter.copyFrom(hit.pickedPoint);
  101870. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  101871. }
  101872. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  101873. if (pickNormal) {
  101874. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  101875. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  101876. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  101877. }
  101878. this._teleportationTarget.position.y += 0.1;
  101879. }
  101880. };
  101881. /**
  101882. * Teleports the users feet to the desired location
  101883. * @param location The location where the user's feet should be placed
  101884. */
  101885. VRExperienceHelper.prototype.teleportCamera = function (location) {
  101886. var _this = this;
  101887. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101888. return;
  101889. }
  101890. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  101891. // offset of the headset from the anchor.
  101892. if (this.webVRCamera.leftCamera) {
  101893. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  101894. this._workingVector.subtractInPlace(this.webVRCamera.position);
  101895. location.subtractToRef(this._workingVector, this._workingVector);
  101896. }
  101897. else {
  101898. this._workingVector.copyFrom(location);
  101899. }
  101900. // Add height to account for user's height offset
  101901. if (this.isInVRMode) {
  101902. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  101903. }
  101904. else {
  101905. this._workingVector.y += this._defaultHeight;
  101906. }
  101907. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  101908. // Create animation from the camera's position to the new location
  101909. this.currentVRCamera.animations = [];
  101910. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101911. var animationCameraTeleportationKeys = [{
  101912. frame: 0,
  101913. value: this.currentVRCamera.position
  101914. },
  101915. {
  101916. frame: 11,
  101917. value: this._workingVector
  101918. }
  101919. ];
  101920. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  101921. animationCameraTeleportation.setEasingFunction(this._circleEase);
  101922. this.currentVRCamera.animations.push(animationCameraTeleportation);
  101923. this._postProcessMove.animations = [];
  101924. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101925. var vignetteWeightKeys = [];
  101926. vignetteWeightKeys.push({
  101927. frame: 0,
  101928. value: 0
  101929. });
  101930. vignetteWeightKeys.push({
  101931. frame: 5,
  101932. value: 8
  101933. });
  101934. vignetteWeightKeys.push({
  101935. frame: 11,
  101936. value: 0
  101937. });
  101938. animationPP.setKeys(vignetteWeightKeys);
  101939. this._postProcessMove.animations.push(animationPP);
  101940. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101941. var vignetteStretchKeys = [];
  101942. vignetteStretchKeys.push({
  101943. frame: 0,
  101944. value: 0
  101945. });
  101946. vignetteStretchKeys.push({
  101947. frame: 5,
  101948. value: 10
  101949. });
  101950. vignetteStretchKeys.push({
  101951. frame: 11,
  101952. value: 0
  101953. });
  101954. animationPP2.setKeys(vignetteStretchKeys);
  101955. this._postProcessMove.animations.push(animationPP2);
  101956. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  101957. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  101958. this._webVRCamera.attachPostProcess(this._postProcessMove);
  101959. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  101960. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  101961. });
  101962. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  101963. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  101964. });
  101965. this._hideTeleportationTarget();
  101966. };
  101967. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  101968. if (normal) {
  101969. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  101970. if (angle < Math.PI / 2) {
  101971. normal.scaleInPlace(-1);
  101972. }
  101973. }
  101974. return normal;
  101975. };
  101976. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  101977. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101978. return;
  101979. }
  101980. var ray = gazer._getForwardRay(this._rayLength);
  101981. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  101982. if (hit) {
  101983. // Populate the contrllers mesh that can be used for drag/drop
  101984. if (gazer._laserPointer) {
  101985. hit.originMesh = gazer._laserPointer.parent;
  101986. }
  101987. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  101988. }
  101989. gazer._currentHit = hit;
  101990. // Moving the gazeTracker on the mesh face targetted
  101991. if (hit && hit.pickedPoint) {
  101992. if (this._displayGaze) {
  101993. var multiplier = 1;
  101994. gazer._gazeTracker.isVisible = true;
  101995. if (gazer._isActionableMesh) {
  101996. multiplier = 3;
  101997. }
  101998. if (this.updateGazeTrackerScale) {
  101999. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  102000. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  102001. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  102002. }
  102003. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  102004. // To avoid z-fighting
  102005. var deltaFighting = 0.002;
  102006. if (pickNormal) {
  102007. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  102008. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  102009. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  102010. }
  102011. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  102012. if (gazer._gazeTracker.position.x < 0) {
  102013. gazer._gazeTracker.position.x += deltaFighting;
  102014. }
  102015. else {
  102016. gazer._gazeTracker.position.x -= deltaFighting;
  102017. }
  102018. if (gazer._gazeTracker.position.y < 0) {
  102019. gazer._gazeTracker.position.y += deltaFighting;
  102020. }
  102021. else {
  102022. gazer._gazeTracker.position.y -= deltaFighting;
  102023. }
  102024. if (gazer._gazeTracker.position.z < 0) {
  102025. gazer._gazeTracker.position.z += deltaFighting;
  102026. }
  102027. else {
  102028. gazer._gazeTracker.position.z -= deltaFighting;
  102029. }
  102030. }
  102031. // Changing the size of the laser pointer based on the distance from the targetted point
  102032. gazer._updatePointerDistance(hit.distance);
  102033. }
  102034. else {
  102035. gazer._updatePointerDistance();
  102036. gazer._gazeTracker.isVisible = false;
  102037. }
  102038. if (hit && hit.pickedMesh) {
  102039. // The object selected is the floor, we're in a teleportation scenario
  102040. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  102041. // Moving the teleportation area to this targetted point
  102042. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  102043. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  102044. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102045. }
  102046. gazer._currentMeshSelected = null;
  102047. if (gazer._teleportationRequestInitiated) {
  102048. this._moveTeleportationSelectorTo(hit, gazer, ray);
  102049. }
  102050. return;
  102051. }
  102052. // If not, we're in a selection scenario
  102053. //this._teleportationAllowed = false;
  102054. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  102055. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  102056. this.onNewMeshPicked.notifyObservers(hit);
  102057. gazer._currentMeshSelected = hit.pickedMesh;
  102058. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  102059. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  102060. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  102061. gazer._isActionableMesh = true;
  102062. }
  102063. else {
  102064. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102065. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102066. gazer._isActionableMesh = false;
  102067. }
  102068. try {
  102069. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  102070. }
  102071. catch (err) {
  102072. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  102073. }
  102074. }
  102075. else {
  102076. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102077. gazer._currentMeshSelected = null;
  102078. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102079. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102080. }
  102081. }
  102082. }
  102083. else {
  102084. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102085. gazer._currentMeshSelected = null;
  102086. //this._teleportationAllowed = false;
  102087. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102088. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102089. }
  102090. };
  102091. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  102092. if (mesh) {
  102093. this.onSelectedMeshUnselected.notifyObservers(mesh);
  102094. }
  102095. };
  102096. /**
  102097. * Sets the color of the laser ray from the vr controllers.
  102098. * @param color new color for the ray.
  102099. */
  102100. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  102101. if (this._leftController) {
  102102. this._leftController._setLaserPointerColor(color);
  102103. }
  102104. if (this._rightController) {
  102105. this._rightController._setLaserPointerColor(color);
  102106. }
  102107. };
  102108. /**
  102109. * Sets the color of the ray from the vr headsets gaze.
  102110. * @param color new color for the ray.
  102111. */
  102112. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  102113. if (!this._cameraGazer._gazeTracker.material) {
  102114. return;
  102115. }
  102116. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  102117. if (this._leftController) {
  102118. this._leftController._gazeTracker.material.emissiveColor = color;
  102119. }
  102120. if (this._rightController) {
  102121. this._rightController._gazeTracker.material.emissiveColor = color;
  102122. }
  102123. };
  102124. /**
  102125. * Exits VR and disposes of the vr experience helper
  102126. */
  102127. VRExperienceHelper.prototype.dispose = function () {
  102128. if (this.isInVRMode) {
  102129. this.exitVR();
  102130. }
  102131. if (this._postProcessMove) {
  102132. this._postProcessMove.dispose();
  102133. }
  102134. if (this._webVRCamera) {
  102135. this._webVRCamera.dispose();
  102136. }
  102137. if (this._vrDeviceOrientationCamera) {
  102138. this._vrDeviceOrientationCamera.dispose();
  102139. }
  102140. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  102141. document.body.removeChild(this._btnVR);
  102142. }
  102143. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  102144. this._deviceOrientationCamera.dispose();
  102145. }
  102146. if (this._cameraGazer) {
  102147. this._cameraGazer.dispose();
  102148. }
  102149. if (this._leftController) {
  102150. this._leftController.dispose();
  102151. }
  102152. if (this._rightController) {
  102153. this._rightController.dispose();
  102154. }
  102155. if (this._teleportationTarget) {
  102156. this._teleportationTarget.dispose();
  102157. }
  102158. this._floorMeshesCollection = [];
  102159. document.removeEventListener("keydown", this._onKeyDown);
  102160. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102161. window.removeEventListener("resize", this._onResize);
  102162. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  102163. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  102164. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  102165. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  102166. document.onmsfullscreenchange = null;
  102167. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  102168. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  102169. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  102170. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102171. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  102172. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  102173. this._scene.unregisterBeforeRender(this.beforeRender);
  102174. };
  102175. /**
  102176. * Gets the name of the VRExperienceHelper class
  102177. * @returns "VRExperienceHelper"
  102178. */
  102179. VRExperienceHelper.prototype.getClassName = function () {
  102180. return "VRExperienceHelper";
  102181. };
  102182. return VRExperienceHelper;
  102183. }());
  102184. BABYLON.VRExperienceHelper = VRExperienceHelper;
  102185. })(BABYLON || (BABYLON = {}));
  102186. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  102187. // Mainly based on these 2 articles :
  102188. // 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
  102189. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  102190. var BABYLON;
  102191. (function (BABYLON) {
  102192. /**
  102193. * Defines the potential axis of a Joystick
  102194. */
  102195. var JoystickAxis;
  102196. (function (JoystickAxis) {
  102197. /** X axis */
  102198. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  102199. /** Y axis */
  102200. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  102201. /** Z axis */
  102202. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  102203. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  102204. /**
  102205. * Class used to define virtual joystick (used in touch mode)
  102206. */
  102207. var VirtualJoystick = /** @class */ (function () {
  102208. /**
  102209. * Creates a new virtual joystick
  102210. * @param leftJoystick defines that the joystick is for left hand (false by default)
  102211. */
  102212. function VirtualJoystick(leftJoystick) {
  102213. var _this = this;
  102214. if (leftJoystick) {
  102215. this._leftJoystick = true;
  102216. }
  102217. else {
  102218. this._leftJoystick = false;
  102219. }
  102220. VirtualJoystick._globalJoystickIndex++;
  102221. // By default left & right arrow keys are moving the X
  102222. // and up & down keys are moving the Y
  102223. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  102224. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  102225. this.reverseLeftRight = false;
  102226. this.reverseUpDown = false;
  102227. // collections of pointers
  102228. this._touches = new BABYLON.StringDictionary();
  102229. this.deltaPosition = BABYLON.Vector3.Zero();
  102230. this._joystickSensibility = 25;
  102231. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  102232. this._onResize = function (evt) {
  102233. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102234. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  102235. if (VirtualJoystick.vjCanvas) {
  102236. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  102237. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  102238. }
  102239. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  102240. };
  102241. // injecting a canvas element on top of the canvas 3D game
  102242. if (!VirtualJoystick.vjCanvas) {
  102243. window.addEventListener("resize", this._onResize, false);
  102244. VirtualJoystick.vjCanvas = document.createElement("canvas");
  102245. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102246. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  102247. VirtualJoystick.vjCanvas.width = window.innerWidth;
  102248. VirtualJoystick.vjCanvas.height = window.innerHeight;
  102249. VirtualJoystick.vjCanvas.style.width = "100%";
  102250. VirtualJoystick.vjCanvas.style.height = "100%";
  102251. VirtualJoystick.vjCanvas.style.position = "absolute";
  102252. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  102253. VirtualJoystick.vjCanvas.style.top = "0px";
  102254. VirtualJoystick.vjCanvas.style.left = "0px";
  102255. VirtualJoystick.vjCanvas.style.zIndex = "5";
  102256. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  102257. // Support for jQuery PEP polyfill
  102258. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  102259. var context = VirtualJoystick.vjCanvas.getContext('2d');
  102260. if (!context) {
  102261. throw new Error("Unable to create canvas for virtual joystick");
  102262. }
  102263. VirtualJoystick.vjCanvasContext = context;
  102264. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  102265. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  102266. document.body.appendChild(VirtualJoystick.vjCanvas);
  102267. }
  102268. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  102269. this.pressed = false;
  102270. // default joystick color
  102271. this._joystickColor = "cyan";
  102272. this._joystickPointerID = -1;
  102273. // current joystick position
  102274. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  102275. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  102276. // origin joystick position
  102277. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  102278. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  102279. this._onPointerDownHandlerRef = function (evt) {
  102280. _this._onPointerDown(evt);
  102281. };
  102282. this._onPointerMoveHandlerRef = function (evt) {
  102283. _this._onPointerMove(evt);
  102284. };
  102285. this._onPointerUpHandlerRef = function (evt) {
  102286. _this._onPointerUp(evt);
  102287. };
  102288. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  102289. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  102290. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  102291. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  102292. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  102293. evt.preventDefault(); // Disables system menu
  102294. }, false);
  102295. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  102296. }
  102297. /**
  102298. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  102299. * @param newJoystickSensibility defines the new sensibility
  102300. */
  102301. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  102302. this._joystickSensibility = newJoystickSensibility;
  102303. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  102304. };
  102305. VirtualJoystick.prototype._onPointerDown = function (e) {
  102306. var positionOnScreenCondition;
  102307. e.preventDefault();
  102308. if (this._leftJoystick === true) {
  102309. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  102310. }
  102311. else {
  102312. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  102313. }
  102314. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  102315. // First contact will be dedicated to the virtual joystick
  102316. this._joystickPointerID = e.pointerId;
  102317. this._joystickPointerStartPos.x = e.clientX;
  102318. this._joystickPointerStartPos.y = e.clientY;
  102319. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  102320. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  102321. this._deltaJoystickVector.x = 0;
  102322. this._deltaJoystickVector.y = 0;
  102323. this.pressed = true;
  102324. this._touches.add(e.pointerId.toString(), e);
  102325. }
  102326. else {
  102327. // You can only trigger the action buttons with a joystick declared
  102328. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  102329. this._action();
  102330. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  102331. }
  102332. }
  102333. };
  102334. VirtualJoystick.prototype._onPointerMove = function (e) {
  102335. // If the current pointer is the one associated to the joystick (first touch contact)
  102336. if (this._joystickPointerID == e.pointerId) {
  102337. this._joystickPointerPos.x = e.clientX;
  102338. this._joystickPointerPos.y = e.clientY;
  102339. this._deltaJoystickVector = this._joystickPointerPos.clone();
  102340. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  102341. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  102342. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  102343. switch (this._axisTargetedByLeftAndRight) {
  102344. case JoystickAxis.X:
  102345. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  102346. break;
  102347. case JoystickAxis.Y:
  102348. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  102349. break;
  102350. case JoystickAxis.Z:
  102351. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  102352. break;
  102353. }
  102354. var directionUpDown = this.reverseUpDown ? 1 : -1;
  102355. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  102356. switch (this._axisTargetedByUpAndDown) {
  102357. case JoystickAxis.X:
  102358. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  102359. break;
  102360. case JoystickAxis.Y:
  102361. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  102362. break;
  102363. case JoystickAxis.Z:
  102364. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  102365. break;
  102366. }
  102367. }
  102368. else {
  102369. var data = this._touches.get(e.pointerId.toString());
  102370. if (data) {
  102371. data.x = e.clientX;
  102372. data.y = e.clientY;
  102373. }
  102374. }
  102375. };
  102376. VirtualJoystick.prototype._onPointerUp = function (e) {
  102377. if (this._joystickPointerID == e.pointerId) {
  102378. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  102379. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  102380. this._joystickPointerID = -1;
  102381. this.pressed = false;
  102382. }
  102383. else {
  102384. var touch = this._touches.get(e.pointerId.toString());
  102385. if (touch) {
  102386. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  102387. }
  102388. }
  102389. this._deltaJoystickVector.x = 0;
  102390. this._deltaJoystickVector.y = 0;
  102391. this._touches.remove(e.pointerId.toString());
  102392. };
  102393. /**
  102394. * Change the color of the virtual joystick
  102395. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  102396. */
  102397. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  102398. this._joystickColor = newColor;
  102399. };
  102400. /**
  102401. * Defines a callback to call when the joystick is touched
  102402. * @param action defines the callback
  102403. */
  102404. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  102405. this._action = action;
  102406. };
  102407. /**
  102408. * Defines which axis you'd like to control for left & right
  102409. * @param axis defines the axis to use
  102410. */
  102411. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  102412. switch (axis) {
  102413. case JoystickAxis.X:
  102414. case JoystickAxis.Y:
  102415. case JoystickAxis.Z:
  102416. this._axisTargetedByLeftAndRight = axis;
  102417. break;
  102418. default:
  102419. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  102420. break;
  102421. }
  102422. };
  102423. /**
  102424. * Defines which axis you'd like to control for up & down
  102425. * @param axis defines the axis to use
  102426. */
  102427. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  102428. switch (axis) {
  102429. case JoystickAxis.X:
  102430. case JoystickAxis.Y:
  102431. case JoystickAxis.Z:
  102432. this._axisTargetedByUpAndDown = axis;
  102433. break;
  102434. default:
  102435. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  102436. break;
  102437. }
  102438. };
  102439. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  102440. var _this = this;
  102441. if (this.pressed) {
  102442. this._touches.forEach(function (key, touch) {
  102443. if (touch.pointerId === _this._joystickPointerID) {
  102444. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  102445. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  102446. VirtualJoystick.vjCanvasContext.beginPath();
  102447. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  102448. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102449. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  102450. VirtualJoystick.vjCanvasContext.stroke();
  102451. VirtualJoystick.vjCanvasContext.closePath();
  102452. VirtualJoystick.vjCanvasContext.beginPath();
  102453. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102454. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  102455. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  102456. VirtualJoystick.vjCanvasContext.stroke();
  102457. VirtualJoystick.vjCanvasContext.closePath();
  102458. VirtualJoystick.vjCanvasContext.beginPath();
  102459. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102460. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  102461. VirtualJoystick.vjCanvasContext.stroke();
  102462. VirtualJoystick.vjCanvasContext.closePath();
  102463. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  102464. }
  102465. else {
  102466. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  102467. VirtualJoystick.vjCanvasContext.beginPath();
  102468. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  102469. VirtualJoystick.vjCanvasContext.beginPath();
  102470. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  102471. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  102472. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  102473. VirtualJoystick.vjCanvasContext.stroke();
  102474. VirtualJoystick.vjCanvasContext.closePath();
  102475. touch.prevX = touch.x;
  102476. touch.prevY = touch.y;
  102477. }
  102478. ;
  102479. });
  102480. }
  102481. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  102482. };
  102483. /**
  102484. * Release internal HTML canvas
  102485. */
  102486. VirtualJoystick.prototype.releaseCanvas = function () {
  102487. if (VirtualJoystick.vjCanvas) {
  102488. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  102489. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  102490. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  102491. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  102492. window.removeEventListener("resize", this._onResize);
  102493. document.body.removeChild(VirtualJoystick.vjCanvas);
  102494. VirtualJoystick.vjCanvas = null;
  102495. }
  102496. };
  102497. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  102498. VirtualJoystick._globalJoystickIndex = 0;
  102499. return VirtualJoystick;
  102500. }());
  102501. BABYLON.VirtualJoystick = VirtualJoystick;
  102502. })(BABYLON || (BABYLON = {}));
  102503. //# sourceMappingURL=babylon.virtualJoystick.js.map
  102504. var BABYLON;
  102505. (function (BABYLON) {
  102506. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  102507. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  102508. });
  102509. /**
  102510. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  102511. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  102512. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  102513. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  102514. */
  102515. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  102516. __extends(VirtualJoysticksCamera, _super);
  102517. /**
  102518. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  102519. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  102520. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  102521. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  102522. * @param name Define the name of the camera in the scene
  102523. * @param position Define the start position of the camera in the scene
  102524. * @param scene Define the scene the camera belongs to
  102525. */
  102526. function VirtualJoysticksCamera(name, position, scene) {
  102527. var _this = _super.call(this, name, position, scene) || this;
  102528. _this.inputs.addVirtualJoystick();
  102529. return _this;
  102530. }
  102531. /**
  102532. * Gets the current object class name.
  102533. * @return the class name
  102534. */
  102535. VirtualJoysticksCamera.prototype.getClassName = function () {
  102536. return "VirtualJoysticksCamera";
  102537. };
  102538. return VirtualJoysticksCamera;
  102539. }(BABYLON.FreeCamera));
  102540. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  102541. })(BABYLON || (BABYLON = {}));
  102542. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  102543. var BABYLON;
  102544. (function (BABYLON) {
  102545. /**
  102546. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  102547. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  102548. */
  102549. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  102550. function FreeCameraVirtualJoystickInput() {
  102551. }
  102552. /**
  102553. * Gets the left stick of the virtual joystick.
  102554. * @returns The virtual Joystick
  102555. */
  102556. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  102557. return this._leftjoystick;
  102558. };
  102559. /**
  102560. * Gets the right stick of the virtual joystick.
  102561. * @returns The virtual Joystick
  102562. */
  102563. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  102564. return this._rightjoystick;
  102565. };
  102566. /**
  102567. * Update the current camera state depending on the inputs that have been used this frame.
  102568. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  102569. */
  102570. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  102571. if (this._leftjoystick) {
  102572. var camera = this.camera;
  102573. var speed = camera._computeLocalCameraSpeed() * 50;
  102574. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  102575. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  102576. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  102577. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  102578. if (!this._leftjoystick.pressed) {
  102579. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  102580. }
  102581. if (!this._rightjoystick.pressed) {
  102582. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  102583. }
  102584. }
  102585. };
  102586. /**
  102587. * Attach the input controls to a specific dom element to get the input from.
  102588. * @param element Defines the element the controls should be listened from
  102589. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  102590. */
  102591. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  102592. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  102593. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  102594. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  102595. this._leftjoystick.setJoystickSensibility(0.15);
  102596. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  102597. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  102598. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  102599. this._rightjoystick.reverseUpDown = true;
  102600. this._rightjoystick.setJoystickSensibility(0.05);
  102601. this._rightjoystick.setJoystickColor("yellow");
  102602. };
  102603. /**
  102604. * Detach the current controls from the specified dom element.
  102605. * @param element Defines the element to stop listening the inputs from
  102606. */
  102607. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  102608. this._leftjoystick.releaseCanvas();
  102609. this._rightjoystick.releaseCanvas();
  102610. };
  102611. /**
  102612. * Gets the class name of the current intput.
  102613. * @returns the class name
  102614. */
  102615. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  102616. return "FreeCameraVirtualJoystickInput";
  102617. };
  102618. /**
  102619. * Get the friendly name associated with the input class.
  102620. * @returns the input friendly name
  102621. */
  102622. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  102623. return "virtualJoystick";
  102624. };
  102625. return FreeCameraVirtualJoystickInput;
  102626. }());
  102627. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  102628. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  102629. })(BABYLON || (BABYLON = {}));
  102630. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  102631. var BABYLON;
  102632. (function (BABYLON) {
  102633. var SimplificationSettings = /** @class */ (function () {
  102634. function SimplificationSettings(quality, distance, optimizeMesh) {
  102635. this.quality = quality;
  102636. this.distance = distance;
  102637. this.optimizeMesh = optimizeMesh;
  102638. }
  102639. return SimplificationSettings;
  102640. }());
  102641. BABYLON.SimplificationSettings = SimplificationSettings;
  102642. var SimplificationQueue = /** @class */ (function () {
  102643. function SimplificationQueue() {
  102644. this.running = false;
  102645. this._simplificationArray = [];
  102646. }
  102647. SimplificationQueue.prototype.addTask = function (task) {
  102648. this._simplificationArray.push(task);
  102649. };
  102650. SimplificationQueue.prototype.executeNext = function () {
  102651. var task = this._simplificationArray.pop();
  102652. if (task) {
  102653. this.running = true;
  102654. this.runSimplification(task);
  102655. }
  102656. else {
  102657. this.running = false;
  102658. }
  102659. };
  102660. SimplificationQueue.prototype.runSimplification = function (task) {
  102661. var _this = this;
  102662. if (task.parallelProcessing) {
  102663. //parallel simplifier
  102664. task.settings.forEach(function (setting) {
  102665. var simplifier = _this.getSimplifier(task);
  102666. simplifier.simplify(setting, function (newMesh) {
  102667. task.mesh.addLODLevel(setting.distance, newMesh);
  102668. newMesh.isVisible = true;
  102669. //check if it is the last
  102670. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  102671. //all done, run the success callback.
  102672. task.successCallback();
  102673. }
  102674. _this.executeNext();
  102675. });
  102676. });
  102677. }
  102678. else {
  102679. //single simplifier.
  102680. var simplifier = this.getSimplifier(task);
  102681. var runDecimation = function (setting, callback) {
  102682. simplifier.simplify(setting, function (newMesh) {
  102683. task.mesh.addLODLevel(setting.distance, newMesh);
  102684. newMesh.isVisible = true;
  102685. //run the next quality level
  102686. callback();
  102687. });
  102688. };
  102689. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  102690. runDecimation(task.settings[loop.index], function () {
  102691. loop.executeNext();
  102692. });
  102693. }, function () {
  102694. //execution ended, run the success callback.
  102695. if (task.successCallback) {
  102696. task.successCallback();
  102697. }
  102698. _this.executeNext();
  102699. });
  102700. }
  102701. };
  102702. SimplificationQueue.prototype.getSimplifier = function (task) {
  102703. switch (task.simplificationType) {
  102704. case SimplificationType.QUADRATIC:
  102705. default:
  102706. return new QuadraticErrorSimplification(task.mesh);
  102707. }
  102708. };
  102709. return SimplificationQueue;
  102710. }());
  102711. BABYLON.SimplificationQueue = SimplificationQueue;
  102712. /**
  102713. * The implemented types of simplification
  102714. * At the moment only Quadratic Error Decimation is implemented
  102715. */
  102716. var SimplificationType;
  102717. (function (SimplificationType) {
  102718. /** Quadratic error decimation */
  102719. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  102720. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  102721. var DecimationTriangle = /** @class */ (function () {
  102722. function DecimationTriangle(vertices) {
  102723. this.vertices = vertices;
  102724. this.error = new Array(4);
  102725. this.deleted = false;
  102726. this.isDirty = false;
  102727. this.deletePending = false;
  102728. this.borderFactor = 0;
  102729. }
  102730. return DecimationTriangle;
  102731. }());
  102732. BABYLON.DecimationTriangle = DecimationTriangle;
  102733. var DecimationVertex = /** @class */ (function () {
  102734. function DecimationVertex(position, id) {
  102735. this.position = position;
  102736. this.id = id;
  102737. this.isBorder = true;
  102738. this.q = new QuadraticMatrix();
  102739. this.triangleCount = 0;
  102740. this.triangleStart = 0;
  102741. this.originalOffsets = [];
  102742. }
  102743. DecimationVertex.prototype.updatePosition = function (newPosition) {
  102744. this.position.copyFrom(newPosition);
  102745. };
  102746. return DecimationVertex;
  102747. }());
  102748. BABYLON.DecimationVertex = DecimationVertex;
  102749. var QuadraticMatrix = /** @class */ (function () {
  102750. function QuadraticMatrix(data) {
  102751. this.data = new Array(10);
  102752. for (var i = 0; i < 10; ++i) {
  102753. if (data && data[i]) {
  102754. this.data[i] = data[i];
  102755. }
  102756. else {
  102757. this.data[i] = 0;
  102758. }
  102759. }
  102760. }
  102761. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  102762. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  102763. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  102764. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  102765. return det;
  102766. };
  102767. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  102768. for (var i = 0; i < 10; ++i) {
  102769. this.data[i] += matrix.data[i];
  102770. }
  102771. };
  102772. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  102773. for (var i = 0; i < 10; ++i) {
  102774. this.data[i] += data[i];
  102775. }
  102776. };
  102777. QuadraticMatrix.prototype.add = function (matrix) {
  102778. var m = new QuadraticMatrix();
  102779. for (var i = 0; i < 10; ++i) {
  102780. m.data[i] = this.data[i] + matrix.data[i];
  102781. }
  102782. return m;
  102783. };
  102784. QuadraticMatrix.FromData = function (a, b, c, d) {
  102785. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  102786. };
  102787. //returning an array to avoid garbage collection
  102788. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  102789. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  102790. };
  102791. return QuadraticMatrix;
  102792. }());
  102793. BABYLON.QuadraticMatrix = QuadraticMatrix;
  102794. var Reference = /** @class */ (function () {
  102795. function Reference(vertexId, triangleId) {
  102796. this.vertexId = vertexId;
  102797. this.triangleId = triangleId;
  102798. }
  102799. return Reference;
  102800. }());
  102801. BABYLON.Reference = Reference;
  102802. /**
  102803. * An implementation of the Quadratic Error simplification algorithm.
  102804. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  102805. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  102806. * @author RaananW
  102807. */
  102808. var QuadraticErrorSimplification = /** @class */ (function () {
  102809. function QuadraticErrorSimplification(_mesh) {
  102810. this._mesh = _mesh;
  102811. this.syncIterations = 5000;
  102812. this.aggressiveness = 7;
  102813. this.decimationIterations = 100;
  102814. this.boundingBoxEpsilon = BABYLON.Epsilon;
  102815. }
  102816. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  102817. var _this = this;
  102818. this.initDecimatedMesh();
  102819. //iterating through the submeshes array, one after the other.
  102820. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  102821. _this.initWithMesh(loop.index, function () {
  102822. _this.runDecimation(settings, loop.index, function () {
  102823. loop.executeNext();
  102824. });
  102825. }, settings.optimizeMesh);
  102826. }, function () {
  102827. setTimeout(function () {
  102828. successCallback(_this._reconstructedMesh);
  102829. }, 0);
  102830. });
  102831. };
  102832. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  102833. var _this = this;
  102834. var targetCount = ~~(this.triangles.length * settings.quality);
  102835. var deletedTriangles = 0;
  102836. var triangleCount = this.triangles.length;
  102837. var iterationFunction = function (iteration, callback) {
  102838. setTimeout(function () {
  102839. if (iteration % 5 === 0) {
  102840. _this.updateMesh(iteration === 0);
  102841. }
  102842. for (var i = 0; i < _this.triangles.length; ++i) {
  102843. _this.triangles[i].isDirty = false;
  102844. }
  102845. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  102846. var trianglesIterator = function (i) {
  102847. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  102848. var t = _this.triangles[tIdx];
  102849. if (!t)
  102850. return;
  102851. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  102852. return;
  102853. }
  102854. for (var j = 0; j < 3; ++j) {
  102855. if (t.error[j] < threshold) {
  102856. var deleted0 = [];
  102857. var deleted1 = [];
  102858. var v0 = t.vertices[j];
  102859. var v1 = t.vertices[(j + 1) % 3];
  102860. if (v0.isBorder || v1.isBorder)
  102861. continue;
  102862. var p = BABYLON.Vector3.Zero();
  102863. var n = BABYLON.Vector3.Zero();
  102864. var uv = BABYLON.Vector2.Zero();
  102865. var color = new BABYLON.Color4(0, 0, 0, 1);
  102866. _this.calculateError(v0, v1, p, n, uv, color);
  102867. var delTr = new Array();
  102868. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  102869. continue;
  102870. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  102871. continue;
  102872. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  102873. continue;
  102874. var uniqueArray = new Array();
  102875. delTr.forEach(function (deletedT) {
  102876. if (uniqueArray.indexOf(deletedT) === -1) {
  102877. deletedT.deletePending = true;
  102878. uniqueArray.push(deletedT);
  102879. }
  102880. });
  102881. if (uniqueArray.length % 2 !== 0) {
  102882. continue;
  102883. }
  102884. v0.q = v1.q.add(v0.q);
  102885. v0.updatePosition(p);
  102886. var tStart = _this.references.length;
  102887. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  102888. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  102889. var tCount = _this.references.length - tStart;
  102890. if (tCount <= v0.triangleCount) {
  102891. if (tCount) {
  102892. for (var c = 0; c < tCount; c++) {
  102893. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  102894. }
  102895. }
  102896. }
  102897. else {
  102898. v0.triangleStart = tStart;
  102899. }
  102900. v0.triangleCount = tCount;
  102901. break;
  102902. }
  102903. }
  102904. };
  102905. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  102906. }, 0);
  102907. };
  102908. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  102909. if (triangleCount - deletedTriangles <= targetCount)
  102910. loop.breakLoop();
  102911. else {
  102912. iterationFunction(loop.index, function () {
  102913. loop.executeNext();
  102914. });
  102915. }
  102916. }, function () {
  102917. setTimeout(function () {
  102918. //reconstruct this part of the mesh
  102919. _this.reconstructMesh(submeshIndex);
  102920. successCallback();
  102921. }, 0);
  102922. });
  102923. };
  102924. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  102925. var _this = this;
  102926. this.vertices = [];
  102927. this.triangles = [];
  102928. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  102929. var indices = this._mesh.getIndices();
  102930. var submesh = this._mesh.subMeshes[submeshIndex];
  102931. var findInVertices = function (positionToSearch) {
  102932. if (optimizeMesh) {
  102933. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  102934. if (_this.vertices[ii].position.equals(positionToSearch)) {
  102935. return _this.vertices[ii];
  102936. }
  102937. }
  102938. }
  102939. return null;
  102940. };
  102941. var vertexReferences = [];
  102942. var vertexInit = function (i) {
  102943. if (!positionData) {
  102944. return;
  102945. }
  102946. var offset = i + submesh.verticesStart;
  102947. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  102948. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  102949. vertex.originalOffsets.push(offset);
  102950. if (vertex.id === _this.vertices.length) {
  102951. _this.vertices.push(vertex);
  102952. }
  102953. vertexReferences.push(vertex.id);
  102954. };
  102955. //var totalVertices = mesh.getTotalVertices();
  102956. var totalVertices = submesh.verticesCount;
  102957. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  102958. var indicesInit = function (i) {
  102959. if (!indices) {
  102960. return;
  102961. }
  102962. var offset = (submesh.indexStart / 3) + i;
  102963. var pos = (offset * 3);
  102964. var i0 = indices[pos + 0];
  102965. var i1 = indices[pos + 1];
  102966. var i2 = indices[pos + 2];
  102967. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  102968. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  102969. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  102970. var triangle = new DecimationTriangle([v0, v1, v2]);
  102971. triangle.originalOffset = pos;
  102972. _this.triangles.push(triangle);
  102973. };
  102974. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  102975. _this.init(callback);
  102976. });
  102977. });
  102978. };
  102979. QuadraticErrorSimplification.prototype.init = function (callback) {
  102980. var _this = this;
  102981. var triangleInit1 = function (i) {
  102982. var t = _this.triangles[i];
  102983. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  102984. for (var j = 0; j < 3; j++) {
  102985. 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))));
  102986. }
  102987. };
  102988. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  102989. var triangleInit2 = function (i) {
  102990. var t = _this.triangles[i];
  102991. for (var j = 0; j < 3; ++j) {
  102992. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  102993. }
  102994. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  102995. };
  102996. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  102997. callback();
  102998. });
  102999. });
  103000. };
  103001. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  103002. var newTriangles = [];
  103003. var i;
  103004. for (i = 0; i < this.vertices.length; ++i) {
  103005. this.vertices[i].triangleCount = 0;
  103006. }
  103007. var t;
  103008. var j;
  103009. for (i = 0; i < this.triangles.length; ++i) {
  103010. if (!this.triangles[i].deleted) {
  103011. t = this.triangles[i];
  103012. for (j = 0; j < 3; ++j) {
  103013. t.vertices[j].triangleCount = 1;
  103014. }
  103015. newTriangles.push(t);
  103016. }
  103017. }
  103018. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  103019. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  103020. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  103021. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  103022. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  103023. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  103024. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  103025. var vertexCount = 0;
  103026. for (i = 0; i < this.vertices.length; ++i) {
  103027. var vertex = this.vertices[i];
  103028. vertex.id = vertexCount;
  103029. if (vertex.triangleCount) {
  103030. vertex.originalOffsets.forEach(function (originalOffset) {
  103031. if (!normalData) {
  103032. return;
  103033. }
  103034. newPositionData.push(vertex.position.x);
  103035. newPositionData.push(vertex.position.y);
  103036. newPositionData.push(vertex.position.z);
  103037. newNormalData.push(normalData[originalOffset * 3]);
  103038. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  103039. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  103040. if (uvs && uvs.length) {
  103041. newUVsData.push(uvs[(originalOffset * 2)]);
  103042. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  103043. }
  103044. else if (colorsData && colorsData.length) {
  103045. newColorsData.push(colorsData[(originalOffset * 4)]);
  103046. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  103047. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  103048. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  103049. }
  103050. ++vertexCount;
  103051. });
  103052. }
  103053. }
  103054. var startingIndex = this._reconstructedMesh.getTotalIndices();
  103055. var startingVertex = this._reconstructedMesh.getTotalVertices();
  103056. var submeshesArray = this._reconstructedMesh.subMeshes;
  103057. this._reconstructedMesh.subMeshes = [];
  103058. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  103059. var originalIndices = this._mesh.getIndices();
  103060. for (i = 0; i < newTriangles.length; ++i) {
  103061. t = newTriangles[i]; //now get the new referencing point for each vertex
  103062. [0, 1, 2].forEach(function (idx) {
  103063. var id = originalIndices[t.originalOffset + idx];
  103064. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  103065. if (offset < 0)
  103066. offset = 0;
  103067. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  103068. });
  103069. }
  103070. //overwriting the old vertex buffers and indices.
  103071. this._reconstructedMesh.setIndices(newIndicesArray);
  103072. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  103073. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  103074. if (newUVsData.length > 0)
  103075. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  103076. if (newColorsData.length > 0)
  103077. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  103078. //create submesh
  103079. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  103080. if (submeshIndex > 0) {
  103081. this._reconstructedMesh.subMeshes = [];
  103082. submeshesArray.forEach(function (submesh) {
  103083. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  103084. });
  103085. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  103086. }
  103087. };
  103088. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  103089. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  103090. this._reconstructedMesh.material = this._mesh.material;
  103091. this._reconstructedMesh.parent = this._mesh.parent;
  103092. this._reconstructedMesh.isVisible = false;
  103093. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  103094. };
  103095. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  103096. for (var i = 0; i < vertex1.triangleCount; ++i) {
  103097. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  103098. if (t.deleted)
  103099. continue;
  103100. var s = this.references[vertex1.triangleStart + i].vertexId;
  103101. var v1 = t.vertices[(s + 1) % 3];
  103102. var v2 = t.vertices[(s + 2) % 3];
  103103. if ((v1 === vertex2 || v2 === vertex2)) {
  103104. deletedArray[i] = true;
  103105. delTr.push(t);
  103106. continue;
  103107. }
  103108. var d1 = v1.position.subtract(point);
  103109. d1 = d1.normalize();
  103110. var d2 = v2.position.subtract(point);
  103111. d2 = d2.normalize();
  103112. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  103113. return true;
  103114. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  103115. deletedArray[i] = false;
  103116. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  103117. return true;
  103118. }
  103119. return false;
  103120. };
  103121. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  103122. var newDeleted = deletedTriangles;
  103123. for (var i = 0; i < vertex.triangleCount; ++i) {
  103124. var ref = this.references[vertex.triangleStart + i];
  103125. var t = this.triangles[ref.triangleId];
  103126. if (t.deleted)
  103127. continue;
  103128. if (deletedArray[i] && t.deletePending) {
  103129. t.deleted = true;
  103130. newDeleted++;
  103131. continue;
  103132. }
  103133. t.vertices[ref.vertexId] = origVertex;
  103134. t.isDirty = true;
  103135. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  103136. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  103137. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  103138. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  103139. this.references.push(ref);
  103140. }
  103141. return newDeleted;
  103142. };
  103143. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  103144. for (var i = 0; i < this.vertices.length; ++i) {
  103145. var vCount = [];
  103146. var vId = [];
  103147. var v = this.vertices[i];
  103148. var j;
  103149. for (j = 0; j < v.triangleCount; ++j) {
  103150. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  103151. for (var ii = 0; ii < 3; ii++) {
  103152. var ofs = 0;
  103153. var vv = triangle.vertices[ii];
  103154. while (ofs < vCount.length) {
  103155. if (vId[ofs] === vv.id)
  103156. break;
  103157. ++ofs;
  103158. }
  103159. if (ofs === vCount.length) {
  103160. vCount.push(1);
  103161. vId.push(vv.id);
  103162. }
  103163. else {
  103164. vCount[ofs]++;
  103165. }
  103166. }
  103167. }
  103168. for (j = 0; j < vCount.length; ++j) {
  103169. if (vCount[j] === 1) {
  103170. this.vertices[vId[j]].isBorder = true;
  103171. }
  103172. else {
  103173. this.vertices[vId[j]].isBorder = false;
  103174. }
  103175. }
  103176. }
  103177. };
  103178. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  103179. if (identifyBorders === void 0) { identifyBorders = false; }
  103180. var i;
  103181. if (!identifyBorders) {
  103182. var newTrianglesVector = [];
  103183. for (i = 0; i < this.triangles.length; ++i) {
  103184. if (!this.triangles[i].deleted) {
  103185. newTrianglesVector.push(this.triangles[i]);
  103186. }
  103187. }
  103188. this.triangles = newTrianglesVector;
  103189. }
  103190. for (i = 0; i < this.vertices.length; ++i) {
  103191. this.vertices[i].triangleCount = 0;
  103192. this.vertices[i].triangleStart = 0;
  103193. }
  103194. var t;
  103195. var j;
  103196. var v;
  103197. for (i = 0; i < this.triangles.length; ++i) {
  103198. t = this.triangles[i];
  103199. for (j = 0; j < 3; ++j) {
  103200. v = t.vertices[j];
  103201. v.triangleCount++;
  103202. }
  103203. }
  103204. var tStart = 0;
  103205. for (i = 0; i < this.vertices.length; ++i) {
  103206. this.vertices[i].triangleStart = tStart;
  103207. tStart += this.vertices[i].triangleCount;
  103208. this.vertices[i].triangleCount = 0;
  103209. }
  103210. var newReferences = new Array(this.triangles.length * 3);
  103211. for (i = 0; i < this.triangles.length; ++i) {
  103212. t = this.triangles[i];
  103213. for (j = 0; j < 3; ++j) {
  103214. v = t.vertices[j];
  103215. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  103216. v.triangleCount++;
  103217. }
  103218. }
  103219. this.references = newReferences;
  103220. if (identifyBorders) {
  103221. this.identifyBorder();
  103222. }
  103223. };
  103224. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  103225. var x = point.x;
  103226. var y = point.y;
  103227. var z = point.z;
  103228. 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
  103229. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  103230. };
  103231. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  103232. var q = vertex1.q.add(vertex2.q);
  103233. var border = vertex1.isBorder && vertex2.isBorder;
  103234. var error = 0;
  103235. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  103236. if (qDet !== 0 && !border) {
  103237. if (!pointResult) {
  103238. pointResult = BABYLON.Vector3.Zero();
  103239. }
  103240. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  103241. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  103242. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  103243. error = this.vertexError(q, pointResult);
  103244. }
  103245. else {
  103246. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  103247. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  103248. var error1 = this.vertexError(q, vertex1.position);
  103249. var error2 = this.vertexError(q, vertex2.position);
  103250. var error3 = this.vertexError(q, p3);
  103251. error = Math.min(error1, error2, error3);
  103252. if (error === error1) {
  103253. if (pointResult) {
  103254. pointResult.copyFrom(vertex1.position);
  103255. }
  103256. }
  103257. else if (error === error2) {
  103258. if (pointResult) {
  103259. pointResult.copyFrom(vertex2.position);
  103260. }
  103261. }
  103262. else {
  103263. if (pointResult) {
  103264. pointResult.copyFrom(p3);
  103265. }
  103266. }
  103267. }
  103268. return error;
  103269. };
  103270. return QuadraticErrorSimplification;
  103271. }());
  103272. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  103273. })(BABYLON || (BABYLON = {}));
  103274. //# sourceMappingURL=babylon.meshSimplification.js.map
  103275. var BABYLON;
  103276. (function (BABYLON) {
  103277. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  103278. get: function () {
  103279. if (!this._simplificationQueue) {
  103280. this._simplificationQueue = new BABYLON.SimplificationQueue();
  103281. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  103282. if (!component) {
  103283. component = new SimplicationQueueSceneComponent(this);
  103284. this._addComponent(component);
  103285. }
  103286. }
  103287. return this._simplificationQueue;
  103288. },
  103289. set: function (value) {
  103290. this._simplificationQueue = value;
  103291. },
  103292. enumerable: true,
  103293. configurable: true
  103294. });
  103295. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  103296. if (parallelProcessing === void 0) { parallelProcessing = true; }
  103297. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  103298. this.getScene().simplificationQueue.addTask({
  103299. settings: settings,
  103300. parallelProcessing: parallelProcessing,
  103301. mesh: this,
  103302. simplificationType: simplificationType,
  103303. successCallback: successCallback
  103304. });
  103305. return this;
  103306. };
  103307. /**
  103308. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  103309. * created in a scene
  103310. */
  103311. var SimplicationQueueSceneComponent = /** @class */ (function () {
  103312. /**
  103313. * Creates a new instance of the component for the given scene
  103314. * @param scene Defines the scene to register the component in
  103315. */
  103316. function SimplicationQueueSceneComponent(scene) {
  103317. /**
  103318. * The component name helpfull to identify the component in the list of scene components.
  103319. */
  103320. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  103321. this.scene = scene;
  103322. }
  103323. /**
  103324. * Registers the component in a given scene
  103325. */
  103326. SimplicationQueueSceneComponent.prototype.register = function () {
  103327. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  103328. };
  103329. /**
  103330. * Rebuilds the elements related to this component in case of
  103331. * context lost for instance.
  103332. */
  103333. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  103334. // Nothing to do for this component
  103335. };
  103336. /**
  103337. * Disposes the component and the associated ressources
  103338. */
  103339. SimplicationQueueSceneComponent.prototype.dispose = function () {
  103340. // Nothing to do for this component
  103341. };
  103342. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  103343. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  103344. this.scene._simplificationQueue.executeNext();
  103345. }
  103346. };
  103347. return SimplicationQueueSceneComponent;
  103348. }());
  103349. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  103350. })(BABYLON || (BABYLON = {}));
  103351. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  103352. var BABYLON;
  103353. (function (BABYLON) {
  103354. /**
  103355. * Class used to represent a specific level of detail of a mesh
  103356. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  103357. */
  103358. var MeshLODLevel = /** @class */ (function () {
  103359. /**
  103360. * Creates a new LOD level
  103361. * @param distance defines the distance where this level should star being displayed
  103362. * @param mesh defines the mesh to use to render this level
  103363. */
  103364. function MeshLODLevel(
  103365. /** Defines the distance where this level should star being displayed */
  103366. distance,
  103367. /** Defines the mesh to use to render this level */
  103368. mesh) {
  103369. this.distance = distance;
  103370. this.mesh = mesh;
  103371. }
  103372. return MeshLODLevel;
  103373. }());
  103374. BABYLON.MeshLODLevel = MeshLODLevel;
  103375. })(BABYLON || (BABYLON = {}));
  103376. //# sourceMappingURL=babylon.meshLODLevel.js.map
  103377. var BABYLON;
  103378. (function (BABYLON) {
  103379. /**
  103380. * Defines the root class used to create scene optimization to use with SceneOptimizer
  103381. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103382. */
  103383. var SceneOptimization = /** @class */ (function () {
  103384. /**
  103385. * Creates the SceneOptimization object
  103386. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103387. * @param desc defines the description associated with the optimization
  103388. */
  103389. function SceneOptimization(
  103390. /**
  103391. * Defines the priority of this optimization (0 by default which means first in the list)
  103392. */
  103393. priority) {
  103394. if (priority === void 0) { priority = 0; }
  103395. this.priority = priority;
  103396. }
  103397. /**
  103398. * Gets a string describing the action executed by the current optimization
  103399. * @returns description string
  103400. */
  103401. SceneOptimization.prototype.getDescription = function () {
  103402. return "";
  103403. };
  103404. /**
  103405. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103406. * @param scene defines the current scene where to apply this optimization
  103407. * @param optimizer defines the current optimizer
  103408. * @returns true if everything that can be done was applied
  103409. */
  103410. SceneOptimization.prototype.apply = function (scene, optimizer) {
  103411. return true;
  103412. };
  103413. ;
  103414. return SceneOptimization;
  103415. }());
  103416. BABYLON.SceneOptimization = SceneOptimization;
  103417. /**
  103418. * Defines an optimization used to reduce the size of render target textures
  103419. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103420. */
  103421. var TextureOptimization = /** @class */ (function (_super) {
  103422. __extends(TextureOptimization, _super);
  103423. /**
  103424. * Creates the TextureOptimization object
  103425. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103426. * @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
  103427. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  103428. */
  103429. function TextureOptimization(
  103430. /**
  103431. * Defines the priority of this optimization (0 by default which means first in the list)
  103432. */
  103433. priority,
  103434. /**
  103435. * 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
  103436. */
  103437. maximumSize,
  103438. /**
  103439. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  103440. */
  103441. step) {
  103442. if (priority === void 0) { priority = 0; }
  103443. if (maximumSize === void 0) { maximumSize = 1024; }
  103444. if (step === void 0) { step = 0.5; }
  103445. var _this = _super.call(this, priority) || this;
  103446. _this.priority = priority;
  103447. _this.maximumSize = maximumSize;
  103448. _this.step = step;
  103449. return _this;
  103450. }
  103451. /**
  103452. * Gets a string describing the action executed by the current optimization
  103453. * @returns description string
  103454. */
  103455. TextureOptimization.prototype.getDescription = function () {
  103456. return "Reducing render target texture size to " + this.maximumSize;
  103457. };
  103458. /**
  103459. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103460. * @param scene defines the current scene where to apply this optimization
  103461. * @param optimizer defines the current optimizer
  103462. * @returns true if everything that can be done was applied
  103463. */
  103464. TextureOptimization.prototype.apply = function (scene, optimizer) {
  103465. var allDone = true;
  103466. for (var index = 0; index < scene.textures.length; index++) {
  103467. var texture = scene.textures[index];
  103468. if (!texture.canRescale || texture.getContext) {
  103469. continue;
  103470. }
  103471. var currentSize = texture.getSize();
  103472. var maxDimension = Math.max(currentSize.width, currentSize.height);
  103473. if (maxDimension > this.maximumSize) {
  103474. texture.scale(this.step);
  103475. allDone = false;
  103476. }
  103477. }
  103478. return allDone;
  103479. };
  103480. return TextureOptimization;
  103481. }(SceneOptimization));
  103482. BABYLON.TextureOptimization = TextureOptimization;
  103483. /**
  103484. * Defines an optimization used to increase or decrease the rendering resolution
  103485. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103486. */
  103487. var HardwareScalingOptimization = /** @class */ (function (_super) {
  103488. __extends(HardwareScalingOptimization, _super);
  103489. /**
  103490. * Creates the HardwareScalingOptimization object
  103491. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103492. * @param maximumScale defines the maximum scale to use (2 by default)
  103493. * @param step defines the step to use between two passes (0.5 by default)
  103494. */
  103495. function HardwareScalingOptimization(
  103496. /**
  103497. * Defines the priority of this optimization (0 by default which means first in the list)
  103498. */
  103499. priority,
  103500. /**
  103501. * Defines the maximum scale to use (2 by default)
  103502. */
  103503. maximumScale,
  103504. /**
  103505. * Defines the step to use between two passes (0.5 by default)
  103506. */
  103507. step) {
  103508. if (priority === void 0) { priority = 0; }
  103509. if (maximumScale === void 0) { maximumScale = 2; }
  103510. if (step === void 0) { step = 0.25; }
  103511. var _this = _super.call(this, priority) || this;
  103512. _this.priority = priority;
  103513. _this.maximumScale = maximumScale;
  103514. _this.step = step;
  103515. _this._currentScale = -1;
  103516. _this._directionOffset = 1;
  103517. return _this;
  103518. }
  103519. /**
  103520. * Gets a string describing the action executed by the current optimization
  103521. * @return description string
  103522. */
  103523. HardwareScalingOptimization.prototype.getDescription = function () {
  103524. return "Setting hardware scaling level to " + this._currentScale;
  103525. };
  103526. /**
  103527. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103528. * @param scene defines the current scene where to apply this optimization
  103529. * @param optimizer defines the current optimizer
  103530. * @returns true if everything that can be done was applied
  103531. */
  103532. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  103533. if (this._currentScale === -1) {
  103534. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  103535. if (this._currentScale > this.maximumScale) {
  103536. this._directionOffset = -1;
  103537. }
  103538. }
  103539. this._currentScale += this._directionOffset * this.step;
  103540. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  103541. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  103542. };
  103543. ;
  103544. return HardwareScalingOptimization;
  103545. }(SceneOptimization));
  103546. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  103547. /**
  103548. * Defines an optimization used to remove shadows
  103549. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103550. */
  103551. var ShadowsOptimization = /** @class */ (function (_super) {
  103552. __extends(ShadowsOptimization, _super);
  103553. function ShadowsOptimization() {
  103554. return _super !== null && _super.apply(this, arguments) || this;
  103555. }
  103556. /**
  103557. * Gets a string describing the action executed by the current optimization
  103558. * @return description string
  103559. */
  103560. ShadowsOptimization.prototype.getDescription = function () {
  103561. return "Turning shadows on/off";
  103562. };
  103563. /**
  103564. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103565. * @param scene defines the current scene where to apply this optimization
  103566. * @param optimizer defines the current optimizer
  103567. * @returns true if everything that can be done was applied
  103568. */
  103569. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  103570. scene.shadowsEnabled = optimizer.isInImprovementMode;
  103571. return true;
  103572. };
  103573. ;
  103574. return ShadowsOptimization;
  103575. }(SceneOptimization));
  103576. BABYLON.ShadowsOptimization = ShadowsOptimization;
  103577. /**
  103578. * Defines an optimization used to turn post-processes off
  103579. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103580. */
  103581. var PostProcessesOptimization = /** @class */ (function (_super) {
  103582. __extends(PostProcessesOptimization, _super);
  103583. function PostProcessesOptimization() {
  103584. return _super !== null && _super.apply(this, arguments) || this;
  103585. }
  103586. /**
  103587. * Gets a string describing the action executed by the current optimization
  103588. * @return description string
  103589. */
  103590. PostProcessesOptimization.prototype.getDescription = function () {
  103591. return "Turning post-processes on/off";
  103592. };
  103593. /**
  103594. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103595. * @param scene defines the current scene where to apply this optimization
  103596. * @param optimizer defines the current optimizer
  103597. * @returns true if everything that can be done was applied
  103598. */
  103599. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  103600. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  103601. return true;
  103602. };
  103603. ;
  103604. return PostProcessesOptimization;
  103605. }(SceneOptimization));
  103606. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  103607. /**
  103608. * Defines an optimization used to turn lens flares off
  103609. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103610. */
  103611. var LensFlaresOptimization = /** @class */ (function (_super) {
  103612. __extends(LensFlaresOptimization, _super);
  103613. function LensFlaresOptimization() {
  103614. return _super !== null && _super.apply(this, arguments) || this;
  103615. }
  103616. /**
  103617. * Gets a string describing the action executed by the current optimization
  103618. * @return description string
  103619. */
  103620. LensFlaresOptimization.prototype.getDescription = function () {
  103621. return "Turning lens flares on/off";
  103622. };
  103623. /**
  103624. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103625. * @param scene defines the current scene where to apply this optimization
  103626. * @param optimizer defines the current optimizer
  103627. * @returns true if everything that can be done was applied
  103628. */
  103629. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  103630. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  103631. return true;
  103632. };
  103633. ;
  103634. return LensFlaresOptimization;
  103635. }(SceneOptimization));
  103636. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  103637. /**
  103638. * Defines an optimization based on user defined callback.
  103639. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103640. */
  103641. var CustomOptimization = /** @class */ (function (_super) {
  103642. __extends(CustomOptimization, _super);
  103643. function CustomOptimization() {
  103644. return _super !== null && _super.apply(this, arguments) || this;
  103645. }
  103646. /**
  103647. * Gets a string describing the action executed by the current optimization
  103648. * @returns description string
  103649. */
  103650. CustomOptimization.prototype.getDescription = function () {
  103651. if (this.onGetDescription) {
  103652. return this.onGetDescription();
  103653. }
  103654. return "Running user defined callback";
  103655. };
  103656. /**
  103657. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103658. * @param scene defines the current scene where to apply this optimization
  103659. * @param optimizer defines the current optimizer
  103660. * @returns true if everything that can be done was applied
  103661. */
  103662. CustomOptimization.prototype.apply = function (scene, optimizer) {
  103663. if (this.onApply) {
  103664. return this.onApply(scene, optimizer);
  103665. }
  103666. return true;
  103667. };
  103668. ;
  103669. return CustomOptimization;
  103670. }(SceneOptimization));
  103671. BABYLON.CustomOptimization = CustomOptimization;
  103672. /**
  103673. * Defines an optimization used to turn particles off
  103674. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103675. */
  103676. var ParticlesOptimization = /** @class */ (function (_super) {
  103677. __extends(ParticlesOptimization, _super);
  103678. function ParticlesOptimization() {
  103679. return _super !== null && _super.apply(this, arguments) || this;
  103680. }
  103681. /**
  103682. * Gets a string describing the action executed by the current optimization
  103683. * @return description string
  103684. */
  103685. ParticlesOptimization.prototype.getDescription = function () {
  103686. return "Turning particles on/off";
  103687. };
  103688. /**
  103689. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103690. * @param scene defines the current scene where to apply this optimization
  103691. * @param optimizer defines the current optimizer
  103692. * @returns true if everything that can be done was applied
  103693. */
  103694. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  103695. scene.particlesEnabled = optimizer.isInImprovementMode;
  103696. return true;
  103697. };
  103698. ;
  103699. return ParticlesOptimization;
  103700. }(SceneOptimization));
  103701. BABYLON.ParticlesOptimization = ParticlesOptimization;
  103702. /**
  103703. * Defines an optimization used to turn render targets off
  103704. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103705. */
  103706. var RenderTargetsOptimization = /** @class */ (function (_super) {
  103707. __extends(RenderTargetsOptimization, _super);
  103708. function RenderTargetsOptimization() {
  103709. return _super !== null && _super.apply(this, arguments) || this;
  103710. }
  103711. /**
  103712. * Gets a string describing the action executed by the current optimization
  103713. * @return description string
  103714. */
  103715. RenderTargetsOptimization.prototype.getDescription = function () {
  103716. return "Turning render targets off";
  103717. };
  103718. /**
  103719. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103720. * @param scene defines the current scene where to apply this optimization
  103721. * @param optimizer defines the current optimizer
  103722. * @returns true if everything that can be done was applied
  103723. */
  103724. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  103725. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  103726. return true;
  103727. };
  103728. ;
  103729. return RenderTargetsOptimization;
  103730. }(SceneOptimization));
  103731. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  103732. /**
  103733. * Defines an optimization used to merge meshes with compatible materials
  103734. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103735. */
  103736. var MergeMeshesOptimization = /** @class */ (function (_super) {
  103737. __extends(MergeMeshesOptimization, _super);
  103738. function MergeMeshesOptimization() {
  103739. var _this = _super !== null && _super.apply(this, arguments) || this;
  103740. _this._canBeMerged = function (abstractMesh) {
  103741. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  103742. return false;
  103743. }
  103744. var mesh = abstractMesh;
  103745. if (mesh.isDisposed()) {
  103746. return false;
  103747. }
  103748. if (!mesh.isVisible || !mesh.isEnabled()) {
  103749. return false;
  103750. }
  103751. if (mesh.instances.length > 0) {
  103752. return false;
  103753. }
  103754. if (mesh.skeleton || mesh.hasLODLevels) {
  103755. return false;
  103756. }
  103757. return true;
  103758. };
  103759. return _this;
  103760. }
  103761. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  103762. /**
  103763. * Gets or sets a boolean which defines if optimization octree has to be updated
  103764. */
  103765. get: function () {
  103766. return MergeMeshesOptimization._UpdateSelectionTree;
  103767. },
  103768. /**
  103769. * Gets or sets a boolean which defines if optimization octree has to be updated
  103770. */
  103771. set: function (value) {
  103772. MergeMeshesOptimization._UpdateSelectionTree = value;
  103773. },
  103774. enumerable: true,
  103775. configurable: true
  103776. });
  103777. /**
  103778. * Gets a string describing the action executed by the current optimization
  103779. * @return description string
  103780. */
  103781. MergeMeshesOptimization.prototype.getDescription = function () {
  103782. return "Merging similar meshes together";
  103783. };
  103784. /**
  103785. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103786. * @param scene defines the current scene where to apply this optimization
  103787. * @param optimizer defines the current optimizer
  103788. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  103789. * @returns true if everything that can be done was applied
  103790. */
  103791. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  103792. var globalPool = scene.meshes.slice(0);
  103793. var globalLength = globalPool.length;
  103794. for (var index = 0; index < globalLength; index++) {
  103795. var currentPool = new Array();
  103796. var current = globalPool[index];
  103797. // Checks
  103798. if (!this._canBeMerged(current)) {
  103799. continue;
  103800. }
  103801. currentPool.push(current);
  103802. // Find compatible meshes
  103803. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  103804. var otherMesh = globalPool[subIndex];
  103805. if (!this._canBeMerged(otherMesh)) {
  103806. continue;
  103807. }
  103808. if (otherMesh.material !== current.material) {
  103809. continue;
  103810. }
  103811. if (otherMesh.checkCollisions !== current.checkCollisions) {
  103812. continue;
  103813. }
  103814. currentPool.push(otherMesh);
  103815. globalLength--;
  103816. globalPool.splice(subIndex, 1);
  103817. subIndex--;
  103818. }
  103819. if (currentPool.length < 2) {
  103820. continue;
  103821. }
  103822. // Merge meshes
  103823. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  103824. }
  103825. // Call the octree system optimization if it is defined.
  103826. var sceneAsAny = scene;
  103827. if (sceneAsAny.createOrUpdateSelectionOctree) {
  103828. if (updateSelectionTree != undefined) {
  103829. if (updateSelectionTree) {
  103830. sceneAsAny.createOrUpdateSelectionOctree();
  103831. }
  103832. }
  103833. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  103834. sceneAsAny.createOrUpdateSelectionOctree();
  103835. }
  103836. }
  103837. return true;
  103838. };
  103839. ;
  103840. MergeMeshesOptimization._UpdateSelectionTree = false;
  103841. return MergeMeshesOptimization;
  103842. }(SceneOptimization));
  103843. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  103844. /**
  103845. * Defines a list of options used by SceneOptimizer
  103846. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103847. */
  103848. var SceneOptimizerOptions = /** @class */ (function () {
  103849. /**
  103850. * Creates a new list of options used by SceneOptimizer
  103851. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  103852. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  103853. */
  103854. function SceneOptimizerOptions(
  103855. /**
  103856. * Defines the target frame rate to reach (60 by default)
  103857. */
  103858. targetFrameRate,
  103859. /**
  103860. * Defines the interval between two checkes (2000ms by default)
  103861. */
  103862. trackerDuration) {
  103863. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  103864. if (trackerDuration === void 0) { trackerDuration = 2000; }
  103865. this.targetFrameRate = targetFrameRate;
  103866. this.trackerDuration = trackerDuration;
  103867. /**
  103868. * Gets the list of optimizations to apply
  103869. */
  103870. this.optimizations = new Array();
  103871. }
  103872. /**
  103873. * Add a new optimization
  103874. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  103875. * @returns the current SceneOptimizerOptions
  103876. */
  103877. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  103878. this.optimizations.push(optimization);
  103879. return this;
  103880. };
  103881. /**
  103882. * Add a new custom optimization
  103883. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  103884. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  103885. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103886. * @returns the current SceneOptimizerOptions
  103887. */
  103888. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  103889. if (priority === void 0) { priority = 0; }
  103890. var optimization = new CustomOptimization(priority);
  103891. optimization.onApply = onApply;
  103892. optimization.onGetDescription = onGetDescription;
  103893. this.optimizations.push(optimization);
  103894. return this;
  103895. };
  103896. /**
  103897. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  103898. * @param targetFrameRate defines the target frame rate (60 by default)
  103899. * @returns a SceneOptimizerOptions object
  103900. */
  103901. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  103902. var result = new SceneOptimizerOptions(targetFrameRate);
  103903. var priority = 0;
  103904. result.addOptimization(new MergeMeshesOptimization(priority));
  103905. result.addOptimization(new ShadowsOptimization(priority));
  103906. result.addOptimization(new LensFlaresOptimization(priority));
  103907. // Next priority
  103908. priority++;
  103909. result.addOptimization(new PostProcessesOptimization(priority));
  103910. result.addOptimization(new ParticlesOptimization(priority));
  103911. // Next priority
  103912. priority++;
  103913. result.addOptimization(new TextureOptimization(priority, 1024));
  103914. return result;
  103915. };
  103916. /**
  103917. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  103918. * @param targetFrameRate defines the target frame rate (60 by default)
  103919. * @returns a SceneOptimizerOptions object
  103920. */
  103921. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  103922. var result = new SceneOptimizerOptions(targetFrameRate);
  103923. var priority = 0;
  103924. result.addOptimization(new MergeMeshesOptimization(priority));
  103925. result.addOptimization(new ShadowsOptimization(priority));
  103926. result.addOptimization(new LensFlaresOptimization(priority));
  103927. // Next priority
  103928. priority++;
  103929. result.addOptimization(new PostProcessesOptimization(priority));
  103930. result.addOptimization(new ParticlesOptimization(priority));
  103931. // Next priority
  103932. priority++;
  103933. result.addOptimization(new TextureOptimization(priority, 512));
  103934. // Next priority
  103935. priority++;
  103936. result.addOptimization(new RenderTargetsOptimization(priority));
  103937. // Next priority
  103938. priority++;
  103939. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  103940. return result;
  103941. };
  103942. /**
  103943. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  103944. * @param targetFrameRate defines the target frame rate (60 by default)
  103945. * @returns a SceneOptimizerOptions object
  103946. */
  103947. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  103948. var result = new SceneOptimizerOptions(targetFrameRate);
  103949. var priority = 0;
  103950. result.addOptimization(new MergeMeshesOptimization(priority));
  103951. result.addOptimization(new ShadowsOptimization(priority));
  103952. result.addOptimization(new LensFlaresOptimization(priority));
  103953. // Next priority
  103954. priority++;
  103955. result.addOptimization(new PostProcessesOptimization(priority));
  103956. result.addOptimization(new ParticlesOptimization(priority));
  103957. // Next priority
  103958. priority++;
  103959. result.addOptimization(new TextureOptimization(priority, 256));
  103960. // Next priority
  103961. priority++;
  103962. result.addOptimization(new RenderTargetsOptimization(priority));
  103963. // Next priority
  103964. priority++;
  103965. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  103966. return result;
  103967. };
  103968. return SceneOptimizerOptions;
  103969. }());
  103970. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  103971. /**
  103972. * Class used to run optimizations in order to reach a target frame rate
  103973. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103974. */
  103975. var SceneOptimizer = /** @class */ (function () {
  103976. /**
  103977. * Creates a new SceneOptimizer
  103978. * @param scene defines the scene to work on
  103979. * @param options defines the options to use with the SceneOptimizer
  103980. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  103981. * @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)
  103982. */
  103983. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  103984. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  103985. if (improvementMode === void 0) { improvementMode = false; }
  103986. var _this = this;
  103987. this._isRunning = false;
  103988. this._currentPriorityLevel = 0;
  103989. this._targetFrameRate = 60;
  103990. this._trackerDuration = 2000;
  103991. this._currentFrameRate = 0;
  103992. this._improvementMode = false;
  103993. /**
  103994. * Defines an observable called when the optimizer reaches the target frame rate
  103995. */
  103996. this.onSuccessObservable = new BABYLON.Observable();
  103997. /**
  103998. * Defines an observable called when the optimizer enables an optimization
  103999. */
  104000. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  104001. /**
  104002. * Defines an observable called when the optimizer is not able to reach the target frame rate
  104003. */
  104004. this.onFailureObservable = new BABYLON.Observable();
  104005. if (!options) {
  104006. this._options = new SceneOptimizerOptions();
  104007. }
  104008. else {
  104009. this._options = options;
  104010. }
  104011. if (this._options.targetFrameRate) {
  104012. this._targetFrameRate = this._options.targetFrameRate;
  104013. }
  104014. if (this._options.trackerDuration) {
  104015. this._trackerDuration = this._options.trackerDuration;
  104016. }
  104017. if (autoGeneratePriorities) {
  104018. var priority = 0;
  104019. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  104020. var optim = _a[_i];
  104021. optim.priority = priority++;
  104022. }
  104023. }
  104024. this._improvementMode = improvementMode;
  104025. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  104026. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  104027. _this._sceneDisposeObserver = null;
  104028. _this.dispose();
  104029. });
  104030. }
  104031. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  104032. /**
  104033. * Gets a boolean indicating if the optimizer is in improvement mode
  104034. */
  104035. get: function () {
  104036. return this._improvementMode;
  104037. },
  104038. enumerable: true,
  104039. configurable: true
  104040. });
  104041. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  104042. /**
  104043. * Gets the current priority level (0 at start)
  104044. */
  104045. get: function () {
  104046. return this._currentPriorityLevel;
  104047. },
  104048. enumerable: true,
  104049. configurable: true
  104050. });
  104051. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  104052. /**
  104053. * Gets the current frame rate checked by the SceneOptimizer
  104054. */
  104055. get: function () {
  104056. return this._currentFrameRate;
  104057. },
  104058. enumerable: true,
  104059. configurable: true
  104060. });
  104061. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  104062. /**
  104063. * Gets or sets the current target frame rate (60 by default)
  104064. */
  104065. get: function () {
  104066. return this._targetFrameRate;
  104067. },
  104068. /**
  104069. * Gets or sets the current target frame rate (60 by default)
  104070. */
  104071. set: function (value) {
  104072. this._targetFrameRate = value;
  104073. },
  104074. enumerable: true,
  104075. configurable: true
  104076. });
  104077. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  104078. /**
  104079. * Gets or sets the current interval between two checks (every 2000ms by default)
  104080. */
  104081. get: function () {
  104082. return this._trackerDuration;
  104083. },
  104084. /**
  104085. * Gets or sets the current interval between two checks (every 2000ms by default)
  104086. */
  104087. set: function (value) {
  104088. this._trackerDuration = value;
  104089. },
  104090. enumerable: true,
  104091. configurable: true
  104092. });
  104093. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  104094. /**
  104095. * Gets the list of active optimizations
  104096. */
  104097. get: function () {
  104098. return this._options.optimizations;
  104099. },
  104100. enumerable: true,
  104101. configurable: true
  104102. });
  104103. /**
  104104. * Stops the current optimizer
  104105. */
  104106. SceneOptimizer.prototype.stop = function () {
  104107. this._isRunning = false;
  104108. };
  104109. /**
  104110. * Reset the optimizer to initial step (current priority level = 0)
  104111. */
  104112. SceneOptimizer.prototype.reset = function () {
  104113. this._currentPriorityLevel = 0;
  104114. };
  104115. /**
  104116. * Start the optimizer. By default it will try to reach a specific framerate
  104117. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  104118. */
  104119. SceneOptimizer.prototype.start = function () {
  104120. var _this = this;
  104121. if (this._isRunning) {
  104122. return;
  104123. }
  104124. this._isRunning = true;
  104125. // Let's wait for the scene to be ready before running our check
  104126. this._scene.executeWhenReady(function () {
  104127. setTimeout(function () {
  104128. _this._checkCurrentState();
  104129. }, _this._trackerDuration);
  104130. });
  104131. };
  104132. SceneOptimizer.prototype._checkCurrentState = function () {
  104133. var _this = this;
  104134. if (!this._isRunning) {
  104135. return;
  104136. }
  104137. var scene = this._scene;
  104138. var options = this._options;
  104139. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  104140. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  104141. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  104142. this._isRunning = false;
  104143. this.onSuccessObservable.notifyObservers(this);
  104144. return;
  104145. }
  104146. // Apply current level of optimizations
  104147. var allDone = true;
  104148. var noOptimizationApplied = true;
  104149. for (var index = 0; index < options.optimizations.length; index++) {
  104150. var optimization = options.optimizations[index];
  104151. if (optimization.priority === this._currentPriorityLevel) {
  104152. noOptimizationApplied = false;
  104153. allDone = allDone && optimization.apply(scene, this);
  104154. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  104155. }
  104156. }
  104157. // If no optimization was applied, this is a failure :(
  104158. if (noOptimizationApplied) {
  104159. this._isRunning = false;
  104160. this.onFailureObservable.notifyObservers(this);
  104161. return;
  104162. }
  104163. // If all optimizations were done, move to next level
  104164. if (allDone) {
  104165. this._currentPriorityLevel++;
  104166. }
  104167. // Let's the system running for a specific amount of time before checking FPS
  104168. scene.executeWhenReady(function () {
  104169. setTimeout(function () {
  104170. _this._checkCurrentState();
  104171. }, _this._trackerDuration);
  104172. });
  104173. };
  104174. /**
  104175. * Release all resources
  104176. */
  104177. SceneOptimizer.prototype.dispose = function () {
  104178. this.stop();
  104179. this.onSuccessObservable.clear();
  104180. this.onFailureObservable.clear();
  104181. this.onNewOptimizationAppliedObservable.clear();
  104182. if (this._sceneDisposeObserver) {
  104183. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  104184. }
  104185. };
  104186. /**
  104187. * Helper function to create a SceneOptimizer with one single line of code
  104188. * @param scene defines the scene to work on
  104189. * @param options defines the options to use with the SceneOptimizer
  104190. * @param onSuccess defines a callback to call on success
  104191. * @param onFailure defines a callback to call on failure
  104192. * @returns the new SceneOptimizer object
  104193. */
  104194. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  104195. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  104196. if (onSuccess) {
  104197. optimizer.onSuccessObservable.add(function () {
  104198. onSuccess();
  104199. });
  104200. }
  104201. if (onFailure) {
  104202. optimizer.onFailureObservable.add(function () {
  104203. onFailure();
  104204. });
  104205. }
  104206. optimizer.start();
  104207. return optimizer;
  104208. };
  104209. return SceneOptimizer;
  104210. }());
  104211. BABYLON.SceneOptimizer = SceneOptimizer;
  104212. })(BABYLON || (BABYLON = {}));
  104213. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  104214. var BABYLON;
  104215. (function (BABYLON) {
  104216. /**
  104217. * Gets the outline renderer associated with the scene
  104218. * @returns a OutlineRenderer
  104219. */
  104220. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  104221. if (!this._outlineRenderer) {
  104222. this._outlineRenderer = new OutlineRenderer(this);
  104223. }
  104224. return this._outlineRenderer;
  104225. };
  104226. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  104227. get: function () {
  104228. return this._renderOutline;
  104229. },
  104230. set: function (value) {
  104231. if (value) {
  104232. // Lazy Load the component.
  104233. this.getScene().getOutlineRenderer();
  104234. }
  104235. this._renderOutline = value;
  104236. },
  104237. enumerable: true,
  104238. configurable: true
  104239. });
  104240. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  104241. get: function () {
  104242. return this._renderOverlay;
  104243. },
  104244. set: function (value) {
  104245. if (value) {
  104246. // Lazy Load the component.
  104247. this.getScene().getOutlineRenderer();
  104248. }
  104249. this._renderOverlay = value;
  104250. },
  104251. enumerable: true,
  104252. configurable: true
  104253. });
  104254. /**
  104255. * This class is responsible to draw bothe outline/overlay of meshes.
  104256. * It should not be used directly but through the available method on mesh.
  104257. */
  104258. var OutlineRenderer = /** @class */ (function () {
  104259. /**
  104260. * Instantiates a new outline renderer. (There could be only one per scene).
  104261. * @param scene Defines the scene it belongs to
  104262. */
  104263. function OutlineRenderer(scene) {
  104264. /**
  104265. * The name of the component. Each component must have a unique name.
  104266. */
  104267. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  104268. /**
  104269. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  104270. */
  104271. this.zOffset = 1;
  104272. this.scene = scene;
  104273. this._engine = scene.getEngine();
  104274. this.scene._addComponent(this);
  104275. }
  104276. /**
  104277. * Register the component to one instance of a scene.
  104278. */
  104279. OutlineRenderer.prototype.register = function () {
  104280. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  104281. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  104282. };
  104283. /**
  104284. * Rebuilds the elements related to this component in case of
  104285. * context lost for instance.
  104286. */
  104287. OutlineRenderer.prototype.rebuild = function () {
  104288. // Nothing to do here.
  104289. };
  104290. /**
  104291. * Disposes the component and the associated ressources.
  104292. */
  104293. OutlineRenderer.prototype.dispose = function () {
  104294. // Nothing to do here.
  104295. };
  104296. /**
  104297. * Renders the outline in the canvas.
  104298. * @param subMesh Defines the sumesh to render
  104299. * @param batch Defines the batch of meshes in case of instances
  104300. * @param useOverlay Defines if the rendering is for the overlay or the outline
  104301. */
  104302. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  104303. var _this = this;
  104304. if (useOverlay === void 0) { useOverlay = false; }
  104305. var scene = this.scene;
  104306. var engine = scene.getEngine();
  104307. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  104308. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  104309. return;
  104310. }
  104311. var mesh = subMesh.getRenderingMesh();
  104312. var material = subMesh.getMaterial();
  104313. if (!material || !scene.activeCamera) {
  104314. return;
  104315. }
  104316. engine.enableEffect(this._effect);
  104317. // Logarithmic depth
  104318. if (material.useLogarithmicDepth) {
  104319. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  104320. }
  104321. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  104322. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  104323. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  104324. // Bones
  104325. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  104326. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  104327. }
  104328. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  104329. // Alpha test
  104330. if (material && material.needAlphaTesting()) {
  104331. var alphaTexture = material.getAlphaTestTexture();
  104332. if (alphaTexture) {
  104333. this._effect.setTexture("diffuseSampler", alphaTexture);
  104334. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  104335. }
  104336. }
  104337. engine.setZOffset(-this.zOffset);
  104338. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  104339. engine.setZOffset(0);
  104340. };
  104341. /**
  104342. * Returns whether or not the outline renderer is ready for a given submesh.
  104343. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  104344. * @param subMesh Defines the submesh to check readyness for
  104345. * @param useInstances Defines wheter wee are trying to render instances or not
  104346. * @returns true if ready otherwise false
  104347. */
  104348. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  104349. var defines = [];
  104350. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  104351. var mesh = subMesh.getMesh();
  104352. var material = subMesh.getMaterial();
  104353. if (material) {
  104354. // Alpha test
  104355. if (material.needAlphaTesting()) {
  104356. defines.push("#define ALPHATEST");
  104357. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104358. attribs.push(BABYLON.VertexBuffer.UVKind);
  104359. defines.push("#define UV1");
  104360. }
  104361. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  104362. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  104363. defines.push("#define UV2");
  104364. }
  104365. }
  104366. //Logarithmic depth
  104367. if (material.useLogarithmicDepth) {
  104368. defines.push("#define LOGARITHMICDEPTH");
  104369. }
  104370. }
  104371. // Bones
  104372. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  104373. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  104374. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  104375. if (mesh.numBoneInfluencers > 4) {
  104376. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  104377. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  104378. }
  104379. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  104380. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  104381. }
  104382. else {
  104383. defines.push("#define NUM_BONE_INFLUENCERS 0");
  104384. }
  104385. // Instances
  104386. if (useInstances) {
  104387. defines.push("#define INSTANCES");
  104388. attribs.push("world0");
  104389. attribs.push("world1");
  104390. attribs.push("world2");
  104391. attribs.push("world3");
  104392. }
  104393. // Get correct effect
  104394. var join = defines.join("\n");
  104395. if (this._cachedDefines !== join) {
  104396. this._cachedDefines = join;
  104397. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  104398. }
  104399. return this._effect.isReady();
  104400. };
  104401. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  104402. // Outline - step 1
  104403. this._savedDepthWrite = this._engine.getDepthWrite();
  104404. if (mesh.renderOutline) {
  104405. this._engine.setDepthWrite(false);
  104406. this.render(subMesh, batch);
  104407. this._engine.setDepthWrite(this._savedDepthWrite);
  104408. }
  104409. };
  104410. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  104411. // Outline - step 2
  104412. if (mesh.renderOutline && this._savedDepthWrite) {
  104413. this._engine.setDepthWrite(true);
  104414. this._engine.setColorWrite(false);
  104415. this.render(subMesh, batch);
  104416. this._engine.setColorWrite(true);
  104417. }
  104418. // Overlay
  104419. if (mesh.renderOverlay) {
  104420. var currentMode = this._engine.getAlphaMode();
  104421. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  104422. this.render(subMesh, batch, true);
  104423. this._engine.setAlphaMode(currentMode);
  104424. }
  104425. };
  104426. return OutlineRenderer;
  104427. }());
  104428. BABYLON.OutlineRenderer = OutlineRenderer;
  104429. })(BABYLON || (BABYLON = {}));
  104430. //# sourceMappingURL=babylon.outlineRenderer.js.map
  104431. var BABYLON;
  104432. (function (BABYLON) {
  104433. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  104434. if (this._edgesRenderer) {
  104435. this._edgesRenderer.dispose();
  104436. this._edgesRenderer = null;
  104437. }
  104438. return this;
  104439. };
  104440. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  104441. if (epsilon === void 0) { epsilon = 0.95; }
  104442. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104443. this.disableEdgesRendering();
  104444. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  104445. return this;
  104446. };
  104447. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  104448. get: function () {
  104449. return this._edgesRenderer;
  104450. },
  104451. enumerable: true,
  104452. configurable: true
  104453. });
  104454. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  104455. if (epsilon === void 0) { epsilon = 0.95; }
  104456. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104457. this.disableEdgesRendering();
  104458. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  104459. return this;
  104460. };
  104461. /**
  104462. * FaceAdjacencies Helper class to generate edges
  104463. */
  104464. var FaceAdjacencies = /** @class */ (function () {
  104465. function FaceAdjacencies() {
  104466. this.edges = new Array();
  104467. this.edgesConnectedCount = 0;
  104468. }
  104469. return FaceAdjacencies;
  104470. }());
  104471. /**
  104472. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  104473. */
  104474. var EdgesRenderer = /** @class */ (function () {
  104475. /**
  104476. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  104477. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  104478. * @param source Mesh used to create edges
  104479. * @param epsilon sum of angles in adjacency to check for edge
  104480. * @param checkVerticesInsteadOfIndices
  104481. * @param generateEdgesLines - should generate Lines or only prepare resources.
  104482. */
  104483. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  104484. if (epsilon === void 0) { epsilon = 0.95; }
  104485. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104486. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  104487. var _this = this;
  104488. /**
  104489. * Define the size of the edges with an orthographic camera
  104490. */
  104491. this.edgesWidthScalerForOrthographic = 1000.0;
  104492. /**
  104493. * Define the size of the edges with a perspective camera
  104494. */
  104495. this.edgesWidthScalerForPerspective = 50.0;
  104496. this._linesPositions = new Array();
  104497. this._linesNormals = new Array();
  104498. this._linesIndices = new Array();
  104499. this._buffers = {};
  104500. this._checkVerticesInsteadOfIndices = false;
  104501. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  104502. this.isEnabled = true;
  104503. this._source = source;
  104504. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  104505. this._epsilon = epsilon;
  104506. this._prepareRessources();
  104507. if (generateEdgesLines) {
  104508. this._generateEdgesLines();
  104509. }
  104510. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  104511. _this._rebuild();
  104512. });
  104513. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  104514. _this.dispose();
  104515. });
  104516. }
  104517. EdgesRenderer.prototype._prepareRessources = function () {
  104518. if (this._lineShader) {
  104519. return;
  104520. }
  104521. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  104522. attributes: ["position", "normal"],
  104523. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  104524. });
  104525. this._lineShader.disableDepthWrite = true;
  104526. this._lineShader.backFaceCulling = false;
  104527. };
  104528. /** @hidden */
  104529. EdgesRenderer.prototype._rebuild = function () {
  104530. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  104531. if (buffer) {
  104532. buffer._rebuild();
  104533. }
  104534. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  104535. if (buffer) {
  104536. buffer._rebuild();
  104537. }
  104538. var scene = this._source.getScene();
  104539. var engine = scene.getEngine();
  104540. this._ib = engine.createIndexBuffer(this._linesIndices);
  104541. };
  104542. /**
  104543. * Releases the required resources for the edges renderer
  104544. */
  104545. EdgesRenderer.prototype.dispose = function () {
  104546. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  104547. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  104548. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  104549. if (buffer) {
  104550. buffer.dispose();
  104551. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  104552. }
  104553. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  104554. if (buffer) {
  104555. buffer.dispose();
  104556. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  104557. }
  104558. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  104559. this._lineShader.dispose();
  104560. };
  104561. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  104562. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  104563. return 0;
  104564. }
  104565. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  104566. return 1;
  104567. }
  104568. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  104569. return 2;
  104570. }
  104571. return -1;
  104572. };
  104573. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  104574. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  104575. return 0;
  104576. }
  104577. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  104578. return 1;
  104579. }
  104580. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  104581. return 2;
  104582. }
  104583. return -1;
  104584. };
  104585. /**
  104586. * Checks if the pair of p0 and p1 is en edge
  104587. * @param faceIndex
  104588. * @param edge
  104589. * @param faceNormals
  104590. * @param p0
  104591. * @param p1
  104592. * @private
  104593. */
  104594. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  104595. var needToCreateLine;
  104596. if (edge === undefined) {
  104597. needToCreateLine = true;
  104598. }
  104599. else {
  104600. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  104601. needToCreateLine = dotProduct < this._epsilon;
  104602. }
  104603. if (needToCreateLine) {
  104604. var offset = this._linesPositions.length / 3;
  104605. var normal = p0.subtract(p1);
  104606. normal.normalize();
  104607. // Positions
  104608. this._linesPositions.push(p0.x);
  104609. this._linesPositions.push(p0.y);
  104610. this._linesPositions.push(p0.z);
  104611. this._linesPositions.push(p0.x);
  104612. this._linesPositions.push(p0.y);
  104613. this._linesPositions.push(p0.z);
  104614. this._linesPositions.push(p1.x);
  104615. this._linesPositions.push(p1.y);
  104616. this._linesPositions.push(p1.z);
  104617. this._linesPositions.push(p1.x);
  104618. this._linesPositions.push(p1.y);
  104619. this._linesPositions.push(p1.z);
  104620. // Normals
  104621. this._linesNormals.push(p1.x);
  104622. this._linesNormals.push(p1.y);
  104623. this._linesNormals.push(p1.z);
  104624. this._linesNormals.push(-1);
  104625. this._linesNormals.push(p1.x);
  104626. this._linesNormals.push(p1.y);
  104627. this._linesNormals.push(p1.z);
  104628. this._linesNormals.push(1);
  104629. this._linesNormals.push(p0.x);
  104630. this._linesNormals.push(p0.y);
  104631. this._linesNormals.push(p0.z);
  104632. this._linesNormals.push(-1);
  104633. this._linesNormals.push(p0.x);
  104634. this._linesNormals.push(p0.y);
  104635. this._linesNormals.push(p0.z);
  104636. this._linesNormals.push(1);
  104637. // Indices
  104638. this._linesIndices.push(offset);
  104639. this._linesIndices.push(offset + 1);
  104640. this._linesIndices.push(offset + 2);
  104641. this._linesIndices.push(offset);
  104642. this._linesIndices.push(offset + 2);
  104643. this._linesIndices.push(offset + 3);
  104644. }
  104645. };
  104646. /**
  104647. * Generates lines edges from adjacencjes
  104648. * @private
  104649. */
  104650. EdgesRenderer.prototype._generateEdgesLines = function () {
  104651. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104652. var indices = this._source.getIndices();
  104653. if (!indices || !positions) {
  104654. return;
  104655. }
  104656. // First let's find adjacencies
  104657. var adjacencies = new Array();
  104658. var faceNormals = new Array();
  104659. var index;
  104660. var faceAdjacencies;
  104661. // Prepare faces
  104662. for (index = 0; index < indices.length; index += 3) {
  104663. faceAdjacencies = new FaceAdjacencies();
  104664. var p0Index = indices[index];
  104665. var p1Index = indices[index + 1];
  104666. var p2Index = indices[index + 2];
  104667. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  104668. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  104669. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  104670. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  104671. faceNormal.normalize();
  104672. faceNormals.push(faceNormal);
  104673. adjacencies.push(faceAdjacencies);
  104674. }
  104675. // Scan
  104676. for (index = 0; index < adjacencies.length; index++) {
  104677. faceAdjacencies = adjacencies[index];
  104678. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  104679. var otherFaceAdjacencies = adjacencies[otherIndex];
  104680. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  104681. break;
  104682. }
  104683. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  104684. continue;
  104685. }
  104686. var otherP0 = indices[otherIndex * 3];
  104687. var otherP1 = indices[otherIndex * 3 + 1];
  104688. var otherP2 = indices[otherIndex * 3 + 2];
  104689. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  104690. var otherEdgeIndex = 0;
  104691. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  104692. continue;
  104693. }
  104694. switch (edgeIndex) {
  104695. case 0:
  104696. if (this._checkVerticesInsteadOfIndices) {
  104697. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104698. }
  104699. else {
  104700. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  104701. }
  104702. break;
  104703. case 1:
  104704. if (this._checkVerticesInsteadOfIndices) {
  104705. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104706. }
  104707. else {
  104708. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  104709. }
  104710. break;
  104711. case 2:
  104712. if (this._checkVerticesInsteadOfIndices) {
  104713. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104714. }
  104715. else {
  104716. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  104717. }
  104718. break;
  104719. }
  104720. if (otherEdgeIndex === -1) {
  104721. continue;
  104722. }
  104723. faceAdjacencies.edges[edgeIndex] = otherIndex;
  104724. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  104725. faceAdjacencies.edgesConnectedCount++;
  104726. otherFaceAdjacencies.edgesConnectedCount++;
  104727. if (faceAdjacencies.edgesConnectedCount === 3) {
  104728. break;
  104729. }
  104730. }
  104731. }
  104732. }
  104733. // Create lines
  104734. for (index = 0; index < adjacencies.length; index++) {
  104735. // 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
  104736. var current = adjacencies[index];
  104737. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  104738. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  104739. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  104740. }
  104741. // Merge into a single mesh
  104742. var engine = this._source.getScene().getEngine();
  104743. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  104744. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  104745. this._ib = engine.createIndexBuffer(this._linesIndices);
  104746. this._indicesCount = this._linesIndices.length;
  104747. };
  104748. /**
  104749. * Checks wether or not the edges renderer is ready to render.
  104750. * @return true if ready, otherwise false.
  104751. */
  104752. EdgesRenderer.prototype.isReady = function () {
  104753. return this._lineShader.isReady();
  104754. };
  104755. /**
  104756. * Renders the edges of the attached mesh,
  104757. */
  104758. EdgesRenderer.prototype.render = function () {
  104759. var scene = this._source.getScene();
  104760. if (!this.isReady() || !scene.activeCamera) {
  104761. return;
  104762. }
  104763. var engine = scene.getEngine();
  104764. this._lineShader._preBind();
  104765. if (this._source.edgesColor.a !== 1) {
  104766. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  104767. }
  104768. else {
  104769. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  104770. }
  104771. // VBOs
  104772. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  104773. scene.resetCachedMaterial();
  104774. this._lineShader.setColor4("color", this._source.edgesColor);
  104775. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  104776. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  104777. }
  104778. else {
  104779. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  104780. }
  104781. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  104782. this._lineShader.bind(this._source.getWorldMatrix());
  104783. // Draw order
  104784. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  104785. this._lineShader.unbind();
  104786. };
  104787. return EdgesRenderer;
  104788. }());
  104789. BABYLON.EdgesRenderer = EdgesRenderer;
  104790. })(BABYLON || (BABYLON = {}));
  104791. //# sourceMappingURL=babylon.edgesRenderer.js.map
  104792. var BABYLON;
  104793. (function (BABYLON) {
  104794. /**
  104795. * FaceAdjacencies Helper class to generate edges
  104796. */
  104797. var FaceAdjacencies = /** @class */ (function () {
  104798. function FaceAdjacencies() {
  104799. this.edges = new Array();
  104800. this.edgesConnectedCount = 0;
  104801. }
  104802. return FaceAdjacencies;
  104803. }());
  104804. /**
  104805. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  104806. */
  104807. var LineEdgesRenderer = /** @class */ (function (_super) {
  104808. __extends(LineEdgesRenderer, _super);
  104809. /**
  104810. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  104811. * @param source LineMesh used to generate edges
  104812. * @param epsilon not important (specified angle for edge detection)
  104813. * @param checkVerticesInsteadOfIndices not important for LineMesh
  104814. */
  104815. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  104816. if (epsilon === void 0) { epsilon = 0.95; }
  104817. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104818. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  104819. _this._generateEdgesLines();
  104820. return _this;
  104821. }
  104822. /**
  104823. * Always create the edge since its a line so only important things are p0 and p1
  104824. * @param faceIndex not important for LineMesh
  104825. * @param edge not important for LineMesh
  104826. * @param faceNormals not important for LineMesh
  104827. * @param p0 beginnig of line
  104828. * @param p1 end of line
  104829. */
  104830. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  104831. var offset = this._linesPositions.length / 3;
  104832. var normal = p0.subtract(p1);
  104833. normal.normalize();
  104834. // Positions
  104835. this._linesPositions.push(p0.x);
  104836. this._linesPositions.push(p0.y);
  104837. this._linesPositions.push(p0.z);
  104838. this._linesPositions.push(p0.x);
  104839. this._linesPositions.push(p0.y);
  104840. this._linesPositions.push(p0.z);
  104841. this._linesPositions.push(p1.x);
  104842. this._linesPositions.push(p1.y);
  104843. this._linesPositions.push(p1.z);
  104844. this._linesPositions.push(p1.x);
  104845. this._linesPositions.push(p1.y);
  104846. this._linesPositions.push(p1.z);
  104847. // Normals
  104848. this._linesNormals.push(p1.x);
  104849. this._linesNormals.push(p1.y);
  104850. this._linesNormals.push(p1.z);
  104851. this._linesNormals.push(-1);
  104852. this._linesNormals.push(p1.x);
  104853. this._linesNormals.push(p1.y);
  104854. this._linesNormals.push(p1.z);
  104855. this._linesNormals.push(1);
  104856. this._linesNormals.push(p0.x);
  104857. this._linesNormals.push(p0.y);
  104858. this._linesNormals.push(p0.z);
  104859. this._linesNormals.push(-1);
  104860. this._linesNormals.push(p0.x);
  104861. this._linesNormals.push(p0.y);
  104862. this._linesNormals.push(p0.z);
  104863. this._linesNormals.push(1);
  104864. // Indices
  104865. this._linesIndices.push(offset);
  104866. this._linesIndices.push(offset + 1);
  104867. this._linesIndices.push(offset + 2);
  104868. this._linesIndices.push(offset);
  104869. this._linesIndices.push(offset + 2);
  104870. this._linesIndices.push(offset + 3);
  104871. };
  104872. /**
  104873. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  104874. */
  104875. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  104876. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104877. var indices = this._source.getIndices();
  104878. if (!indices || !positions) {
  104879. return;
  104880. }
  104881. // First let's find adjacencies
  104882. var adjacencies = new Array();
  104883. var faceNormals = new Array();
  104884. var index;
  104885. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  104886. var currentAdjecancy = new FaceAdjacencies();
  104887. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  104888. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  104889. adjacencies.push(currentAdjecancy);
  104890. }
  104891. // Create lines
  104892. for (index = 0; index < adjacencies.length; index++) {
  104893. // 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
  104894. var current = adjacencies[index];
  104895. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  104896. }
  104897. // Merge into a single mesh
  104898. var engine = this._source.getScene().getEngine();
  104899. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  104900. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  104901. this._ib = engine.createIndexBuffer(this._linesIndices);
  104902. this._indicesCount = this._linesIndices.length;
  104903. };
  104904. return LineEdgesRenderer;
  104905. }(BABYLON.EdgesRenderer));
  104906. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  104907. })(BABYLON || (BABYLON = {}));
  104908. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  104909. var BABYLON;
  104910. (function (BABYLON) {
  104911. // Adds the parser to the scene parsers.
  104912. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  104913. if (parsedData.effectLayers) {
  104914. if (!container.effectLayers) {
  104915. container.effectLayers = new Array();
  104916. }
  104917. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  104918. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  104919. container.effectLayers.push(effectLayer);
  104920. }
  104921. }
  104922. });
  104923. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  104924. var index = this.effectLayers.indexOf(toRemove);
  104925. if (index !== -1) {
  104926. this.effectLayers.splice(index, 1);
  104927. }
  104928. return index;
  104929. };
  104930. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  104931. this.effectLayers.push(newEffectLayer);
  104932. };
  104933. /**
  104934. * Defines the layer scene component responsible to manage any effect layers
  104935. * in a given scene.
  104936. */
  104937. var EffectLayerSceneComponent = /** @class */ (function () {
  104938. /**
  104939. * Creates a new instance of the component for the given scene
  104940. * @param scene Defines the scene to register the component in
  104941. */
  104942. function EffectLayerSceneComponent(scene) {
  104943. /**
  104944. * The component name helpfull to identify the component in the list of scene components.
  104945. */
  104946. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  104947. this._renderEffects = false;
  104948. this._needStencil = false;
  104949. this._previousStencilState = false;
  104950. this.scene = scene;
  104951. this._engine = scene.getEngine();
  104952. scene.effectLayers = new Array();
  104953. }
  104954. /**
  104955. * Registers the component in a given scene
  104956. */
  104957. EffectLayerSceneComponent.prototype.register = function () {
  104958. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  104959. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  104960. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  104961. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  104962. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  104963. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  104964. };
  104965. /**
  104966. * Rebuilds the elements related to this component in case of
  104967. * context lost for instance.
  104968. */
  104969. EffectLayerSceneComponent.prototype.rebuild = function () {
  104970. var layers = this.scene.effectLayers;
  104971. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  104972. var effectLayer = layers_1[_i];
  104973. effectLayer._rebuild();
  104974. }
  104975. };
  104976. /**
  104977. * Serializes the component data to the specified json object
  104978. * @param serializationObject The object to serialize to
  104979. */
  104980. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  104981. // Effect layers
  104982. serializationObject.effectLayers = [];
  104983. var layers = this.scene.effectLayers;
  104984. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  104985. var effectLayer = layers_2[_i];
  104986. if (effectLayer.serialize) {
  104987. serializationObject.effectLayers.push(effectLayer.serialize());
  104988. }
  104989. }
  104990. };
  104991. /**
  104992. * Adds all the element from the container to the scene
  104993. * @param container the container holding the elements
  104994. */
  104995. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  104996. var _this = this;
  104997. if (!container.effectLayers) {
  104998. return;
  104999. }
  105000. container.effectLayers.forEach(function (o) {
  105001. _this.scene.addEffectLayer(o);
  105002. });
  105003. };
  105004. /**
  105005. * Removes all the elements in the container from the scene
  105006. * @param container contains the elements to remove
  105007. */
  105008. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  105009. var _this = this;
  105010. if (!container.effectLayers) {
  105011. return;
  105012. }
  105013. container.effectLayers.forEach(function (o) {
  105014. _this.scene.removeEffectLayer(o);
  105015. });
  105016. };
  105017. /**
  105018. * Disposes the component and the associated ressources.
  105019. */
  105020. EffectLayerSceneComponent.prototype.dispose = function () {
  105021. var layers = this.scene.effectLayers;
  105022. while (layers.length) {
  105023. layers[0].dispose();
  105024. }
  105025. };
  105026. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  105027. var layers = this.scene.effectLayers;
  105028. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  105029. var layer = layers_3[_i];
  105030. if (!layer.hasMesh(mesh)) {
  105031. continue;
  105032. }
  105033. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  105034. var subMesh = _b[_a];
  105035. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  105036. return false;
  105037. }
  105038. }
  105039. }
  105040. return true;
  105041. };
  105042. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  105043. this._renderEffects = false;
  105044. this._needStencil = false;
  105045. var layers = this.scene.effectLayers;
  105046. if (layers && layers.length > 0) {
  105047. this._previousStencilState = this._engine.getStencilBuffer();
  105048. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  105049. var effectLayer = layers_4[_i];
  105050. if (effectLayer.shouldRender() &&
  105051. (!effectLayer.camera ||
  105052. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  105053. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  105054. this._renderEffects = true;
  105055. this._needStencil = this._needStencil || effectLayer.needStencil();
  105056. var renderTarget = effectLayer._mainTexture;
  105057. if (renderTarget._shouldRender()) {
  105058. this.scene.incrementRenderId();
  105059. renderTarget.render(false, false);
  105060. }
  105061. }
  105062. }
  105063. this.scene.incrementRenderId();
  105064. }
  105065. };
  105066. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  105067. // Activate effect Layer stencil
  105068. if (this._needStencil) {
  105069. this._engine.setStencilBuffer(true);
  105070. }
  105071. };
  105072. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  105073. // Restore effect Layer stencil
  105074. if (this._needStencil) {
  105075. this._engine.setStencilBuffer(this._previousStencilState);
  105076. }
  105077. };
  105078. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  105079. if (this._renderEffects) {
  105080. this._engine.setDepthBuffer(false);
  105081. var layers = this.scene.effectLayers;
  105082. for (var i = 0; i < layers.length; i++) {
  105083. var effectLayer = layers[i];
  105084. if (effectLayer.renderingGroupId === renderingGroupId) {
  105085. if (effectLayer.shouldRender()) {
  105086. effectLayer.render();
  105087. }
  105088. }
  105089. }
  105090. this._engine.setDepthBuffer(true);
  105091. }
  105092. };
  105093. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  105094. if (this._renderEffects) {
  105095. this._draw(-1);
  105096. }
  105097. };
  105098. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  105099. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  105100. this._draw(index);
  105101. }
  105102. };
  105103. return EffectLayerSceneComponent;
  105104. }());
  105105. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  105106. })(BABYLON || (BABYLON = {}));
  105107. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  105108. var __assign = (this && this.__assign) || function () {
  105109. __assign = Object.assign || function(t) {
  105110. for (var s, i = 1, n = arguments.length; i < n; i++) {
  105111. s = arguments[i];
  105112. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  105113. t[p] = s[p];
  105114. }
  105115. return t;
  105116. };
  105117. return __assign.apply(this, arguments);
  105118. };
  105119. var BABYLON;
  105120. (function (BABYLON) {
  105121. /**
  105122. * The effect layer Helps adding post process effect blended with the main pass.
  105123. *
  105124. * This can be for instance use to generate glow or higlight effects on the scene.
  105125. *
  105126. * The effect layer class can not be used directly and is intented to inherited from to be
  105127. * customized per effects.
  105128. */
  105129. var EffectLayer = /** @class */ (function () {
  105130. /**
  105131. * Instantiates a new effect Layer and references it in the scene.
  105132. * @param name The name of the layer
  105133. * @param scene The scene to use the layer in
  105134. */
  105135. function EffectLayer(
  105136. /** The Friendly of the effect in the scene */
  105137. name, scene) {
  105138. this._vertexBuffers = {};
  105139. this._maxSize = 0;
  105140. this._mainTextureDesiredSize = { width: 0, height: 0 };
  105141. this._shouldRender = true;
  105142. this._postProcesses = [];
  105143. this._textures = [];
  105144. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  105145. /**
  105146. * The clear color of the texture used to generate the glow map.
  105147. */
  105148. this.neutralColor = new BABYLON.Color4();
  105149. /**
  105150. * Specifies wether the highlight layer is enabled or not.
  105151. */
  105152. this.isEnabled = true;
  105153. /**
  105154. * An event triggered when the effect layer has been disposed.
  105155. */
  105156. this.onDisposeObservable = new BABYLON.Observable();
  105157. /**
  105158. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  105159. */
  105160. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  105161. /**
  105162. * An event triggered when the generated texture is being merged in the scene.
  105163. */
  105164. this.onBeforeComposeObservable = new BABYLON.Observable();
  105165. /**
  105166. * An event triggered when the generated texture has been merged in the scene.
  105167. */
  105168. this.onAfterComposeObservable = new BABYLON.Observable();
  105169. /**
  105170. * An event triggered when the efffect layer changes its size.
  105171. */
  105172. this.onSizeChangedObservable = new BABYLON.Observable();
  105173. this.name = name;
  105174. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  105175. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  105176. if (!component) {
  105177. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  105178. this._scene._addComponent(component);
  105179. }
  105180. this._engine = this._scene.getEngine();
  105181. this._maxSize = this._engine.getCaps().maxTextureSize;
  105182. this._scene.effectLayers.push(this);
  105183. // Generate Buffers
  105184. this._generateIndexBuffer();
  105185. this._genrateVertexBuffer();
  105186. }
  105187. Object.defineProperty(EffectLayer.prototype, "camera", {
  105188. /**
  105189. * Gets the camera attached to the layer.
  105190. */
  105191. get: function () {
  105192. return this._effectLayerOptions.camera;
  105193. },
  105194. enumerable: true,
  105195. configurable: true
  105196. });
  105197. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  105198. /**
  105199. * Gets the rendering group id the layer should render in.
  105200. */
  105201. get: function () {
  105202. return this._effectLayerOptions.renderingGroupId;
  105203. },
  105204. enumerable: true,
  105205. configurable: true
  105206. });
  105207. /**
  105208. * Initializes the effect layer with the required options.
  105209. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  105210. */
  105211. EffectLayer.prototype._init = function (options) {
  105212. // Adapt options
  105213. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  105214. this._setMainTextureSize();
  105215. this._createMainTexture();
  105216. this._createTextureAndPostProcesses();
  105217. this._mergeEffect = this._createMergeEffect();
  105218. };
  105219. /**
  105220. * Generates the index buffer of the full screen quad blending to the main canvas.
  105221. */
  105222. EffectLayer.prototype._generateIndexBuffer = function () {
  105223. // Indices
  105224. var indices = [];
  105225. indices.push(0);
  105226. indices.push(1);
  105227. indices.push(2);
  105228. indices.push(0);
  105229. indices.push(2);
  105230. indices.push(3);
  105231. this._indexBuffer = this._engine.createIndexBuffer(indices);
  105232. };
  105233. /**
  105234. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  105235. */
  105236. EffectLayer.prototype._genrateVertexBuffer = function () {
  105237. // VBO
  105238. var vertices = [];
  105239. vertices.push(1, 1);
  105240. vertices.push(-1, 1);
  105241. vertices.push(-1, -1);
  105242. vertices.push(1, -1);
  105243. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  105244. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  105245. };
  105246. /**
  105247. * Sets the main texture desired size which is the closest power of two
  105248. * of the engine canvas size.
  105249. */
  105250. EffectLayer.prototype._setMainTextureSize = function () {
  105251. if (this._effectLayerOptions.mainTextureFixedSize) {
  105252. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  105253. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  105254. }
  105255. else {
  105256. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  105257. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  105258. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  105259. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  105260. }
  105261. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  105262. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  105263. };
  105264. /**
  105265. * Creates the main texture for the effect layer.
  105266. */
  105267. EffectLayer.prototype._createMainTexture = function () {
  105268. var _this = this;
  105269. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  105270. width: this._mainTextureDesiredSize.width,
  105271. height: this._mainTextureDesiredSize.height
  105272. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  105273. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  105274. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105275. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105276. this._mainTexture.anisotropicFilteringLevel = 1;
  105277. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105278. this._mainTexture.renderParticles = false;
  105279. this._mainTexture.renderList = null;
  105280. this._mainTexture.ignoreCameraViewport = true;
  105281. // Custom render function
  105282. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  105283. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  105284. var index;
  105285. var engine = _this._scene.getEngine();
  105286. if (depthOnlySubMeshes.length) {
  105287. engine.setColorWrite(false);
  105288. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  105289. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  105290. }
  105291. engine.setColorWrite(true);
  105292. }
  105293. for (index = 0; index < opaqueSubMeshes.length; index++) {
  105294. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  105295. }
  105296. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  105297. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  105298. }
  105299. for (index = 0; index < transparentSubMeshes.length; index++) {
  105300. _this._renderSubMesh(transparentSubMeshes.data[index]);
  105301. }
  105302. };
  105303. this._mainTexture.onClearObservable.add(function (engine) {
  105304. engine.clear(_this.neutralColor, true, true, true);
  105305. });
  105306. };
  105307. /**
  105308. * Checks for the readiness of the element composing the layer.
  105309. * @param subMesh the mesh to check for
  105310. * @param useInstances specify wether or not to use instances to render the mesh
  105311. * @param emissiveTexture the associated emissive texture used to generate the glow
  105312. * @return true if ready otherwise, false
  105313. */
  105314. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  105315. var material = subMesh.getMaterial();
  105316. if (!material) {
  105317. return false;
  105318. }
  105319. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  105320. return false;
  105321. }
  105322. var defines = [];
  105323. var attribs = [BABYLON.VertexBuffer.PositionKind];
  105324. var mesh = subMesh.getMesh();
  105325. var uv1 = false;
  105326. var uv2 = false;
  105327. // Alpha test
  105328. if (material && material.needAlphaTesting()) {
  105329. var alphaTexture = material.getAlphaTestTexture();
  105330. if (alphaTexture) {
  105331. defines.push("#define ALPHATEST");
  105332. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  105333. alphaTexture.coordinatesIndex === 1) {
  105334. defines.push("#define DIFFUSEUV2");
  105335. uv2 = true;
  105336. }
  105337. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105338. defines.push("#define DIFFUSEUV1");
  105339. uv1 = true;
  105340. }
  105341. }
  105342. }
  105343. // Emissive
  105344. if (emissiveTexture) {
  105345. defines.push("#define EMISSIVE");
  105346. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  105347. emissiveTexture.coordinatesIndex === 1) {
  105348. defines.push("#define EMISSIVEUV2");
  105349. uv2 = true;
  105350. }
  105351. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105352. defines.push("#define EMISSIVEUV1");
  105353. uv1 = true;
  105354. }
  105355. }
  105356. if (uv1) {
  105357. attribs.push(BABYLON.VertexBuffer.UVKind);
  105358. defines.push("#define UV1");
  105359. }
  105360. if (uv2) {
  105361. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105362. defines.push("#define UV2");
  105363. }
  105364. // Bones
  105365. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  105366. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  105367. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  105368. if (mesh.numBoneInfluencers > 4) {
  105369. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  105370. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  105371. }
  105372. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  105373. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  105374. }
  105375. else {
  105376. defines.push("#define NUM_BONE_INFLUENCERS 0");
  105377. }
  105378. // Morph targets
  105379. var manager = mesh.morphTargetManager;
  105380. var morphInfluencers = 0;
  105381. if (manager) {
  105382. if (manager.numInfluencers > 0) {
  105383. defines.push("#define MORPHTARGETS");
  105384. morphInfluencers = manager.numInfluencers;
  105385. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  105386. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  105387. }
  105388. }
  105389. // Instances
  105390. if (useInstances) {
  105391. defines.push("#define INSTANCES");
  105392. attribs.push("world0");
  105393. attribs.push("world1");
  105394. attribs.push("world2");
  105395. attribs.push("world3");
  105396. }
  105397. // Get correct effect
  105398. var join = defines.join("\n");
  105399. if (this._cachedDefines !== join) {
  105400. this._cachedDefines = join;
  105401. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  105402. }
  105403. return this._effectLayerMapGenerationEffect.isReady();
  105404. };
  105405. /**
  105406. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  105407. */
  105408. EffectLayer.prototype.render = function () {
  105409. var currentEffect = this._mergeEffect;
  105410. // Check
  105411. if (!currentEffect.isReady())
  105412. return;
  105413. for (var i = 0; i < this._postProcesses.length; i++) {
  105414. if (!this._postProcesses[i].isReady()) {
  105415. return;
  105416. }
  105417. }
  105418. var engine = this._scene.getEngine();
  105419. this.onBeforeComposeObservable.notifyObservers(this);
  105420. // Render
  105421. engine.enableEffect(currentEffect);
  105422. engine.setState(false);
  105423. // VBOs
  105424. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  105425. // Cache
  105426. var previousAlphaMode = engine.getAlphaMode();
  105427. // Go Blend.
  105428. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  105429. // Blends the map on the main canvas.
  105430. this._internalRender(currentEffect);
  105431. // Restore Alpha
  105432. engine.setAlphaMode(previousAlphaMode);
  105433. this.onAfterComposeObservable.notifyObservers(this);
  105434. // Handle size changes.
  105435. var size = this._mainTexture.getSize();
  105436. this._setMainTextureSize();
  105437. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  105438. // Recreate RTT and post processes on size change.
  105439. this.onSizeChangedObservable.notifyObservers(this);
  105440. this._disposeTextureAndPostProcesses();
  105441. this._createMainTexture();
  105442. this._createTextureAndPostProcesses();
  105443. }
  105444. };
  105445. /**
  105446. * Determine if a given mesh will be used in the current effect.
  105447. * @param mesh mesh to test
  105448. * @returns true if the mesh will be used
  105449. */
  105450. EffectLayer.prototype.hasMesh = function (mesh) {
  105451. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  105452. return true;
  105453. }
  105454. return false;
  105455. };
  105456. /**
  105457. * Returns true if the layer contains information to display, otherwise false.
  105458. * @returns true if the glow layer should be rendered
  105459. */
  105460. EffectLayer.prototype.shouldRender = function () {
  105461. return this.isEnabled && this._shouldRender;
  105462. };
  105463. /**
  105464. * Returns true if the mesh should render, otherwise false.
  105465. * @param mesh The mesh to render
  105466. * @returns true if it should render otherwise false
  105467. */
  105468. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  105469. return true;
  105470. };
  105471. /**
  105472. * Returns true if the mesh should render, otherwise false.
  105473. * @param mesh The mesh to render
  105474. * @returns true if it should render otherwise false
  105475. */
  105476. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  105477. return true;
  105478. };
  105479. /**
  105480. * Renders the submesh passed in parameter to the generation map.
  105481. */
  105482. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  105483. var _this = this;
  105484. if (!this.shouldRender()) {
  105485. return;
  105486. }
  105487. var material = subMesh.getMaterial();
  105488. var mesh = subMesh.getRenderingMesh();
  105489. var scene = this._scene;
  105490. var engine = scene.getEngine();
  105491. if (!material) {
  105492. return;
  105493. }
  105494. // Do not block in blend mode.
  105495. if (material.needAlphaBlendingForMesh(mesh)) {
  105496. return;
  105497. }
  105498. // Culling
  105499. engine.setState(material.backFaceCulling);
  105500. // Managing instances
  105501. var batch = mesh._getInstancesRenderList(subMesh._id);
  105502. if (batch.mustReturn) {
  105503. return;
  105504. }
  105505. // Early Exit per mesh
  105506. if (!this._shouldRenderMesh(mesh)) {
  105507. return;
  105508. }
  105509. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  105510. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  105511. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  105512. engine.enableEffect(this._effectLayerMapGenerationEffect);
  105513. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  105514. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  105515. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  105516. // Alpha test
  105517. if (material && material.needAlphaTesting()) {
  105518. var alphaTexture = material.getAlphaTestTexture();
  105519. if (alphaTexture) {
  105520. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  105521. var textureMatrix = alphaTexture.getTextureMatrix();
  105522. if (textureMatrix) {
  105523. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  105524. }
  105525. }
  105526. }
  105527. // Glow emissive only
  105528. if (this._emissiveTextureAndColor.texture) {
  105529. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  105530. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  105531. }
  105532. // Bones
  105533. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  105534. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  105535. }
  105536. // Morph targets
  105537. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  105538. // Draw
  105539. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  105540. }
  105541. else {
  105542. // Need to reset refresh rate of the main map
  105543. this._mainTexture.resetRefreshCounter();
  105544. }
  105545. };
  105546. /**
  105547. * Rebuild the required buffers.
  105548. * @hidden Internal use only.
  105549. */
  105550. EffectLayer.prototype._rebuild = function () {
  105551. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105552. if (vb) {
  105553. vb._rebuild();
  105554. }
  105555. this._generateIndexBuffer();
  105556. };
  105557. /**
  105558. * Dispose only the render target textures and post process.
  105559. */
  105560. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  105561. this._mainTexture.dispose();
  105562. for (var i = 0; i < this._postProcesses.length; i++) {
  105563. if (this._postProcesses[i]) {
  105564. this._postProcesses[i].dispose();
  105565. }
  105566. }
  105567. this._postProcesses = [];
  105568. for (var i = 0; i < this._textures.length; i++) {
  105569. if (this._textures[i]) {
  105570. this._textures[i].dispose();
  105571. }
  105572. }
  105573. this._textures = [];
  105574. };
  105575. /**
  105576. * Dispose the highlight layer and free resources.
  105577. */
  105578. EffectLayer.prototype.dispose = function () {
  105579. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105580. if (vertexBuffer) {
  105581. vertexBuffer.dispose();
  105582. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  105583. }
  105584. if (this._indexBuffer) {
  105585. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  105586. this._indexBuffer = null;
  105587. }
  105588. // Clean textures and post processes
  105589. this._disposeTextureAndPostProcesses();
  105590. // Remove from scene
  105591. var index = this._scene.effectLayers.indexOf(this, 0);
  105592. if (index > -1) {
  105593. this._scene.effectLayers.splice(index, 1);
  105594. }
  105595. // Callback
  105596. this.onDisposeObservable.notifyObservers(this);
  105597. this.onDisposeObservable.clear();
  105598. this.onBeforeRenderMainTextureObservable.clear();
  105599. this.onBeforeComposeObservable.clear();
  105600. this.onAfterComposeObservable.clear();
  105601. this.onSizeChangedObservable.clear();
  105602. };
  105603. /**
  105604. * Gets the class name of the effect layer
  105605. * @returns the string with the class name of the effect layer
  105606. */
  105607. EffectLayer.prototype.getClassName = function () {
  105608. return "EffectLayer";
  105609. };
  105610. /**
  105611. * Creates an effect layer from parsed effect layer data
  105612. * @param parsedEffectLayer defines effect layer data
  105613. * @param scene defines the current scene
  105614. * @param rootUrl defines the root URL containing the effect layer information
  105615. * @returns a parsed effect Layer
  105616. */
  105617. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  105618. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  105619. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  105620. };
  105621. __decorate([
  105622. BABYLON.serialize()
  105623. ], EffectLayer.prototype, "name", void 0);
  105624. __decorate([
  105625. BABYLON.serializeAsColor4()
  105626. ], EffectLayer.prototype, "neutralColor", void 0);
  105627. __decorate([
  105628. BABYLON.serialize()
  105629. ], EffectLayer.prototype, "isEnabled", void 0);
  105630. __decorate([
  105631. BABYLON.serializeAsCameraReference()
  105632. ], EffectLayer.prototype, "camera", null);
  105633. __decorate([
  105634. BABYLON.serialize()
  105635. ], EffectLayer.prototype, "renderingGroupId", null);
  105636. return EffectLayer;
  105637. }());
  105638. BABYLON.EffectLayer = EffectLayer;
  105639. })(BABYLON || (BABYLON = {}));
  105640. //# sourceMappingURL=babylon.effectLayer.js.map
  105641. var BABYLON;
  105642. (function (BABYLON) {
  105643. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  105644. for (var index = 0; index < this.effectLayers.length; index++) {
  105645. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  105646. return this.effectLayers[index];
  105647. }
  105648. }
  105649. return null;
  105650. };
  105651. /**
  105652. * Special Glow Blur post process only blurring the alpha channel
  105653. * It enforces keeping the most luminous color in the color channel.
  105654. */
  105655. var GlowBlurPostProcess = /** @class */ (function (_super) {
  105656. __extends(GlowBlurPostProcess, _super);
  105657. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  105658. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  105659. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  105660. _this.direction = direction;
  105661. _this.kernel = kernel;
  105662. _this.onApplyObservable.add(function (effect) {
  105663. effect.setFloat2("screenSize", _this.width, _this.height);
  105664. effect.setVector2("direction", _this.direction);
  105665. effect.setFloat("blurWidth", _this.kernel);
  105666. });
  105667. return _this;
  105668. }
  105669. return GlowBlurPostProcess;
  105670. }(BABYLON.PostProcess));
  105671. /**
  105672. * The highlight layer Helps adding a glow effect around a mesh.
  105673. *
  105674. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  105675. * glowy meshes to your scene.
  105676. *
  105677. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  105678. */
  105679. var HighlightLayer = /** @class */ (function (_super) {
  105680. __extends(HighlightLayer, _super);
  105681. /**
  105682. * Instantiates a new highlight Layer and references it to the scene..
  105683. * @param name The name of the layer
  105684. * @param scene The scene to use the layer in
  105685. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  105686. */
  105687. function HighlightLayer(name, scene, options) {
  105688. var _this = _super.call(this, name, scene) || this;
  105689. _this.name = name;
  105690. /**
  105691. * Specifies whether or not the inner glow is ACTIVE in the layer.
  105692. */
  105693. _this.innerGlow = true;
  105694. /**
  105695. * Specifies whether or not the outer glow is ACTIVE in the layer.
  105696. */
  105697. _this.outerGlow = true;
  105698. /**
  105699. * An event triggered when the highlight layer is being blurred.
  105700. */
  105701. _this.onBeforeBlurObservable = new BABYLON.Observable();
  105702. /**
  105703. * An event triggered when the highlight layer has been blurred.
  105704. */
  105705. _this.onAfterBlurObservable = new BABYLON.Observable();
  105706. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  105707. _this._meshes = {};
  105708. _this._excludedMeshes = {};
  105709. _this.neutralColor = HighlightLayer.NeutralColor;
  105710. // Warn on stencil
  105711. if (!_this._engine.isStencilEnable) {
  105712. 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 }");
  105713. }
  105714. // Adapt options
  105715. _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);
  105716. // Initialize the layer
  105717. _this._init({
  105718. alphaBlendingMode: _this._options.alphaBlendingMode,
  105719. camera: _this._options.camera,
  105720. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  105721. mainTextureRatio: _this._options.mainTextureRatio,
  105722. renderingGroupId: _this._options.renderingGroupId
  105723. });
  105724. // Do not render as long as no meshes have been added
  105725. _this._shouldRender = false;
  105726. return _this;
  105727. }
  105728. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  105729. /**
  105730. * Gets the horizontal size of the blur.
  105731. */
  105732. get: function () {
  105733. return this._horizontalBlurPostprocess.kernel;
  105734. },
  105735. /**
  105736. * Specifies the horizontal size of the blur.
  105737. */
  105738. set: function (value) {
  105739. this._horizontalBlurPostprocess.kernel = value;
  105740. },
  105741. enumerable: true,
  105742. configurable: true
  105743. });
  105744. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  105745. /**
  105746. * Gets the vertical size of the blur.
  105747. */
  105748. get: function () {
  105749. return this._verticalBlurPostprocess.kernel;
  105750. },
  105751. /**
  105752. * Specifies the vertical size of the blur.
  105753. */
  105754. set: function (value) {
  105755. this._verticalBlurPostprocess.kernel = value;
  105756. },
  105757. enumerable: true,
  105758. configurable: true
  105759. });
  105760. /**
  105761. * Get the effect name of the layer.
  105762. * @return The effect name
  105763. */
  105764. HighlightLayer.prototype.getEffectName = function () {
  105765. return HighlightLayer.EffectName;
  105766. };
  105767. /**
  105768. * Create the merge effect. This is the shader use to blit the information back
  105769. * to the main canvas at the end of the scene rendering.
  105770. */
  105771. HighlightLayer.prototype._createMergeEffect = function () {
  105772. // Effect
  105773. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  105774. };
  105775. /**
  105776. * Creates the render target textures and post processes used in the highlight layer.
  105777. */
  105778. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  105779. var _this = this;
  105780. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  105781. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  105782. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  105783. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  105784. var textureType = 0;
  105785. if (this._engine.getCaps().textureHalfFloatRender) {
  105786. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  105787. }
  105788. else {
  105789. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105790. }
  105791. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  105792. width: blurTextureWidth,
  105793. height: blurTextureHeight
  105794. }, this._scene, false, true, textureType);
  105795. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105796. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105797. this._blurTexture.anisotropicFilteringLevel = 16;
  105798. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  105799. this._blurTexture.renderParticles = false;
  105800. this._blurTexture.ignoreCameraViewport = true;
  105801. this._textures = [this._blurTexture];
  105802. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  105803. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105804. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  105805. effect.setTexture("textureSampler", _this._mainTexture);
  105806. });
  105807. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105808. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  105809. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  105810. });
  105811. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105812. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  105813. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  105814. });
  105815. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  105816. }
  105817. else {
  105818. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  105819. width: blurTextureWidth,
  105820. height: blurTextureHeight
  105821. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105822. this._horizontalBlurPostprocess.width = blurTextureWidth;
  105823. this._horizontalBlurPostprocess.height = blurTextureHeight;
  105824. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  105825. effect.setTexture("textureSampler", _this._mainTexture);
  105826. });
  105827. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  105828. width: blurTextureWidth,
  105829. height: blurTextureHeight
  105830. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105831. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  105832. }
  105833. this._mainTexture.onAfterUnbindObservable.add(function () {
  105834. _this.onBeforeBlurObservable.notifyObservers(_this);
  105835. var internalTexture = _this._blurTexture.getInternalTexture();
  105836. if (internalTexture) {
  105837. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  105838. }
  105839. _this.onAfterBlurObservable.notifyObservers(_this);
  105840. });
  105841. // Prevent autoClear.
  105842. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  105843. };
  105844. /**
  105845. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  105846. */
  105847. HighlightLayer.prototype.needStencil = function () {
  105848. return true;
  105849. };
  105850. /**
  105851. * Checks for the readiness of the element composing the layer.
  105852. * @param subMesh the mesh to check for
  105853. * @param useInstances specify wether or not to use instances to render the mesh
  105854. * @param emissiveTexture the associated emissive texture used to generate the glow
  105855. * @return true if ready otherwise, false
  105856. */
  105857. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  105858. var material = subMesh.getMaterial();
  105859. var mesh = subMesh.getRenderingMesh();
  105860. if (!material || !mesh || !this._meshes) {
  105861. return false;
  105862. }
  105863. var emissiveTexture = null;
  105864. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  105865. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  105866. emissiveTexture = material.emissiveTexture;
  105867. }
  105868. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  105869. };
  105870. /**
  105871. * Implementation specific of rendering the generating effect on the main canvas.
  105872. * @param effect The effect used to render through
  105873. */
  105874. HighlightLayer.prototype._internalRender = function (effect) {
  105875. // Texture
  105876. effect.setTexture("textureSampler", this._blurTexture);
  105877. // Cache
  105878. var engine = this._engine;
  105879. var previousStencilBuffer = engine.getStencilBuffer();
  105880. var previousStencilFunction = engine.getStencilFunction();
  105881. var previousStencilMask = engine.getStencilMask();
  105882. var previousStencilOperationPass = engine.getStencilOperationPass();
  105883. var previousStencilOperationFail = engine.getStencilOperationFail();
  105884. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  105885. var previousStencilReference = engine.getStencilFunctionReference();
  105886. // Stencil operations
  105887. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  105888. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  105889. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  105890. // Draw order
  105891. engine.setStencilMask(0x00);
  105892. engine.setStencilBuffer(true);
  105893. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  105894. // 2 passes inner outer
  105895. if (this.outerGlow) {
  105896. effect.setFloat("offset", 0);
  105897. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  105898. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105899. }
  105900. if (this.innerGlow) {
  105901. effect.setFloat("offset", 1);
  105902. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  105903. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105904. }
  105905. // Restore Cache
  105906. engine.setStencilFunction(previousStencilFunction);
  105907. engine.setStencilMask(previousStencilMask);
  105908. engine.setStencilBuffer(previousStencilBuffer);
  105909. engine.setStencilOperationPass(previousStencilOperationPass);
  105910. engine.setStencilOperationFail(previousStencilOperationFail);
  105911. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  105912. engine.setStencilFunctionReference(previousStencilReference);
  105913. };
  105914. /**
  105915. * Returns true if the layer contains information to display, otherwise false.
  105916. */
  105917. HighlightLayer.prototype.shouldRender = function () {
  105918. if (_super.prototype.shouldRender.call(this)) {
  105919. return this._meshes ? true : false;
  105920. }
  105921. return false;
  105922. };
  105923. /**
  105924. * Returns true if the mesh should render, otherwise false.
  105925. * @param mesh The mesh to render
  105926. * @returns true if it should render otherwise false
  105927. */
  105928. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  105929. // Excluded Mesh
  105930. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  105931. return false;
  105932. }
  105933. ;
  105934. if (!_super.prototype.hasMesh.call(this, mesh)) {
  105935. return false;
  105936. }
  105937. return true;
  105938. };
  105939. /**
  105940. * Sets the required values for both the emissive texture and and the main color.
  105941. */
  105942. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  105943. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  105944. if (highlightLayerMesh) {
  105945. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  105946. }
  105947. else {
  105948. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  105949. }
  105950. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  105951. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  105952. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  105953. }
  105954. else {
  105955. this._emissiveTextureAndColor.texture = null;
  105956. }
  105957. };
  105958. /**
  105959. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  105960. * @param mesh The mesh to exclude from the highlight layer
  105961. */
  105962. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  105963. if (!this._excludedMeshes) {
  105964. return;
  105965. }
  105966. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  105967. if (!meshExcluded) {
  105968. this._excludedMeshes[mesh.uniqueId] = {
  105969. mesh: mesh,
  105970. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  105971. mesh.getEngine().setStencilBuffer(false);
  105972. }),
  105973. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  105974. mesh.getEngine().setStencilBuffer(true);
  105975. }),
  105976. };
  105977. }
  105978. };
  105979. /**
  105980. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  105981. * @param mesh The mesh to highlight
  105982. */
  105983. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  105984. if (!this._excludedMeshes) {
  105985. return;
  105986. }
  105987. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  105988. if (meshExcluded) {
  105989. if (meshExcluded.beforeRender) {
  105990. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  105991. }
  105992. if (meshExcluded.afterRender) {
  105993. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  105994. }
  105995. }
  105996. this._excludedMeshes[mesh.uniqueId] = null;
  105997. };
  105998. /**
  105999. * Determine if a given mesh will be highlighted by the current HighlightLayer
  106000. * @param mesh mesh to test
  106001. * @returns true if the mesh will be highlighted by the current HighlightLayer
  106002. */
  106003. HighlightLayer.prototype.hasMesh = function (mesh) {
  106004. if (!this._meshes) {
  106005. return false;
  106006. }
  106007. if (!_super.prototype.hasMesh.call(this, mesh)) {
  106008. return false;
  106009. }
  106010. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  106011. };
  106012. /**
  106013. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  106014. * @param mesh The mesh to highlight
  106015. * @param color The color of the highlight
  106016. * @param glowEmissiveOnly Extract the glow from the emissive texture
  106017. */
  106018. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  106019. var _this = this;
  106020. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  106021. if (!this._meshes) {
  106022. return;
  106023. }
  106024. var meshHighlight = this._meshes[mesh.uniqueId];
  106025. if (meshHighlight) {
  106026. meshHighlight.color = color;
  106027. }
  106028. else {
  106029. this._meshes[mesh.uniqueId] = {
  106030. mesh: mesh,
  106031. color: color,
  106032. // Lambda required for capture due to Observable this context
  106033. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  106034. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  106035. _this._defaultStencilReference(mesh);
  106036. }
  106037. else {
  106038. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  106039. }
  106040. }),
  106041. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  106042. glowEmissiveOnly: glowEmissiveOnly
  106043. };
  106044. mesh.onDisposeObservable.add(function () {
  106045. _this._disposeMesh(mesh);
  106046. });
  106047. }
  106048. this._shouldRender = true;
  106049. };
  106050. /**
  106051. * Remove a mesh from the highlight layer in order to make it stop glowing.
  106052. * @param mesh The mesh to highlight
  106053. */
  106054. HighlightLayer.prototype.removeMesh = function (mesh) {
  106055. if (!this._meshes) {
  106056. return;
  106057. }
  106058. var meshHighlight = this._meshes[mesh.uniqueId];
  106059. if (meshHighlight) {
  106060. if (meshHighlight.observerHighlight) {
  106061. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  106062. }
  106063. if (meshHighlight.observerDefault) {
  106064. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  106065. }
  106066. delete this._meshes[mesh.uniqueId];
  106067. }
  106068. this._shouldRender = false;
  106069. for (var meshHighlightToCheck in this._meshes) {
  106070. if (this._meshes[meshHighlightToCheck]) {
  106071. this._shouldRender = true;
  106072. break;
  106073. }
  106074. }
  106075. };
  106076. /**
  106077. * Force the stencil to the normal expected value for none glowing parts
  106078. */
  106079. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  106080. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  106081. };
  106082. /**
  106083. * Free any resources and references associated to a mesh.
  106084. * Internal use
  106085. * @param mesh The mesh to free.
  106086. * @hidden
  106087. */
  106088. HighlightLayer.prototype._disposeMesh = function (mesh) {
  106089. this.removeMesh(mesh);
  106090. this.removeExcludedMesh(mesh);
  106091. };
  106092. /**
  106093. * Dispose the highlight layer and free resources.
  106094. */
  106095. HighlightLayer.prototype.dispose = function () {
  106096. if (this._meshes) {
  106097. // Clean mesh references
  106098. for (var id in this._meshes) {
  106099. var meshHighlight = this._meshes[id];
  106100. if (meshHighlight && meshHighlight.mesh) {
  106101. if (meshHighlight.observerHighlight) {
  106102. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  106103. }
  106104. if (meshHighlight.observerDefault) {
  106105. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  106106. }
  106107. }
  106108. }
  106109. this._meshes = null;
  106110. }
  106111. if (this._excludedMeshes) {
  106112. for (var id in this._excludedMeshes) {
  106113. var meshHighlight = this._excludedMeshes[id];
  106114. if (meshHighlight) {
  106115. if (meshHighlight.beforeRender) {
  106116. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  106117. }
  106118. if (meshHighlight.afterRender) {
  106119. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  106120. }
  106121. }
  106122. }
  106123. this._excludedMeshes = null;
  106124. }
  106125. _super.prototype.dispose.call(this);
  106126. };
  106127. /**
  106128. * Gets the class name of the effect layer
  106129. * @returns the string with the class name of the effect layer
  106130. */
  106131. HighlightLayer.prototype.getClassName = function () {
  106132. return "HighlightLayer";
  106133. };
  106134. /**
  106135. * Serializes this Highlight layer
  106136. * @returns a serialized Highlight layer object
  106137. */
  106138. HighlightLayer.prototype.serialize = function () {
  106139. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106140. serializationObject.customType = "BABYLON.HighlightLayer";
  106141. // Highlighted meshes
  106142. serializationObject.meshes = [];
  106143. if (this._meshes) {
  106144. for (var m in this._meshes) {
  106145. var mesh = this._meshes[m];
  106146. if (mesh) {
  106147. serializationObject.meshes.push({
  106148. glowEmissiveOnly: mesh.glowEmissiveOnly,
  106149. color: mesh.color.asArray(),
  106150. meshId: mesh.mesh.id
  106151. });
  106152. }
  106153. }
  106154. }
  106155. // Excluded meshes
  106156. serializationObject.excludedMeshes = [];
  106157. if (this._excludedMeshes) {
  106158. for (var e in this._excludedMeshes) {
  106159. var excludedMesh = this._excludedMeshes[e];
  106160. if (excludedMesh) {
  106161. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  106162. }
  106163. }
  106164. }
  106165. return serializationObject;
  106166. };
  106167. /**
  106168. * Creates a Highlight layer from parsed Highlight layer data
  106169. * @param parsedHightlightLayer defines the Highlight layer data
  106170. * @param scene defines the current scene
  106171. * @param rootUrl defines the root URL containing the Highlight layer information
  106172. * @returns a parsed Highlight layer
  106173. */
  106174. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  106175. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  106176. var index;
  106177. // Excluded meshes
  106178. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  106179. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  106180. if (mesh) {
  106181. hl.addExcludedMesh(mesh);
  106182. }
  106183. }
  106184. // Included meshes
  106185. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  106186. var highlightedMesh = parsedHightlightLayer.meshes[index];
  106187. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  106188. if (mesh) {
  106189. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  106190. }
  106191. }
  106192. return hl;
  106193. };
  106194. /**
  106195. * Effect Name of the highlight layer.
  106196. */
  106197. HighlightLayer.EffectName = "HighlightLayer";
  106198. /**
  106199. * The neutral color used during the preparation of the glow effect.
  106200. * This is black by default as the blend operation is a blend operation.
  106201. */
  106202. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  106203. /**
  106204. * Stencil value used for glowing meshes.
  106205. */
  106206. HighlightLayer.GlowingMeshStencilReference = 0x02;
  106207. /**
  106208. * Stencil value used for the other meshes in the scene.
  106209. */
  106210. HighlightLayer.NormalMeshStencilReference = 0x01;
  106211. __decorate([
  106212. BABYLON.serialize()
  106213. ], HighlightLayer.prototype, "innerGlow", void 0);
  106214. __decorate([
  106215. BABYLON.serialize()
  106216. ], HighlightLayer.prototype, "outerGlow", void 0);
  106217. __decorate([
  106218. BABYLON.serialize()
  106219. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  106220. __decorate([
  106221. BABYLON.serialize()
  106222. ], HighlightLayer.prototype, "blurVerticalSize", null);
  106223. __decorate([
  106224. BABYLON.serialize("options")
  106225. ], HighlightLayer.prototype, "_options", void 0);
  106226. return HighlightLayer;
  106227. }(BABYLON.EffectLayer));
  106228. BABYLON.HighlightLayer = HighlightLayer;
  106229. })(BABYLON || (BABYLON = {}));
  106230. //# sourceMappingURL=babylon.highlightLayer.js.map
  106231. var BABYLON;
  106232. (function (BABYLON) {
  106233. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  106234. for (var index = 0; index < this.effectLayers.length; index++) {
  106235. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  106236. return this.effectLayers[index];
  106237. }
  106238. }
  106239. return null;
  106240. };
  106241. /**
  106242. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  106243. *
  106244. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  106245. * glowy meshes to your scene.
  106246. *
  106247. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  106248. */
  106249. var GlowLayer = /** @class */ (function (_super) {
  106250. __extends(GlowLayer, _super);
  106251. /**
  106252. * Instantiates a new glow Layer and references it to the scene.
  106253. * @param name The name of the layer
  106254. * @param scene The scene to use the layer in
  106255. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  106256. */
  106257. function GlowLayer(name, scene, options) {
  106258. var _this = _super.call(this, name, scene) || this;
  106259. _this._intensity = 1.0;
  106260. _this._includedOnlyMeshes = [];
  106261. _this._excludedMeshes = [];
  106262. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  106263. // Adapt options
  106264. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  106265. // Initialize the layer
  106266. _this._init({
  106267. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  106268. camera: _this._options.camera,
  106269. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  106270. mainTextureRatio: _this._options.mainTextureRatio,
  106271. renderingGroupId: _this._options.renderingGroupId
  106272. });
  106273. return _this;
  106274. }
  106275. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  106276. /**
  106277. * Gets the kernel size of the blur.
  106278. */
  106279. get: function () {
  106280. return this._horizontalBlurPostprocess1.kernel;
  106281. },
  106282. /**
  106283. * Sets the kernel size of the blur.
  106284. */
  106285. set: function (value) {
  106286. this._horizontalBlurPostprocess1.kernel = value;
  106287. this._verticalBlurPostprocess1.kernel = value;
  106288. this._horizontalBlurPostprocess2.kernel = value;
  106289. this._verticalBlurPostprocess2.kernel = value;
  106290. },
  106291. enumerable: true,
  106292. configurable: true
  106293. });
  106294. Object.defineProperty(GlowLayer.prototype, "intensity", {
  106295. /**
  106296. * Gets the glow intensity.
  106297. */
  106298. get: function () {
  106299. return this._intensity;
  106300. },
  106301. /**
  106302. * Sets the glow intensity.
  106303. */
  106304. set: function (value) {
  106305. this._intensity = value;
  106306. },
  106307. enumerable: true,
  106308. configurable: true
  106309. });
  106310. /**
  106311. * Get the effect name of the layer.
  106312. * @return The effect name
  106313. */
  106314. GlowLayer.prototype.getEffectName = function () {
  106315. return GlowLayer.EffectName;
  106316. };
  106317. /**
  106318. * Create the merge effect. This is the shader use to blit the information back
  106319. * to the main canvas at the end of the scene rendering.
  106320. */
  106321. GlowLayer.prototype._createMergeEffect = function () {
  106322. // Effect
  106323. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  106324. };
  106325. /**
  106326. * Creates the render target textures and post processes used in the glow layer.
  106327. */
  106328. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  106329. var _this = this;
  106330. var blurTextureWidth = this._mainTextureDesiredSize.width;
  106331. var blurTextureHeight = this._mainTextureDesiredSize.height;
  106332. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  106333. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  106334. var textureType = 0;
  106335. if (this._engine.getCaps().textureHalfFloatRender) {
  106336. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  106337. }
  106338. else {
  106339. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106340. }
  106341. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  106342. width: blurTextureWidth,
  106343. height: blurTextureHeight
  106344. }, this._scene, false, true, textureType);
  106345. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106346. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106347. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106348. this._blurTexture1.renderParticles = false;
  106349. this._blurTexture1.ignoreCameraViewport = true;
  106350. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  106351. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  106352. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  106353. width: blurTextureWidth2,
  106354. height: blurTextureHeight2
  106355. }, this._scene, false, true, textureType);
  106356. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106357. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106358. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106359. this._blurTexture2.renderParticles = false;
  106360. this._blurTexture2.ignoreCameraViewport = true;
  106361. this._textures = [this._blurTexture1, this._blurTexture2];
  106362. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  106363. width: blurTextureWidth,
  106364. height: blurTextureHeight
  106365. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106366. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  106367. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  106368. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  106369. effect.setTexture("textureSampler", _this._mainTexture);
  106370. });
  106371. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  106372. width: blurTextureWidth,
  106373. height: blurTextureHeight
  106374. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106375. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  106376. width: blurTextureWidth2,
  106377. height: blurTextureHeight2
  106378. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106379. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  106380. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  106381. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  106382. effect.setTexture("textureSampler", _this._blurTexture1);
  106383. });
  106384. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  106385. width: blurTextureWidth2,
  106386. height: blurTextureHeight2
  106387. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106388. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  106389. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  106390. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  106391. this._mainTexture.samples = this._options.mainTextureSamples;
  106392. this._mainTexture.onAfterUnbindObservable.add(function () {
  106393. var internalTexture = _this._blurTexture1.getInternalTexture();
  106394. if (internalTexture) {
  106395. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  106396. internalTexture = _this._blurTexture2.getInternalTexture();
  106397. if (internalTexture) {
  106398. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  106399. }
  106400. }
  106401. });
  106402. // Prevent autoClear.
  106403. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  106404. };
  106405. /**
  106406. * Checks for the readiness of the element composing the layer.
  106407. * @param subMesh the mesh to check for
  106408. * @param useInstances specify wether or not to use instances to render the mesh
  106409. * @param emissiveTexture the associated emissive texture used to generate the glow
  106410. * @return true if ready otherwise, false
  106411. */
  106412. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  106413. var material = subMesh.getMaterial();
  106414. var mesh = subMesh.getRenderingMesh();
  106415. if (!material || !mesh) {
  106416. return false;
  106417. }
  106418. var emissiveTexture = material.emissiveTexture;
  106419. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  106420. };
  106421. /**
  106422. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  106423. */
  106424. GlowLayer.prototype.needStencil = function () {
  106425. return false;
  106426. };
  106427. /**
  106428. * Implementation specific of rendering the generating effect on the main canvas.
  106429. * @param effect The effect used to render through
  106430. */
  106431. GlowLayer.prototype._internalRender = function (effect) {
  106432. // Texture
  106433. effect.setTexture("textureSampler", this._blurTexture1);
  106434. effect.setTexture("textureSampler2", this._blurTexture2);
  106435. effect.setFloat("offset", this._intensity);
  106436. // Cache
  106437. var engine = this._engine;
  106438. var previousStencilBuffer = engine.getStencilBuffer();
  106439. // Draw order
  106440. engine.setStencilBuffer(false);
  106441. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  106442. // Draw order
  106443. engine.setStencilBuffer(previousStencilBuffer);
  106444. };
  106445. /**
  106446. * Sets the required values for both the emissive texture and and the main color.
  106447. */
  106448. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  106449. var textureLevel = 1.0;
  106450. if (this.customEmissiveTextureSelector) {
  106451. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  106452. }
  106453. else {
  106454. if (material) {
  106455. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  106456. if (this._emissiveTextureAndColor.texture) {
  106457. textureLevel = this._emissiveTextureAndColor.texture.level;
  106458. }
  106459. }
  106460. else {
  106461. this._emissiveTextureAndColor.texture = null;
  106462. }
  106463. }
  106464. if (this.customEmissiveColorSelector) {
  106465. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  106466. }
  106467. else {
  106468. if (material.emissiveColor) {
  106469. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  106470. }
  106471. else {
  106472. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  106473. }
  106474. }
  106475. };
  106476. /**
  106477. * Returns true if the mesh should render, otherwise false.
  106478. * @param mesh The mesh to render
  106479. * @returns true if it should render otherwise false
  106480. */
  106481. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  106482. return this.hasMesh(mesh);
  106483. };
  106484. /**
  106485. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  106486. * @param mesh The mesh to exclude from the glow layer
  106487. */
  106488. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  106489. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  106490. this._excludedMeshes.push(mesh.uniqueId);
  106491. }
  106492. };
  106493. /**
  106494. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  106495. * @param mesh The mesh to remove
  106496. */
  106497. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  106498. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  106499. if (index !== -1) {
  106500. this._excludedMeshes.splice(index, 1);
  106501. }
  106502. };
  106503. /**
  106504. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  106505. * @param mesh The mesh to include in the glow layer
  106506. */
  106507. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  106508. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  106509. this._includedOnlyMeshes.push(mesh.uniqueId);
  106510. }
  106511. };
  106512. /**
  106513. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  106514. * @param mesh The mesh to remove
  106515. */
  106516. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  106517. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  106518. if (index !== -1) {
  106519. this._includedOnlyMeshes.splice(index, 1);
  106520. }
  106521. };
  106522. /**
  106523. * Determine if a given mesh will be used in the glow layer
  106524. * @param mesh The mesh to test
  106525. * @returns true if the mesh will be highlighted by the current glow layer
  106526. */
  106527. GlowLayer.prototype.hasMesh = function (mesh) {
  106528. if (!_super.prototype.hasMesh.call(this, mesh)) {
  106529. return false;
  106530. }
  106531. // Included Mesh
  106532. if (this._includedOnlyMeshes.length) {
  106533. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  106534. }
  106535. ;
  106536. // Excluded Mesh
  106537. if (this._excludedMeshes.length) {
  106538. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  106539. }
  106540. ;
  106541. return true;
  106542. };
  106543. /**
  106544. * Free any resources and references associated to a mesh.
  106545. * Internal use
  106546. * @param mesh The mesh to free.
  106547. * @hidden
  106548. */
  106549. GlowLayer.prototype._disposeMesh = function (mesh) {
  106550. this.removeIncludedOnlyMesh(mesh);
  106551. this.removeExcludedMesh(mesh);
  106552. };
  106553. /**
  106554. * Gets the class name of the effect layer
  106555. * @returns the string with the class name of the effect layer
  106556. */
  106557. GlowLayer.prototype.getClassName = function () {
  106558. return "GlowLayer";
  106559. };
  106560. /**
  106561. * Serializes this glow layer
  106562. * @returns a serialized glow layer object
  106563. */
  106564. GlowLayer.prototype.serialize = function () {
  106565. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106566. serializationObject.customType = "BABYLON.GlowLayer";
  106567. var index;
  106568. // Included meshes
  106569. serializationObject.includedMeshes = [];
  106570. if (this._includedOnlyMeshes.length) {
  106571. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  106572. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  106573. if (mesh) {
  106574. serializationObject.includedMeshes.push(mesh.id);
  106575. }
  106576. }
  106577. }
  106578. // Excluded meshes
  106579. serializationObject.excludedMeshes = [];
  106580. if (this._excludedMeshes.length) {
  106581. for (index = 0; index < this._excludedMeshes.length; index++) {
  106582. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  106583. if (mesh) {
  106584. serializationObject.excludedMeshes.push(mesh.id);
  106585. }
  106586. }
  106587. }
  106588. return serializationObject;
  106589. };
  106590. /**
  106591. * Creates a Glow Layer from parsed glow layer data
  106592. * @param parsedGlowLayer defines glow layer data
  106593. * @param scene defines the current scene
  106594. * @param rootUrl defines the root URL containing the glow layer information
  106595. * @returns a parsed Glow Layer
  106596. */
  106597. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  106598. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  106599. var index;
  106600. // Excluded meshes
  106601. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  106602. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  106603. if (mesh) {
  106604. gl.addExcludedMesh(mesh);
  106605. }
  106606. }
  106607. // Included meshes
  106608. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  106609. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  106610. if (mesh) {
  106611. gl.addIncludedOnlyMesh(mesh);
  106612. }
  106613. }
  106614. return gl;
  106615. };
  106616. /**
  106617. * Effect Name of the layer.
  106618. */
  106619. GlowLayer.EffectName = "GlowLayer";
  106620. /**
  106621. * The default blur kernel size used for the glow.
  106622. */
  106623. GlowLayer.DefaultBlurKernelSize = 32;
  106624. /**
  106625. * The default texture size ratio used for the glow.
  106626. */
  106627. GlowLayer.DefaultTextureRatio = 0.5;
  106628. __decorate([
  106629. BABYLON.serialize()
  106630. ], GlowLayer.prototype, "blurKernelSize", null);
  106631. __decorate([
  106632. BABYLON.serialize()
  106633. ], GlowLayer.prototype, "intensity", null);
  106634. __decorate([
  106635. BABYLON.serialize("options")
  106636. ], GlowLayer.prototype, "_options", void 0);
  106637. return GlowLayer;
  106638. }(BABYLON.EffectLayer));
  106639. BABYLON.GlowLayer = GlowLayer;
  106640. })(BABYLON || (BABYLON = {}));
  106641. //# sourceMappingURL=babylon.glowLayer.js.map
  106642. var BABYLON;
  106643. (function (BABYLON) {
  106644. /**
  106645. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  106646. */
  106647. var AssetTaskState;
  106648. (function (AssetTaskState) {
  106649. /**
  106650. * Initialization
  106651. */
  106652. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  106653. /**
  106654. * Running
  106655. */
  106656. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  106657. /**
  106658. * Done
  106659. */
  106660. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  106661. /**
  106662. * Error
  106663. */
  106664. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  106665. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  106666. /**
  106667. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  106668. */
  106669. var AbstractAssetTask = /** @class */ (function () {
  106670. /**
  106671. * Creates a new {BABYLON.AssetsManager}
  106672. * @param name defines the name of the task
  106673. */
  106674. function AbstractAssetTask(
  106675. /**
  106676. * Task name
  106677. */ name) {
  106678. this.name = name;
  106679. this._isCompleted = false;
  106680. this._taskState = AssetTaskState.INIT;
  106681. }
  106682. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  106683. /**
  106684. * Get if the task is completed
  106685. */
  106686. get: function () {
  106687. return this._isCompleted;
  106688. },
  106689. enumerable: true,
  106690. configurable: true
  106691. });
  106692. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  106693. /**
  106694. * Gets the current state of the task
  106695. */
  106696. get: function () {
  106697. return this._taskState;
  106698. },
  106699. enumerable: true,
  106700. configurable: true
  106701. });
  106702. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  106703. /**
  106704. * Gets the current error object (if task is in error)
  106705. */
  106706. get: function () {
  106707. return this._errorObject;
  106708. },
  106709. enumerable: true,
  106710. configurable: true
  106711. });
  106712. /**
  106713. * Internal only
  106714. * @hidden
  106715. */
  106716. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  106717. if (this._errorObject) {
  106718. return;
  106719. }
  106720. this._errorObject = {
  106721. message: message,
  106722. exception: exception
  106723. };
  106724. };
  106725. /**
  106726. * Execute the current task
  106727. * @param scene defines the scene where you want your assets to be loaded
  106728. * @param onSuccess is a callback called when the task is successfully executed
  106729. * @param onError is a callback called if an error occurs
  106730. */
  106731. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  106732. var _this = this;
  106733. this._taskState = AssetTaskState.RUNNING;
  106734. this.runTask(scene, function () {
  106735. _this.onDoneCallback(onSuccess, onError);
  106736. }, function (msg, exception) {
  106737. _this.onErrorCallback(onError, msg, exception);
  106738. });
  106739. };
  106740. /**
  106741. * Execute the current task
  106742. * @param scene defines the scene where you want your assets to be loaded
  106743. * @param onSuccess is a callback called when the task is successfully executed
  106744. * @param onError is a callback called if an error occurs
  106745. */
  106746. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106747. throw new Error("runTask is not implemented");
  106748. };
  106749. /**
  106750. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  106751. * This can be used with failed tasks that have the reason for failure fixed.
  106752. */
  106753. AbstractAssetTask.prototype.reset = function () {
  106754. this._taskState = AssetTaskState.INIT;
  106755. };
  106756. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  106757. this._taskState = AssetTaskState.ERROR;
  106758. this._errorObject = {
  106759. message: message,
  106760. exception: exception
  106761. };
  106762. if (this.onError) {
  106763. this.onError(this, message, exception);
  106764. }
  106765. onError();
  106766. };
  106767. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  106768. try {
  106769. this._taskState = AssetTaskState.DONE;
  106770. this._isCompleted = true;
  106771. if (this.onSuccess) {
  106772. this.onSuccess(this);
  106773. }
  106774. onSuccess();
  106775. }
  106776. catch (e) {
  106777. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  106778. }
  106779. };
  106780. return AbstractAssetTask;
  106781. }());
  106782. BABYLON.AbstractAssetTask = AbstractAssetTask;
  106783. /**
  106784. * Class used to share progress information about assets loading
  106785. */
  106786. var AssetsProgressEvent = /** @class */ (function () {
  106787. /**
  106788. * Creates a {BABYLON.AssetsProgressEvent}
  106789. * @param remainingCount defines the number of remaining tasks to process
  106790. * @param totalCount defines the total number of tasks
  106791. * @param task defines the task that was just processed
  106792. */
  106793. function AssetsProgressEvent(remainingCount, totalCount, task) {
  106794. this.remainingCount = remainingCount;
  106795. this.totalCount = totalCount;
  106796. this.task = task;
  106797. }
  106798. return AssetsProgressEvent;
  106799. }());
  106800. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  106801. /**
  106802. * Define a task used by {BABYLON.AssetsManager} to load meshes
  106803. */
  106804. var MeshAssetTask = /** @class */ (function (_super) {
  106805. __extends(MeshAssetTask, _super);
  106806. /**
  106807. * Creates a new {BABYLON.MeshAssetTask}
  106808. * @param name defines the name of the task
  106809. * @param meshesNames defines the list of mesh's names you want to load
  106810. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  106811. * @param sceneFilename defines the filename of the scene to load from
  106812. */
  106813. function MeshAssetTask(
  106814. /**
  106815. * Defines the name of the task
  106816. */
  106817. name,
  106818. /**
  106819. * Defines the list of mesh's names you want to load
  106820. */
  106821. meshesNames,
  106822. /**
  106823. * Defines the root url to use as a base to load your meshes and associated resources
  106824. */
  106825. rootUrl,
  106826. /**
  106827. * Defines the filename of the scene to load from
  106828. */
  106829. sceneFilename) {
  106830. var _this = _super.call(this, name) || this;
  106831. _this.name = name;
  106832. _this.meshesNames = meshesNames;
  106833. _this.rootUrl = rootUrl;
  106834. _this.sceneFilename = sceneFilename;
  106835. return _this;
  106836. }
  106837. /**
  106838. * Execute the current task
  106839. * @param scene defines the scene where you want your assets to be loaded
  106840. * @param onSuccess is a callback called when the task is successfully executed
  106841. * @param onError is a callback called if an error occurs
  106842. */
  106843. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106844. var _this = this;
  106845. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  106846. _this.loadedMeshes = meshes;
  106847. _this.loadedParticleSystems = particleSystems;
  106848. _this.loadedSkeletons = skeletons;
  106849. onSuccess();
  106850. }, null, function (scene, message, exception) {
  106851. onError(message, exception);
  106852. });
  106853. };
  106854. return MeshAssetTask;
  106855. }(AbstractAssetTask));
  106856. BABYLON.MeshAssetTask = MeshAssetTask;
  106857. /**
  106858. * Define a task used by {BABYLON.AssetsManager} to load text content
  106859. */
  106860. var TextFileAssetTask = /** @class */ (function (_super) {
  106861. __extends(TextFileAssetTask, _super);
  106862. /**
  106863. * Creates a new TextFileAssetTask object
  106864. * @param name defines the name of the task
  106865. * @param url defines the location of the file to load
  106866. */
  106867. function TextFileAssetTask(
  106868. /**
  106869. * Defines the name of the task
  106870. */
  106871. name,
  106872. /**
  106873. * Defines the location of the file to load
  106874. */
  106875. url) {
  106876. var _this = _super.call(this, name) || this;
  106877. _this.name = name;
  106878. _this.url = url;
  106879. return _this;
  106880. }
  106881. /**
  106882. * Execute the current task
  106883. * @param scene defines the scene where you want your assets to be loaded
  106884. * @param onSuccess is a callback called when the task is successfully executed
  106885. * @param onError is a callback called if an error occurs
  106886. */
  106887. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106888. var _this = this;
  106889. scene._loadFile(this.url, function (data) {
  106890. _this.text = data;
  106891. onSuccess();
  106892. }, undefined, false, false, function (request, exception) {
  106893. if (request) {
  106894. onError(request.status + " " + request.statusText, exception);
  106895. }
  106896. });
  106897. };
  106898. return TextFileAssetTask;
  106899. }(AbstractAssetTask));
  106900. BABYLON.TextFileAssetTask = TextFileAssetTask;
  106901. /**
  106902. * Define a task used by {BABYLON.AssetsManager} to load binary data
  106903. */
  106904. var BinaryFileAssetTask = /** @class */ (function (_super) {
  106905. __extends(BinaryFileAssetTask, _super);
  106906. /**
  106907. * Creates a new BinaryFileAssetTask object
  106908. * @param name defines the name of the new task
  106909. * @param url defines the location of the file to load
  106910. */
  106911. function BinaryFileAssetTask(
  106912. /**
  106913. * Defines the name of the task
  106914. */
  106915. name,
  106916. /**
  106917. * Defines the location of the file to load
  106918. */
  106919. url) {
  106920. var _this = _super.call(this, name) || this;
  106921. _this.name = name;
  106922. _this.url = url;
  106923. return _this;
  106924. }
  106925. /**
  106926. * Execute the current task
  106927. * @param scene defines the scene where you want your assets to be loaded
  106928. * @param onSuccess is a callback called when the task is successfully executed
  106929. * @param onError is a callback called if an error occurs
  106930. */
  106931. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106932. var _this = this;
  106933. scene._loadFile(this.url, function (data) {
  106934. _this.data = data;
  106935. onSuccess();
  106936. }, undefined, true, true, function (request, exception) {
  106937. if (request) {
  106938. onError(request.status + " " + request.statusText, exception);
  106939. }
  106940. });
  106941. };
  106942. return BinaryFileAssetTask;
  106943. }(AbstractAssetTask));
  106944. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  106945. /**
  106946. * Define a task used by {BABYLON.AssetsManager} to load images
  106947. */
  106948. var ImageAssetTask = /** @class */ (function (_super) {
  106949. __extends(ImageAssetTask, _super);
  106950. /**
  106951. * Creates a new ImageAssetTask
  106952. * @param name defines the name of the task
  106953. * @param url defines the location of the image to load
  106954. */
  106955. function ImageAssetTask(
  106956. /**
  106957. * Defines the name of the task
  106958. */
  106959. name,
  106960. /**
  106961. * Defines the location of the image to load
  106962. */
  106963. url) {
  106964. var _this = _super.call(this, name) || this;
  106965. _this.name = name;
  106966. _this.url = url;
  106967. return _this;
  106968. }
  106969. /**
  106970. * Execute the current task
  106971. * @param scene defines the scene where you want your assets to be loaded
  106972. * @param onSuccess is a callback called when the task is successfully executed
  106973. * @param onError is a callback called if an error occurs
  106974. */
  106975. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106976. var _this = this;
  106977. var img = new Image();
  106978. BABYLON.Tools.SetCorsBehavior(this.url, img);
  106979. img.onload = function () {
  106980. _this.image = img;
  106981. onSuccess();
  106982. };
  106983. img.onerror = function (err) {
  106984. onError("Error loading image", err);
  106985. };
  106986. img.src = this.url;
  106987. };
  106988. return ImageAssetTask;
  106989. }(AbstractAssetTask));
  106990. BABYLON.ImageAssetTask = ImageAssetTask;
  106991. /**
  106992. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  106993. */
  106994. var TextureAssetTask = /** @class */ (function (_super) {
  106995. __extends(TextureAssetTask, _super);
  106996. /**
  106997. * Creates a new TextureAssetTask object
  106998. * @param name defines the name of the task
  106999. * @param url defines the location of the file to load
  107000. * @param noMipmap defines if mipmap should not be generated (default is false)
  107001. * @param invertY defines if texture must be inverted on Y axis (default is false)
  107002. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  107003. */
  107004. function TextureAssetTask(
  107005. /**
  107006. * Defines the name of the task
  107007. */
  107008. name,
  107009. /**
  107010. * Defines the location of the file to load
  107011. */
  107012. url,
  107013. /**
  107014. * Defines if mipmap should not be generated (default is false)
  107015. */
  107016. noMipmap,
  107017. /**
  107018. * Defines if texture must be inverted on Y axis (default is false)
  107019. */
  107020. invertY,
  107021. /**
  107022. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  107023. */
  107024. samplingMode) {
  107025. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  107026. var _this = _super.call(this, name) || this;
  107027. _this.name = name;
  107028. _this.url = url;
  107029. _this.noMipmap = noMipmap;
  107030. _this.invertY = invertY;
  107031. _this.samplingMode = samplingMode;
  107032. return _this;
  107033. }
  107034. /**
  107035. * Execute the current task
  107036. * @param scene defines the scene where you want your assets to be loaded
  107037. * @param onSuccess is a callback called when the task is successfully executed
  107038. * @param onError is a callback called if an error occurs
  107039. */
  107040. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107041. var onload = function () {
  107042. onSuccess();
  107043. };
  107044. var onerror = function (message, exception) {
  107045. onError(message, exception);
  107046. };
  107047. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  107048. };
  107049. return TextureAssetTask;
  107050. }(AbstractAssetTask));
  107051. BABYLON.TextureAssetTask = TextureAssetTask;
  107052. /**
  107053. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  107054. */
  107055. var CubeTextureAssetTask = /** @class */ (function (_super) {
  107056. __extends(CubeTextureAssetTask, _super);
  107057. /**
  107058. * Creates a new CubeTextureAssetTask
  107059. * @param name defines the name of the task
  107060. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  107061. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  107062. * @param noMipmap defines if mipmaps should not be generated (default is false)
  107063. * @param files defines the explicit list of files (undefined by default)
  107064. */
  107065. function CubeTextureAssetTask(
  107066. /**
  107067. * Defines the name of the task
  107068. */
  107069. name,
  107070. /**
  107071. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  107072. */
  107073. url,
  107074. /**
  107075. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  107076. */
  107077. extensions,
  107078. /**
  107079. * Defines if mipmaps should not be generated (default is false)
  107080. */
  107081. noMipmap,
  107082. /**
  107083. * Defines the explicit list of files (undefined by default)
  107084. */
  107085. files) {
  107086. var _this = _super.call(this, name) || this;
  107087. _this.name = name;
  107088. _this.url = url;
  107089. _this.extensions = extensions;
  107090. _this.noMipmap = noMipmap;
  107091. _this.files = files;
  107092. return _this;
  107093. }
  107094. /**
  107095. * Execute the current task
  107096. * @param scene defines the scene where you want your assets to be loaded
  107097. * @param onSuccess is a callback called when the task is successfully executed
  107098. * @param onError is a callback called if an error occurs
  107099. */
  107100. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107101. var onload = function () {
  107102. onSuccess();
  107103. };
  107104. var onerror = function (message, exception) {
  107105. onError(message, exception);
  107106. };
  107107. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  107108. };
  107109. return CubeTextureAssetTask;
  107110. }(AbstractAssetTask));
  107111. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  107112. /**
  107113. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  107114. */
  107115. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  107116. __extends(HDRCubeTextureAssetTask, _super);
  107117. /**
  107118. * Creates a new HDRCubeTextureAssetTask object
  107119. * @param name defines the name of the task
  107120. * @param url defines the location of the file to load
  107121. * @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.
  107122. * @param noMipmap defines if mipmaps should not be generated (default is false)
  107123. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  107124. * @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)
  107125. * @param reserved Internal use only
  107126. */
  107127. function HDRCubeTextureAssetTask(
  107128. /**
  107129. * Defines the name of the task
  107130. */
  107131. name,
  107132. /**
  107133. * Defines the location of the file to load
  107134. */
  107135. url,
  107136. /**
  107137. * Defines the desired size (the more it increases the longer the generation will be)
  107138. */
  107139. size,
  107140. /**
  107141. * Defines if mipmaps should not be generated (default is false)
  107142. */
  107143. noMipmap,
  107144. /**
  107145. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  107146. */
  107147. generateHarmonics,
  107148. /**
  107149. * 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)
  107150. */
  107151. gammaSpace,
  107152. /**
  107153. * Internal Use Only
  107154. */
  107155. reserved) {
  107156. if (noMipmap === void 0) { noMipmap = false; }
  107157. if (generateHarmonics === void 0) { generateHarmonics = true; }
  107158. if (gammaSpace === void 0) { gammaSpace = false; }
  107159. if (reserved === void 0) { reserved = false; }
  107160. var _this = _super.call(this, name) || this;
  107161. _this.name = name;
  107162. _this.url = url;
  107163. _this.size = size;
  107164. _this.noMipmap = noMipmap;
  107165. _this.generateHarmonics = generateHarmonics;
  107166. _this.gammaSpace = gammaSpace;
  107167. _this.reserved = reserved;
  107168. return _this;
  107169. }
  107170. /**
  107171. * Execute the current task
  107172. * @param scene defines the scene where you want your assets to be loaded
  107173. * @param onSuccess is a callback called when the task is successfully executed
  107174. * @param onError is a callback called if an error occurs
  107175. */
  107176. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  107177. var onload = function () {
  107178. onSuccess();
  107179. };
  107180. var onerror = function (message, exception) {
  107181. onError(message, exception);
  107182. };
  107183. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  107184. };
  107185. return HDRCubeTextureAssetTask;
  107186. }(AbstractAssetTask));
  107187. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  107188. /**
  107189. * This class can be used to easily import assets into a scene
  107190. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  107191. */
  107192. var AssetsManager = /** @class */ (function () {
  107193. /**
  107194. * Creates a new AssetsManager
  107195. * @param scene defines the scene to work on
  107196. */
  107197. function AssetsManager(scene) {
  107198. this._isLoading = false;
  107199. this._tasks = new Array();
  107200. this._waitingTasksCount = 0;
  107201. this._totalTasksCount = 0;
  107202. /**
  107203. * Observable called when all tasks are processed
  107204. */
  107205. this.onTaskSuccessObservable = new BABYLON.Observable();
  107206. /**
  107207. * Observable called when a task had an error
  107208. */
  107209. this.onTaskErrorObservable = new BABYLON.Observable();
  107210. /**
  107211. * Observable called when a task is successful
  107212. */
  107213. this.onTasksDoneObservable = new BABYLON.Observable();
  107214. /**
  107215. * Observable called when a task is done (whatever the result is)
  107216. */
  107217. this.onProgressObservable = new BABYLON.Observable();
  107218. /**
  107219. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  107220. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  107221. */
  107222. this.useDefaultLoadingScreen = true;
  107223. this._scene = scene;
  107224. }
  107225. /**
  107226. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  107227. * @param taskName defines the name of the new task
  107228. * @param meshesNames defines the name of meshes to load
  107229. * @param rootUrl defines the root url to use to locate files
  107230. * @param sceneFilename defines the filename of the scene file
  107231. * @returns a new {BABYLON.MeshAssetTask} object
  107232. */
  107233. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  107234. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  107235. this._tasks.push(task);
  107236. return task;
  107237. };
  107238. /**
  107239. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  107240. * @param taskName defines the name of the new task
  107241. * @param url defines the url of the file to load
  107242. * @returns a new {BABYLON.TextFileAssetTask} object
  107243. */
  107244. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  107245. var task = new TextFileAssetTask(taskName, url);
  107246. this._tasks.push(task);
  107247. return task;
  107248. };
  107249. /**
  107250. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  107251. * @param taskName defines the name of the new task
  107252. * @param url defines the url of the file to load
  107253. * @returns a new {BABYLON.BinaryFileAssetTask} object
  107254. */
  107255. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  107256. var task = new BinaryFileAssetTask(taskName, url);
  107257. this._tasks.push(task);
  107258. return task;
  107259. };
  107260. /**
  107261. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  107262. * @param taskName defines the name of the new task
  107263. * @param url defines the url of the file to load
  107264. * @returns a new {BABYLON.ImageAssetTask} object
  107265. */
  107266. AssetsManager.prototype.addImageTask = function (taskName, url) {
  107267. var task = new ImageAssetTask(taskName, url);
  107268. this._tasks.push(task);
  107269. return task;
  107270. };
  107271. /**
  107272. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  107273. * @param taskName defines the name of the new task
  107274. * @param url defines the url of the file to load
  107275. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107276. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  107277. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  107278. * @returns a new {BABYLON.TextureAssetTask} object
  107279. */
  107280. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  107281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  107282. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  107283. this._tasks.push(task);
  107284. return task;
  107285. };
  107286. /**
  107287. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  107288. * @param taskName defines the name of the new task
  107289. * @param url defines the url of the file to load
  107290. * @param extensions defines the extension to use to load the cube map (can be null)
  107291. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107292. * @param files defines the list of files to load (can be null)
  107293. * @returns a new {BABYLON.CubeTextureAssetTask} object
  107294. */
  107295. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  107296. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  107297. this._tasks.push(task);
  107298. return task;
  107299. };
  107300. /**
  107301. *
  107302. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  107303. * @param taskName defines the name of the new task
  107304. * @param url defines the url of the file to load
  107305. * @param size defines the size you want for the cubemap (can be null)
  107306. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107307. * @param generateHarmonics defines if you want to automatically generate (true by default)
  107308. * @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)
  107309. * @param reserved Internal use only
  107310. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  107311. */
  107312. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  107313. if (noMipmap === void 0) { noMipmap = false; }
  107314. if (generateHarmonics === void 0) { generateHarmonics = true; }
  107315. if (gammaSpace === void 0) { gammaSpace = false; }
  107316. if (reserved === void 0) { reserved = false; }
  107317. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  107318. this._tasks.push(task);
  107319. return task;
  107320. };
  107321. /**
  107322. * Remove a task from the assets manager.
  107323. * @param task the task to remove
  107324. */
  107325. AssetsManager.prototype.removeTask = function (task) {
  107326. var index = this._tasks.indexOf(task);
  107327. if (index > -1) {
  107328. this._tasks.splice(index, 1);
  107329. }
  107330. };
  107331. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  107332. this._waitingTasksCount--;
  107333. try {
  107334. if (this.onProgress) {
  107335. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  107336. }
  107337. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  107338. }
  107339. catch (e) {
  107340. BABYLON.Tools.Error("Error running progress callbacks.");
  107341. console.log(e);
  107342. }
  107343. if (this._waitingTasksCount === 0) {
  107344. try {
  107345. if (this.onFinish) {
  107346. this.onFinish(this._tasks);
  107347. }
  107348. // Let's remove successfull tasks
  107349. var currentTasks = this._tasks.slice();
  107350. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  107351. var task = currentTasks_1[_i];
  107352. if (task.taskState === AssetTaskState.DONE) {
  107353. var index = this._tasks.indexOf(task);
  107354. if (index > -1) {
  107355. this._tasks.splice(index, 1);
  107356. }
  107357. }
  107358. }
  107359. this.onTasksDoneObservable.notifyObservers(this._tasks);
  107360. }
  107361. catch (e) {
  107362. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  107363. console.log(e);
  107364. }
  107365. this._isLoading = false;
  107366. this._scene.getEngine().hideLoadingUI();
  107367. }
  107368. };
  107369. AssetsManager.prototype._runTask = function (task) {
  107370. var _this = this;
  107371. var done = function () {
  107372. try {
  107373. if (_this.onTaskSuccess) {
  107374. _this.onTaskSuccess(task);
  107375. }
  107376. _this.onTaskSuccessObservable.notifyObservers(task);
  107377. _this._decreaseWaitingTasksCount(task);
  107378. }
  107379. catch (e) {
  107380. error("Error executing task success callbacks", e);
  107381. }
  107382. };
  107383. var error = function (message, exception) {
  107384. task._setErrorObject(message, exception);
  107385. if (_this.onTaskError) {
  107386. _this.onTaskError(task);
  107387. }
  107388. _this.onTaskErrorObservable.notifyObservers(task);
  107389. _this._decreaseWaitingTasksCount(task);
  107390. };
  107391. task.run(this._scene, done, error);
  107392. };
  107393. /**
  107394. * Reset the {BABYLON.AssetsManager} and remove all tasks
  107395. * @return the current instance of the {BABYLON.AssetsManager}
  107396. */
  107397. AssetsManager.prototype.reset = function () {
  107398. this._isLoading = false;
  107399. this._tasks = new Array();
  107400. return this;
  107401. };
  107402. /**
  107403. * Start the loading process
  107404. * @return the current instance of the {BABYLON.AssetsManager}
  107405. */
  107406. AssetsManager.prototype.load = function () {
  107407. if (this._isLoading) {
  107408. return this;
  107409. }
  107410. this._isLoading = true;
  107411. this._waitingTasksCount = this._tasks.length;
  107412. this._totalTasksCount = this._tasks.length;
  107413. if (this._waitingTasksCount === 0) {
  107414. this._isLoading = false;
  107415. if (this.onFinish) {
  107416. this.onFinish(this._tasks);
  107417. }
  107418. this.onTasksDoneObservable.notifyObservers(this._tasks);
  107419. return this;
  107420. }
  107421. if (this.useDefaultLoadingScreen) {
  107422. this._scene.getEngine().displayLoadingUI();
  107423. }
  107424. for (var index = 0; index < this._tasks.length; index++) {
  107425. var task = this._tasks[index];
  107426. if (task.taskState === AssetTaskState.INIT) {
  107427. this._runTask(task);
  107428. }
  107429. }
  107430. return this;
  107431. };
  107432. return AssetsManager;
  107433. }());
  107434. BABYLON.AssetsManager = AssetsManager;
  107435. })(BABYLON || (BABYLON = {}));
  107436. //# sourceMappingURL=babylon.assetsManager.js.map
  107437. var BABYLON;
  107438. (function (BABYLON) {
  107439. var serializedGeometries = [];
  107440. var serializeGeometry = function (geometry, serializationGeometries) {
  107441. if (serializedGeometries[geometry.id]) {
  107442. return;
  107443. }
  107444. if (geometry.doNotSerialize) {
  107445. return;
  107446. }
  107447. if (geometry instanceof BABYLON.BoxGeometry) {
  107448. serializationGeometries.boxes.push(geometry.serialize());
  107449. }
  107450. else if (geometry instanceof BABYLON.SphereGeometry) {
  107451. serializationGeometries.spheres.push(geometry.serialize());
  107452. }
  107453. else if (geometry instanceof BABYLON.CylinderGeometry) {
  107454. serializationGeometries.cylinders.push(geometry.serialize());
  107455. }
  107456. else if (geometry instanceof BABYLON.TorusGeometry) {
  107457. serializationGeometries.toruses.push(geometry.serialize());
  107458. }
  107459. else if (geometry instanceof BABYLON.GroundGeometry) {
  107460. serializationGeometries.grounds.push(geometry.serialize());
  107461. }
  107462. else if (geometry instanceof BABYLON.Plane) {
  107463. serializationGeometries.planes.push(geometry.serialize());
  107464. }
  107465. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  107466. serializationGeometries.torusKnots.push(geometry.serialize());
  107467. }
  107468. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  107469. throw new Error("Unknown primitive type");
  107470. }
  107471. else {
  107472. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  107473. }
  107474. serializedGeometries[geometry.id] = true;
  107475. };
  107476. var serializeMesh = function (mesh, serializationScene) {
  107477. var serializationObject = {};
  107478. // Geometry
  107479. var geometry = mesh._geometry;
  107480. if (geometry) {
  107481. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  107482. // 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
  107483. serializeGeometry(geometry, serializationScene.geometries);
  107484. }
  107485. }
  107486. // Custom
  107487. if (mesh.serialize) {
  107488. mesh.serialize(serializationObject);
  107489. }
  107490. return serializationObject;
  107491. };
  107492. var finalizeSingleMesh = function (mesh, serializationObject) {
  107493. //only works if the mesh is already loaded
  107494. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  107495. //serialize material
  107496. if (mesh.material) {
  107497. if (mesh.material instanceof BABYLON.MultiMaterial) {
  107498. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  107499. serializationObject.materials = serializationObject.materials || [];
  107500. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  107501. serializationObject.multiMaterials.push(mesh.material.serialize());
  107502. var _loop_1 = function (submaterial) {
  107503. if (submaterial) {
  107504. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  107505. serializationObject.materials.push(submaterial.serialize());
  107506. }
  107507. }
  107508. };
  107509. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  107510. var submaterial = _a[_i];
  107511. _loop_1(submaterial);
  107512. }
  107513. }
  107514. }
  107515. else {
  107516. serializationObject.materials = serializationObject.materials || [];
  107517. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  107518. serializationObject.materials.push(mesh.material.serialize());
  107519. }
  107520. }
  107521. }
  107522. //serialize geometry
  107523. var geometry = mesh._geometry;
  107524. if (geometry) {
  107525. if (!serializationObject.geometries) {
  107526. serializationObject.geometries = {};
  107527. serializationObject.geometries.boxes = [];
  107528. serializationObject.geometries.spheres = [];
  107529. serializationObject.geometries.cylinders = [];
  107530. serializationObject.geometries.toruses = [];
  107531. serializationObject.geometries.grounds = [];
  107532. serializationObject.geometries.planes = [];
  107533. serializationObject.geometries.torusKnots = [];
  107534. serializationObject.geometries.vertexData = [];
  107535. }
  107536. serializeGeometry(geometry, serializationObject.geometries);
  107537. }
  107538. // Skeletons
  107539. if (mesh.skeleton) {
  107540. serializationObject.skeletons = serializationObject.skeletons || [];
  107541. serializationObject.skeletons.push(mesh.skeleton.serialize());
  107542. }
  107543. //serialize the actual mesh
  107544. serializationObject.meshes = serializationObject.meshes || [];
  107545. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  107546. }
  107547. };
  107548. var SceneSerializer = /** @class */ (function () {
  107549. function SceneSerializer() {
  107550. }
  107551. SceneSerializer.ClearCache = function () {
  107552. serializedGeometries = [];
  107553. };
  107554. SceneSerializer.Serialize = function (scene) {
  107555. var serializationObject = {};
  107556. SceneSerializer.ClearCache();
  107557. // Scene
  107558. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  107559. serializationObject.autoClear = scene.autoClear;
  107560. serializationObject.clearColor = scene.clearColor.asArray();
  107561. serializationObject.ambientColor = scene.ambientColor.asArray();
  107562. serializationObject.gravity = scene.gravity.asArray();
  107563. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  107564. serializationObject.workerCollisions = scene.workerCollisions;
  107565. // Fog
  107566. if (scene.fogMode && scene.fogMode !== 0) {
  107567. serializationObject.fogMode = scene.fogMode;
  107568. serializationObject.fogColor = scene.fogColor.asArray();
  107569. serializationObject.fogStart = scene.fogStart;
  107570. serializationObject.fogEnd = scene.fogEnd;
  107571. serializationObject.fogDensity = scene.fogDensity;
  107572. }
  107573. //Physics
  107574. if (scene.isPhysicsEnabled()) {
  107575. var physicEngine = scene.getPhysicsEngine();
  107576. if (physicEngine) {
  107577. serializationObject.physicsEnabled = true;
  107578. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  107579. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  107580. }
  107581. }
  107582. // Metadata
  107583. if (scene.metadata) {
  107584. serializationObject.metadata = scene.metadata;
  107585. }
  107586. // Morph targets
  107587. serializationObject.morphTargetManagers = [];
  107588. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  107589. var abstractMesh = _a[_i];
  107590. var manager = abstractMesh.morphTargetManager;
  107591. if (manager) {
  107592. serializationObject.morphTargetManagers.push(manager.serialize());
  107593. }
  107594. }
  107595. // Lights
  107596. serializationObject.lights = [];
  107597. var index;
  107598. var light;
  107599. for (index = 0; index < scene.lights.length; index++) {
  107600. light = scene.lights[index];
  107601. if (!light.doNotSerialize) {
  107602. serializationObject.lights.push(light.serialize());
  107603. }
  107604. }
  107605. // Cameras
  107606. serializationObject.cameras = [];
  107607. for (index = 0; index < scene.cameras.length; index++) {
  107608. var camera = scene.cameras[index];
  107609. if (!camera.doNotSerialize) {
  107610. serializationObject.cameras.push(camera.serialize());
  107611. }
  107612. }
  107613. if (scene.activeCamera) {
  107614. serializationObject.activeCameraID = scene.activeCamera.id;
  107615. }
  107616. // Animations
  107617. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  107618. // Materials
  107619. serializationObject.materials = [];
  107620. serializationObject.multiMaterials = [];
  107621. var material;
  107622. for (index = 0; index < scene.materials.length; index++) {
  107623. material = scene.materials[index];
  107624. if (!material.doNotSerialize) {
  107625. serializationObject.materials.push(material.serialize());
  107626. }
  107627. }
  107628. // MultiMaterials
  107629. serializationObject.multiMaterials = [];
  107630. for (index = 0; index < scene.multiMaterials.length; index++) {
  107631. var multiMaterial = scene.multiMaterials[index];
  107632. serializationObject.multiMaterials.push(multiMaterial.serialize());
  107633. }
  107634. // Environment texture
  107635. if (scene.environmentTexture) {
  107636. serializationObject.environmentTexture = scene.environmentTexture.name;
  107637. }
  107638. // Skeletons
  107639. serializationObject.skeletons = [];
  107640. for (index = 0; index < scene.skeletons.length; index++) {
  107641. var skeleton = scene.skeletons[index];
  107642. if (!skeleton.doNotSerialize) {
  107643. serializationObject.skeletons.push(skeleton.serialize());
  107644. }
  107645. }
  107646. // Transform nodes
  107647. serializationObject.transformNodes = [];
  107648. for (index = 0; index < scene.transformNodes.length; index++) {
  107649. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  107650. }
  107651. // Geometries
  107652. serializationObject.geometries = {};
  107653. serializationObject.geometries.boxes = [];
  107654. serializationObject.geometries.spheres = [];
  107655. serializationObject.geometries.cylinders = [];
  107656. serializationObject.geometries.toruses = [];
  107657. serializationObject.geometries.grounds = [];
  107658. serializationObject.geometries.planes = [];
  107659. serializationObject.geometries.torusKnots = [];
  107660. serializationObject.geometries.vertexData = [];
  107661. serializedGeometries = [];
  107662. var geometries = scene.getGeometries();
  107663. for (index = 0; index < geometries.length; index++) {
  107664. var geometry = geometries[index];
  107665. if (geometry.isReady()) {
  107666. serializeGeometry(geometry, serializationObject.geometries);
  107667. }
  107668. }
  107669. // Meshes
  107670. serializationObject.meshes = [];
  107671. for (index = 0; index < scene.meshes.length; index++) {
  107672. var abstractMesh = scene.meshes[index];
  107673. if (abstractMesh instanceof BABYLON.Mesh) {
  107674. var mesh = abstractMesh;
  107675. if (!mesh.doNotSerialize) {
  107676. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  107677. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  107678. }
  107679. }
  107680. }
  107681. }
  107682. // Particles Systems
  107683. serializationObject.particleSystems = [];
  107684. for (index = 0; index < scene.particleSystems.length; index++) {
  107685. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  107686. }
  107687. // Action Manager
  107688. if (scene.actionManager) {
  107689. serializationObject.actions = scene.actionManager.serialize("scene");
  107690. }
  107691. // Components
  107692. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  107693. var component = _c[_b];
  107694. component.serialize(serializationObject);
  107695. }
  107696. return serializationObject;
  107697. };
  107698. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  107699. if (withParents === void 0) { withParents = false; }
  107700. if (withChildren === void 0) { withChildren = false; }
  107701. var serializationObject = {};
  107702. SceneSerializer.ClearCache();
  107703. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  107704. if (withParents || withChildren) {
  107705. //deliberate for loop! not for each, appended should be processed as well.
  107706. for (var i = 0; i < toSerialize.length; ++i) {
  107707. if (withChildren) {
  107708. toSerialize[i].getDescendants().forEach(function (node) {
  107709. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  107710. toSerialize.push(node);
  107711. }
  107712. });
  107713. }
  107714. //make sure the array doesn't contain the object already
  107715. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  107716. toSerialize.push(toSerialize[i].parent);
  107717. }
  107718. }
  107719. }
  107720. toSerialize.forEach(function (mesh) {
  107721. finalizeSingleMesh(mesh, serializationObject);
  107722. });
  107723. return serializationObject;
  107724. };
  107725. return SceneSerializer;
  107726. }());
  107727. BABYLON.SceneSerializer = SceneSerializer;
  107728. })(BABYLON || (BABYLON = {}));
  107729. //# sourceMappingURL=babylon.sceneSerializer.js.map
  107730. var BABYLON;
  107731. (function (BABYLON) {
  107732. /**
  107733. * Class used to generate realtime reflection / refraction cube textures
  107734. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  107735. */
  107736. var ReflectionProbe = /** @class */ (function () {
  107737. /**
  107738. * Creates a new reflection probe
  107739. * @param name defines the name of the probe
  107740. * @param size defines the texture resolution (for each face)
  107741. * @param scene defines the hosting scene
  107742. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  107743. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  107744. */
  107745. function ReflectionProbe(
  107746. /** defines the name of the probe */
  107747. name, size, scene, generateMipMaps, useFloat) {
  107748. if (generateMipMaps === void 0) { generateMipMaps = true; }
  107749. if (useFloat === void 0) { useFloat = false; }
  107750. var _this = this;
  107751. this.name = name;
  107752. this._viewMatrix = BABYLON.Matrix.Identity();
  107753. this._target = BABYLON.Vector3.Zero();
  107754. this._add = BABYLON.Vector3.Zero();
  107755. this._invertYAxis = false;
  107756. /** Gets or sets probe position (center of the cube map) */
  107757. this.position = BABYLON.Vector3.Zero();
  107758. this._scene = scene;
  107759. // Create the scene field if not exist.
  107760. if (!this._scene.reflectionProbes) {
  107761. this._scene.reflectionProbes = new Array();
  107762. }
  107763. this._scene.reflectionProbes.push(this);
  107764. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  107765. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  107766. switch (faceIndex) {
  107767. case 0:
  107768. _this._add.copyFromFloats(1, 0, 0);
  107769. break;
  107770. case 1:
  107771. _this._add.copyFromFloats(-1, 0, 0);
  107772. break;
  107773. case 2:
  107774. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  107775. break;
  107776. case 3:
  107777. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  107778. break;
  107779. case 4:
  107780. _this._add.copyFromFloats(0, 0, 1);
  107781. break;
  107782. case 5:
  107783. _this._add.copyFromFloats(0, 0, -1);
  107784. break;
  107785. }
  107786. if (_this._attachedMesh) {
  107787. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  107788. }
  107789. _this.position.addToRef(_this._add, _this._target);
  107790. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  107791. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  107792. scene._forcedViewPosition = _this.position;
  107793. });
  107794. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  107795. scene._forcedViewPosition = null;
  107796. scene.updateTransformMatrix(true);
  107797. });
  107798. if (scene.activeCamera) {
  107799. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  107800. }
  107801. }
  107802. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  107803. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  107804. get: function () {
  107805. return this._renderTargetTexture.samples;
  107806. },
  107807. set: function (value) {
  107808. this._renderTargetTexture.samples = value;
  107809. },
  107810. enumerable: true,
  107811. configurable: true
  107812. });
  107813. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  107814. /** Gets or sets the refresh rate to use (on every frame by default) */
  107815. get: function () {
  107816. return this._renderTargetTexture.refreshRate;
  107817. },
  107818. set: function (value) {
  107819. this._renderTargetTexture.refreshRate = value;
  107820. },
  107821. enumerable: true,
  107822. configurable: true
  107823. });
  107824. /**
  107825. * Gets the hosting scene
  107826. * @returns a Scene
  107827. */
  107828. ReflectionProbe.prototype.getScene = function () {
  107829. return this._scene;
  107830. };
  107831. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  107832. /** Gets the internal CubeTexture used to render to */
  107833. get: function () {
  107834. return this._renderTargetTexture;
  107835. },
  107836. enumerable: true,
  107837. configurable: true
  107838. });
  107839. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  107840. /** Gets the list of meshes to render */
  107841. get: function () {
  107842. return this._renderTargetTexture.renderList;
  107843. },
  107844. enumerable: true,
  107845. configurable: true
  107846. });
  107847. /**
  107848. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  107849. * @param mesh defines the mesh to attach to
  107850. */
  107851. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  107852. this._attachedMesh = mesh;
  107853. };
  107854. /**
  107855. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  107856. * @param renderingGroupId The rendering group id corresponding to its index
  107857. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  107858. */
  107859. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  107860. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  107861. };
  107862. /**
  107863. * Clean all associated resources
  107864. */
  107865. ReflectionProbe.prototype.dispose = function () {
  107866. var index = this._scene.reflectionProbes.indexOf(this);
  107867. if (index !== -1) {
  107868. // Remove from the scene if found
  107869. this._scene.reflectionProbes.splice(index, 1);
  107870. }
  107871. if (this._renderTargetTexture) {
  107872. this._renderTargetTexture.dispose();
  107873. this._renderTargetTexture = null;
  107874. }
  107875. };
  107876. return ReflectionProbe;
  107877. }());
  107878. BABYLON.ReflectionProbe = ReflectionProbe;
  107879. })(BABYLON || (BABYLON = {}));
  107880. //# sourceMappingURL=babylon.reflectionProbe.js.map
  107881. var BABYLON;
  107882. (function (BABYLON) {
  107883. /**
  107884. * Defines the layer scene component responsible to manage any layers
  107885. * in a given scene.
  107886. */
  107887. var LayerSceneComponent = /** @class */ (function () {
  107888. /**
  107889. * Creates a new instance of the component for the given scene
  107890. * @param scene Defines the scene to register the component in
  107891. */
  107892. function LayerSceneComponent(scene) {
  107893. /**
  107894. * The component name helpfull to identify the component in the list of scene components.
  107895. */
  107896. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  107897. this.scene = scene;
  107898. this._engine = scene.getEngine();
  107899. scene.layers = new Array();
  107900. }
  107901. /**
  107902. * Registers the component in a given scene
  107903. */
  107904. LayerSceneComponent.prototype.register = function () {
  107905. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  107906. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  107907. };
  107908. /**
  107909. * Rebuilds the elements related to this component in case of
  107910. * context lost for instance.
  107911. */
  107912. LayerSceneComponent.prototype.rebuild = function () {
  107913. var layers = this.scene.layers;
  107914. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  107915. var layer = layers_1[_i];
  107916. layer._rebuild();
  107917. }
  107918. };
  107919. /**
  107920. * Disposes the component and the associated ressources.
  107921. */
  107922. LayerSceneComponent.prototype.dispose = function () {
  107923. var layers = this.scene.layers;
  107924. while (layers.length) {
  107925. layers[0].dispose();
  107926. }
  107927. };
  107928. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  107929. var layers = this.scene.layers;
  107930. if (layers.length) {
  107931. this._engine.setDepthBuffer(false);
  107932. var cameraLayerMask = camera.layerMask;
  107933. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  107934. var layer = layers_2[_i];
  107935. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  107936. layer.render();
  107937. }
  107938. }
  107939. this._engine.setDepthBuffer(true);
  107940. }
  107941. };
  107942. LayerSceneComponent.prototype._drawBackground = function (camera) {
  107943. this._draw(camera, true);
  107944. };
  107945. LayerSceneComponent.prototype._drawForeground = function (camera) {
  107946. this._draw(camera, false);
  107947. };
  107948. return LayerSceneComponent;
  107949. }());
  107950. BABYLON.LayerSceneComponent = LayerSceneComponent;
  107951. })(BABYLON || (BABYLON = {}));
  107952. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  107953. var BABYLON;
  107954. (function (BABYLON) {
  107955. /**
  107956. * This represents a full screen 2d layer.
  107957. * This can be usefull to display a picture in the background of your scene for instance.
  107958. * @see https://www.babylonjs-playground.com/#08A2BS#1
  107959. */
  107960. var Layer = /** @class */ (function () {
  107961. /**
  107962. * Instantiates a new layer.
  107963. * This represents a full screen 2d layer.
  107964. * This can be usefull to display a picture in the background of your scene for instance.
  107965. * @see https://www.babylonjs-playground.com/#08A2BS#1
  107966. * @param name Define the name of the layer in the scene
  107967. * @param imgUrl Define the url of the texture to display in the layer
  107968. * @param scene Define the scene the layer belongs to
  107969. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  107970. * @param color Defines a color for the layer
  107971. */
  107972. function Layer(
  107973. /**
  107974. * Define the name of the layer.
  107975. */
  107976. name, imgUrl, scene, isBackground, color) {
  107977. this.name = name;
  107978. /**
  107979. * Define the scale of the layer in order to zoom in out of the texture.
  107980. */
  107981. this.scale = new BABYLON.Vector2(1, 1);
  107982. /**
  107983. * Define an offset for the layer in order to shift the texture.
  107984. */
  107985. this.offset = new BABYLON.Vector2(0, 0);
  107986. /**
  107987. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  107988. */
  107989. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  107990. /**
  107991. * Define a mask to restrict the layer to only some of the scene cameras.
  107992. */
  107993. this.layerMask = 0x0FFFFFFF;
  107994. this._vertexBuffers = {};
  107995. /**
  107996. * An event triggered when the layer is disposed.
  107997. */
  107998. this.onDisposeObservable = new BABYLON.Observable();
  107999. /**
  108000. * An event triggered before rendering the scene
  108001. */
  108002. this.onBeforeRenderObservable = new BABYLON.Observable();
  108003. /**
  108004. * An event triggered after rendering the scene
  108005. */
  108006. this.onAfterRenderObservable = new BABYLON.Observable();
  108007. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  108008. this.isBackground = isBackground === undefined ? true : isBackground;
  108009. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  108010. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  108011. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  108012. if (!layerComponent) {
  108013. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  108014. this._scene._addComponent(layerComponent);
  108015. }
  108016. this._scene.layers.push(this);
  108017. var engine = this._scene.getEngine();
  108018. // VBO
  108019. var vertices = [];
  108020. vertices.push(1, 1);
  108021. vertices.push(-1, 1);
  108022. vertices.push(-1, -1);
  108023. vertices.push(1, -1);
  108024. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  108025. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  108026. this._createIndexBuffer();
  108027. // Effects
  108028. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  108029. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  108030. }
  108031. Object.defineProperty(Layer.prototype, "onDispose", {
  108032. /**
  108033. * Back compatibility with callback before the onDisposeObservable existed.
  108034. * The set callback will be triggered when the layer has been disposed.
  108035. */
  108036. set: function (callback) {
  108037. if (this._onDisposeObserver) {
  108038. this.onDisposeObservable.remove(this._onDisposeObserver);
  108039. }
  108040. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  108041. },
  108042. enumerable: true,
  108043. configurable: true
  108044. });
  108045. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  108046. /**
  108047. * Back compatibility with callback before the onBeforeRenderObservable existed.
  108048. * The set callback will be triggered just before rendering the layer.
  108049. */
  108050. set: function (callback) {
  108051. if (this._onBeforeRenderObserver) {
  108052. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  108053. }
  108054. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  108055. },
  108056. enumerable: true,
  108057. configurable: true
  108058. });
  108059. Object.defineProperty(Layer.prototype, "onAfterRender", {
  108060. /**
  108061. * Back compatibility with callback before the onAfterRenderObservable existed.
  108062. * The set callback will be triggered just after rendering the layer.
  108063. */
  108064. set: function (callback) {
  108065. if (this._onAfterRenderObserver) {
  108066. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  108067. }
  108068. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  108069. },
  108070. enumerable: true,
  108071. configurable: true
  108072. });
  108073. Layer.prototype._createIndexBuffer = function () {
  108074. var engine = this._scene.getEngine();
  108075. // Indices
  108076. var indices = [];
  108077. indices.push(0);
  108078. indices.push(1);
  108079. indices.push(2);
  108080. indices.push(0);
  108081. indices.push(2);
  108082. indices.push(3);
  108083. this._indexBuffer = engine.createIndexBuffer(indices);
  108084. };
  108085. /** @hidden */
  108086. Layer.prototype._rebuild = function () {
  108087. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  108088. if (vb) {
  108089. vb._rebuild();
  108090. }
  108091. this._createIndexBuffer();
  108092. };
  108093. /**
  108094. * Renders the layer in the scene.
  108095. */
  108096. Layer.prototype.render = function () {
  108097. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  108098. // Check
  108099. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  108100. return;
  108101. var engine = this._scene.getEngine();
  108102. this.onBeforeRenderObservable.notifyObservers(this);
  108103. // Render
  108104. engine.enableEffect(currentEffect);
  108105. engine.setState(false);
  108106. // Texture
  108107. currentEffect.setTexture("textureSampler", this.texture);
  108108. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  108109. // Color
  108110. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  108111. // Scale / offset
  108112. currentEffect.setVector2("offset", this.offset);
  108113. currentEffect.setVector2("scale", this.scale);
  108114. // VBOs
  108115. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  108116. // Draw order
  108117. if (!this.alphaTest) {
  108118. engine.setAlphaMode(this.alphaBlendingMode);
  108119. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108120. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108121. }
  108122. else {
  108123. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108124. }
  108125. this.onAfterRenderObservable.notifyObservers(this);
  108126. };
  108127. /**
  108128. * Disposes and releases the associated ressources.
  108129. */
  108130. Layer.prototype.dispose = function () {
  108131. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  108132. if (vertexBuffer) {
  108133. vertexBuffer.dispose();
  108134. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  108135. }
  108136. if (this._indexBuffer) {
  108137. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  108138. this._indexBuffer = null;
  108139. }
  108140. if (this.texture) {
  108141. this.texture.dispose();
  108142. this.texture = null;
  108143. }
  108144. // Remove from scene
  108145. var index = this._scene.layers.indexOf(this);
  108146. this._scene.layers.splice(index, 1);
  108147. // Callback
  108148. this.onDisposeObservable.notifyObservers(this);
  108149. this.onDisposeObservable.clear();
  108150. this.onAfterRenderObservable.clear();
  108151. this.onBeforeRenderObservable.clear();
  108152. };
  108153. return Layer;
  108154. }());
  108155. BABYLON.Layer = Layer;
  108156. })(BABYLON || (BABYLON = {}));
  108157. //# sourceMappingURL=babylon.layer.js.map
  108158. var BABYLON;
  108159. (function (BABYLON) {
  108160. var TextureTools = /** @class */ (function () {
  108161. function TextureTools() {
  108162. }
  108163. /**
  108164. * Uses the GPU to create a copy texture rescaled at a given size
  108165. * @param texture Texture to copy from
  108166. * @param width Desired width
  108167. * @param height Desired height
  108168. * @return Generated texture
  108169. */
  108170. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  108171. if (useBilinearMode === void 0) { useBilinearMode = true; }
  108172. var scene = texture.getScene();
  108173. var engine = scene.getEngine();
  108174. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  108175. rtt.wrapU = texture.wrapU;
  108176. rtt.wrapV = texture.wrapV;
  108177. rtt.uOffset = texture.uOffset;
  108178. rtt.vOffset = texture.vOffset;
  108179. rtt.uScale = texture.uScale;
  108180. rtt.vScale = texture.vScale;
  108181. rtt.uAng = texture.uAng;
  108182. rtt.vAng = texture.vAng;
  108183. rtt.wAng = texture.wAng;
  108184. rtt.coordinatesIndex = texture.coordinatesIndex;
  108185. rtt.level = texture.level;
  108186. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  108187. rtt._texture.isReady = false;
  108188. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108189. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108190. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  108191. passPostProcess.getEffect().executeWhenCompiled(function () {
  108192. passPostProcess.onApply = function (effect) {
  108193. effect.setTexture("textureSampler", texture);
  108194. };
  108195. var internalTexture = rtt.getInternalTexture();
  108196. if (internalTexture) {
  108197. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  108198. engine.unBindFramebuffer(internalTexture);
  108199. rtt.disposeFramebufferObjects();
  108200. passPostProcess.dispose();
  108201. internalTexture.isReady = true;
  108202. }
  108203. });
  108204. return rtt;
  108205. };
  108206. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  108207. if (!scene._environmentBRDFTexture) {
  108208. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108209. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108210. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108211. scene._environmentBRDFTexture = texture;
  108212. }
  108213. return scene._environmentBRDFTexture;
  108214. };
  108215. 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=";
  108216. return TextureTools;
  108217. }());
  108218. BABYLON.TextureTools = TextureTools;
  108219. })(BABYLON || (BABYLON = {}));
  108220. //# sourceMappingURL=babylon.textureTools.js.map
  108221. var BABYLON;
  108222. (function (BABYLON) {
  108223. /**
  108224. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  108225. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  108226. */
  108227. var FramingBehavior = /** @class */ (function () {
  108228. function FramingBehavior() {
  108229. this._mode = FramingBehavior.FitFrustumSidesMode;
  108230. this._radiusScale = 1.0;
  108231. this._positionScale = 0.5;
  108232. this._defaultElevation = 0.3;
  108233. this._elevationReturnTime = 1500;
  108234. this._elevationReturnWaitTime = 1000;
  108235. this._zoomStopsAnimation = false;
  108236. this._framingTime = 1500;
  108237. /**
  108238. * Define if the behavior should automatically change the configured
  108239. * camera limits and sensibilities.
  108240. */
  108241. this.autoCorrectCameraLimitsAndSensibility = true;
  108242. this._isPointerDown = false;
  108243. this._lastInteractionTime = -Infinity;
  108244. // Framing control
  108245. this._animatables = new Array();
  108246. this._betaIsAnimating = false;
  108247. }
  108248. Object.defineProperty(FramingBehavior.prototype, "name", {
  108249. /**
  108250. * Gets the name of the behavior.
  108251. */
  108252. get: function () {
  108253. return "Framing";
  108254. },
  108255. enumerable: true,
  108256. configurable: true
  108257. });
  108258. Object.defineProperty(FramingBehavior.prototype, "mode", {
  108259. /**
  108260. * Gets current mode used by the behavior.
  108261. */
  108262. get: function () {
  108263. return this._mode;
  108264. },
  108265. /**
  108266. * Sets the current mode used by the behavior
  108267. */
  108268. set: function (mode) {
  108269. this._mode = mode;
  108270. },
  108271. enumerable: true,
  108272. configurable: true
  108273. });
  108274. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  108275. /**
  108276. * Gets the scale applied to the radius
  108277. */
  108278. get: function () {
  108279. return this._radiusScale;
  108280. },
  108281. /**
  108282. * Sets the scale applied to the radius (1 by default)
  108283. */
  108284. set: function (radius) {
  108285. this._radiusScale = radius;
  108286. },
  108287. enumerable: true,
  108288. configurable: true
  108289. });
  108290. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  108291. /**
  108292. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  108293. */
  108294. get: function () {
  108295. return this._positionScale;
  108296. },
  108297. /**
  108298. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  108299. */
  108300. set: function (scale) {
  108301. this._positionScale = scale;
  108302. },
  108303. enumerable: true,
  108304. configurable: true
  108305. });
  108306. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  108307. /**
  108308. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  108309. * behaviour is triggered, in radians.
  108310. */
  108311. get: function () {
  108312. return this._defaultElevation;
  108313. },
  108314. /**
  108315. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  108316. * behaviour is triggered, in radians.
  108317. */
  108318. set: function (elevation) {
  108319. this._defaultElevation = elevation;
  108320. },
  108321. enumerable: true,
  108322. configurable: true
  108323. });
  108324. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  108325. /**
  108326. * Gets the time (in milliseconds) taken to return to the default beta position.
  108327. * Negative value indicates camera should not return to default.
  108328. */
  108329. get: function () {
  108330. return this._elevationReturnTime;
  108331. },
  108332. /**
  108333. * Sets the time (in milliseconds) taken to return to the default beta position.
  108334. * Negative value indicates camera should not return to default.
  108335. */
  108336. set: function (speed) {
  108337. this._elevationReturnTime = speed;
  108338. },
  108339. enumerable: true,
  108340. configurable: true
  108341. });
  108342. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  108343. /**
  108344. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  108345. */
  108346. get: function () {
  108347. return this._elevationReturnWaitTime;
  108348. },
  108349. /**
  108350. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  108351. */
  108352. set: function (time) {
  108353. this._elevationReturnWaitTime = time;
  108354. },
  108355. enumerable: true,
  108356. configurable: true
  108357. });
  108358. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  108359. /**
  108360. * Gets the flag that indicates if user zooming should stop animation.
  108361. */
  108362. get: function () {
  108363. return this._zoomStopsAnimation;
  108364. },
  108365. /**
  108366. * Sets the flag that indicates if user zooming should stop animation.
  108367. */
  108368. set: function (flag) {
  108369. this._zoomStopsAnimation = flag;
  108370. },
  108371. enumerable: true,
  108372. configurable: true
  108373. });
  108374. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  108375. /**
  108376. * Gets the transition time when framing the mesh, in milliseconds
  108377. */
  108378. get: function () {
  108379. return this._framingTime;
  108380. },
  108381. /**
  108382. * Sets the transition time when framing the mesh, in milliseconds
  108383. */
  108384. set: function (time) {
  108385. this._framingTime = time;
  108386. },
  108387. enumerable: true,
  108388. configurable: true
  108389. });
  108390. /**
  108391. * Initializes the behavior.
  108392. */
  108393. FramingBehavior.prototype.init = function () {
  108394. // Do notihng
  108395. };
  108396. /**
  108397. * Attaches the behavior to its arc rotate camera.
  108398. * @param camera Defines the camera to attach the behavior to
  108399. */
  108400. FramingBehavior.prototype.attach = function (camera) {
  108401. var _this = this;
  108402. this._attachedCamera = camera;
  108403. var scene = this._attachedCamera.getScene();
  108404. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  108405. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  108406. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  108407. _this._isPointerDown = true;
  108408. return;
  108409. }
  108410. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  108411. _this._isPointerDown = false;
  108412. }
  108413. });
  108414. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  108415. if (mesh) {
  108416. _this.zoomOnMesh(mesh);
  108417. }
  108418. });
  108419. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  108420. // Stop the animation if there is user interaction and the animation should stop for this interaction
  108421. _this._applyUserInteraction();
  108422. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  108423. // back to the default position after a given timeout
  108424. _this._maintainCameraAboveGround();
  108425. });
  108426. };
  108427. /**
  108428. * Detaches the behavior from its current arc rotate camera.
  108429. */
  108430. FramingBehavior.prototype.detach = function () {
  108431. if (!this._attachedCamera) {
  108432. return;
  108433. }
  108434. var scene = this._attachedCamera.getScene();
  108435. if (this._onPrePointerObservableObserver) {
  108436. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  108437. }
  108438. if (this._onAfterCheckInputsObserver) {
  108439. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  108440. }
  108441. if (this._onMeshTargetChangedObserver) {
  108442. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108443. }
  108444. this._attachedCamera = null;
  108445. };
  108446. /**
  108447. * Targets the given mesh and updates zoom level accordingly.
  108448. * @param mesh The mesh to target.
  108449. * @param radius Optional. If a cached radius position already exists, overrides default.
  108450. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  108451. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108452. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108453. */
  108454. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  108455. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108456. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108457. mesh.computeWorldMatrix(true);
  108458. var boundingBox = mesh.getBoundingInfo().boundingBox;
  108459. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  108460. };
  108461. /**
  108462. * Targets the given mesh with its children and updates zoom level accordingly.
  108463. * @param mesh The mesh to target.
  108464. * @param radius Optional. If a cached radius position already exists, overrides default.
  108465. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  108466. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108467. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108468. */
  108469. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  108470. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108471. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108472. mesh.computeWorldMatrix(true);
  108473. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  108474. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  108475. };
  108476. /**
  108477. * Targets the given meshes with their children and updates zoom level accordingly.
  108478. * @param meshes The mesh to target.
  108479. * @param radius Optional. If a cached radius position already exists, overrides default.
  108480. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  108481. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108482. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108483. */
  108484. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  108485. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108486. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108487. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  108488. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  108489. for (var i = 0; i < meshes.length; i++) {
  108490. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  108491. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  108492. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  108493. }
  108494. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  108495. };
  108496. /**
  108497. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  108498. * @param minimumWorld Determines the smaller position of the bounding box extend
  108499. * @param maximumWorld Determines the bigger position of the bounding box extend
  108500. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108501. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108502. */
  108503. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  108504. var _this = this;
  108505. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108506. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108507. var zoomTarget;
  108508. if (!this._attachedCamera) {
  108509. return;
  108510. }
  108511. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  108512. var bottom = minimumWorld.y;
  108513. var top = maximumWorld.y;
  108514. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  108515. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  108516. if (focusOnOriginXZ) {
  108517. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  108518. }
  108519. else {
  108520. var centerWorld = minimumWorld.add(radiusWorld);
  108521. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  108522. }
  108523. if (!this._vectorTransition) {
  108524. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  108525. }
  108526. this._betaIsAnimating = true;
  108527. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  108528. if (animatable) {
  108529. this._animatables.push(animatable);
  108530. }
  108531. // sets the radius and lower radius bounds
  108532. // Small delta ensures camera is not always at lower zoom limit.
  108533. var radius = 0;
  108534. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  108535. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  108536. if (this.autoCorrectCameraLimitsAndSensibility) {
  108537. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  108538. }
  108539. radius = position;
  108540. }
  108541. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  108542. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  108543. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  108544. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  108545. }
  108546. }
  108547. // Set sensibilities
  108548. if (this.autoCorrectCameraLimitsAndSensibility) {
  108549. var extend = maximumWorld.subtract(minimumWorld).length();
  108550. this._attachedCamera.panningSensibility = 5000 / extend;
  108551. this._attachedCamera.wheelPrecision = 100 / radius;
  108552. }
  108553. // transition to new radius
  108554. if (!this._radiusTransition) {
  108555. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  108556. }
  108557. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  108558. _this.stopAllAnimations();
  108559. if (onAnimationEnd) {
  108560. onAnimationEnd();
  108561. }
  108562. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  108563. _this._attachedCamera.storeState();
  108564. }
  108565. });
  108566. if (animatable) {
  108567. this._animatables.push(animatable);
  108568. }
  108569. };
  108570. /**
  108571. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  108572. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  108573. * frustum width.
  108574. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  108575. * to fully enclose the mesh in the viewing frustum.
  108576. */
  108577. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  108578. var size = maximumWorld.subtract(minimumWorld);
  108579. var boxVectorGlobalDiagonal = size.length();
  108580. var frustumSlope = this._getFrustumSlope();
  108581. // Formula for setting distance
  108582. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  108583. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  108584. // Horizon distance
  108585. var radius = radiusWithoutFraming * this._radiusScale;
  108586. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  108587. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  108588. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  108589. var camera = this._attachedCamera;
  108590. if (!camera) {
  108591. return 0;
  108592. }
  108593. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  108594. // Don't exceed the requested limit
  108595. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  108596. }
  108597. // Don't exceed the upper radius limit
  108598. if (camera.upperRadiusLimit) {
  108599. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  108600. }
  108601. return distance;
  108602. };
  108603. /**
  108604. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  108605. * is automatically returned to its default position (expected to be above ground plane).
  108606. */
  108607. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  108608. var _this = this;
  108609. if (this._elevationReturnTime < 0) {
  108610. return;
  108611. }
  108612. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  108613. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  108614. var limitBeta = Math.PI * 0.5;
  108615. // Bring the camera back up if below the ground plane
  108616. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  108617. this._betaIsAnimating = true;
  108618. //Transition to new position
  108619. this.stopAllAnimations();
  108620. if (!this._betaTransition) {
  108621. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  108622. }
  108623. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  108624. _this._clearAnimationLocks();
  108625. _this.stopAllAnimations();
  108626. });
  108627. if (animatabe) {
  108628. this._animatables.push(animatabe);
  108629. }
  108630. }
  108631. };
  108632. /**
  108633. * Returns the frustum slope based on the canvas ratio and camera FOV
  108634. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  108635. */
  108636. FramingBehavior.prototype._getFrustumSlope = function () {
  108637. // Calculate the viewport ratio
  108638. // Aspect Ratio is Height/Width.
  108639. var camera = this._attachedCamera;
  108640. if (!camera) {
  108641. return BABYLON.Vector2.Zero();
  108642. }
  108643. var engine = camera.getScene().getEngine();
  108644. var aspectRatio = engine.getAspectRatio(camera);
  108645. // Camera FOV is the vertical field of view (top-bottom) in radians.
  108646. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  108647. var frustumSlopeY = Math.tan(camera.fov / 2);
  108648. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  108649. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  108650. // along the forward vector.
  108651. var frustumSlopeX = frustumSlopeY * aspectRatio;
  108652. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  108653. };
  108654. /**
  108655. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  108656. */
  108657. FramingBehavior.prototype._clearAnimationLocks = function () {
  108658. this._betaIsAnimating = false;
  108659. };
  108660. /**
  108661. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  108662. */
  108663. FramingBehavior.prototype._applyUserInteraction = function () {
  108664. if (this.isUserIsMoving) {
  108665. this._lastInteractionTime = BABYLON.Tools.Now;
  108666. this.stopAllAnimations();
  108667. this._clearAnimationLocks();
  108668. }
  108669. };
  108670. /**
  108671. * Stops and removes all animations that have been applied to the camera
  108672. */
  108673. FramingBehavior.prototype.stopAllAnimations = function () {
  108674. if (this._attachedCamera) {
  108675. this._attachedCamera.animations = [];
  108676. }
  108677. while (this._animatables.length) {
  108678. if (this._animatables[0]) {
  108679. this._animatables[0].onAnimationEnd = null;
  108680. this._animatables[0].stop();
  108681. }
  108682. this._animatables.shift();
  108683. }
  108684. };
  108685. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  108686. /**
  108687. * Gets a value indicating if the user is moving the camera
  108688. */
  108689. get: function () {
  108690. if (!this._attachedCamera) {
  108691. return false;
  108692. }
  108693. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  108694. this._attachedCamera.inertialBetaOffset !== 0 ||
  108695. this._attachedCamera.inertialRadiusOffset !== 0 ||
  108696. this._attachedCamera.inertialPanningX !== 0 ||
  108697. this._attachedCamera.inertialPanningY !== 0 ||
  108698. this._isPointerDown;
  108699. },
  108700. enumerable: true,
  108701. configurable: true
  108702. });
  108703. /**
  108704. * The easing function used by animations
  108705. */
  108706. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  108707. /**
  108708. * The easing mode used by animations
  108709. */
  108710. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  108711. // Statics
  108712. /**
  108713. * The camera can move all the way towards the mesh.
  108714. */
  108715. FramingBehavior.IgnoreBoundsSizeMode = 0;
  108716. /**
  108717. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  108718. */
  108719. FramingBehavior.FitFrustumSidesMode = 1;
  108720. return FramingBehavior;
  108721. }());
  108722. BABYLON.FramingBehavior = FramingBehavior;
  108723. })(BABYLON || (BABYLON = {}));
  108724. //# sourceMappingURL=babylon.framingBehavior.js.map
  108725. var BABYLON;
  108726. (function (BABYLON) {
  108727. /**
  108728. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  108729. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  108730. */
  108731. var BouncingBehavior = /** @class */ (function () {
  108732. function BouncingBehavior() {
  108733. /**
  108734. * The duration of the animation, in milliseconds
  108735. */
  108736. this.transitionDuration = 450;
  108737. /**
  108738. * Length of the distance animated by the transition when lower radius is reached
  108739. */
  108740. this.lowerRadiusTransitionRange = 2;
  108741. /**
  108742. * Length of the distance animated by the transition when upper radius is reached
  108743. */
  108744. this.upperRadiusTransitionRange = -2;
  108745. this._autoTransitionRange = false;
  108746. // Animations
  108747. this._radiusIsAnimating = false;
  108748. this._radiusBounceTransition = null;
  108749. this._animatables = new Array();
  108750. }
  108751. Object.defineProperty(BouncingBehavior.prototype, "name", {
  108752. /**
  108753. * Gets the name of the behavior.
  108754. */
  108755. get: function () {
  108756. return "Bouncing";
  108757. },
  108758. enumerable: true,
  108759. configurable: true
  108760. });
  108761. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  108762. /**
  108763. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  108764. */
  108765. get: function () {
  108766. return this._autoTransitionRange;
  108767. },
  108768. /**
  108769. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  108770. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  108771. */
  108772. set: function (value) {
  108773. var _this = this;
  108774. if (this._autoTransitionRange === value) {
  108775. return;
  108776. }
  108777. this._autoTransitionRange = value;
  108778. var camera = this._attachedCamera;
  108779. if (!camera) {
  108780. return;
  108781. }
  108782. if (value) {
  108783. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  108784. if (!mesh) {
  108785. return;
  108786. }
  108787. mesh.computeWorldMatrix(true);
  108788. var diagonal = mesh.getBoundingInfo().diagonalLength;
  108789. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  108790. _this.upperRadiusTransitionRange = diagonal * 0.05;
  108791. });
  108792. }
  108793. else if (this._onMeshTargetChangedObserver) {
  108794. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108795. }
  108796. },
  108797. enumerable: true,
  108798. configurable: true
  108799. });
  108800. /**
  108801. * Initializes the behavior.
  108802. */
  108803. BouncingBehavior.prototype.init = function () {
  108804. // Do notihng
  108805. };
  108806. /**
  108807. * Attaches the behavior to its arc rotate camera.
  108808. * @param camera Defines the camera to attach the behavior to
  108809. */
  108810. BouncingBehavior.prototype.attach = function (camera) {
  108811. var _this = this;
  108812. this._attachedCamera = camera;
  108813. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  108814. if (!_this._attachedCamera) {
  108815. return;
  108816. }
  108817. // Add the bounce animation to the lower radius limit
  108818. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  108819. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  108820. }
  108821. // Add the bounce animation to the upper radius limit
  108822. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  108823. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  108824. }
  108825. });
  108826. };
  108827. /**
  108828. * Detaches the behavior from its current arc rotate camera.
  108829. */
  108830. BouncingBehavior.prototype.detach = function () {
  108831. if (!this._attachedCamera) {
  108832. return;
  108833. }
  108834. if (this._onAfterCheckInputsObserver) {
  108835. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  108836. }
  108837. if (this._onMeshTargetChangedObserver) {
  108838. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108839. }
  108840. this._attachedCamera = null;
  108841. };
  108842. /**
  108843. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  108844. * @param radiusLimit The limit to check against.
  108845. * @return Bool to indicate if at limit.
  108846. */
  108847. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  108848. if (!this._attachedCamera) {
  108849. return false;
  108850. }
  108851. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  108852. return true;
  108853. }
  108854. return false;
  108855. };
  108856. /**
  108857. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  108858. * @param radiusDelta The delta by which to animate to. Can be negative.
  108859. */
  108860. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  108861. var _this = this;
  108862. if (!this._attachedCamera) {
  108863. return;
  108864. }
  108865. if (!this._radiusBounceTransition) {
  108866. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  108867. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  108868. }
  108869. // Prevent zoom until bounce has completed
  108870. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  108871. this._attachedCamera.wheelPrecision = Infinity;
  108872. this._attachedCamera.inertialRadiusOffset = 0;
  108873. // Animate to the radius limit
  108874. this.stopAllAnimations();
  108875. this._radiusIsAnimating = true;
  108876. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  108877. if (animatable) {
  108878. this._animatables.push(animatable);
  108879. }
  108880. };
  108881. /**
  108882. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  108883. */
  108884. BouncingBehavior.prototype._clearAnimationLocks = function () {
  108885. this._radiusIsAnimating = false;
  108886. if (this._attachedCamera) {
  108887. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  108888. }
  108889. };
  108890. /**
  108891. * Stops and removes all animations that have been applied to the camera
  108892. */
  108893. BouncingBehavior.prototype.stopAllAnimations = function () {
  108894. if (this._attachedCamera) {
  108895. this._attachedCamera.animations = [];
  108896. }
  108897. while (this._animatables.length) {
  108898. this._animatables[0].onAnimationEnd = null;
  108899. this._animatables[0].stop();
  108900. this._animatables.shift();
  108901. }
  108902. };
  108903. /**
  108904. * The easing function used by animations
  108905. */
  108906. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  108907. /**
  108908. * The easing mode used by animations
  108909. */
  108910. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  108911. return BouncingBehavior;
  108912. }());
  108913. BABYLON.BouncingBehavior = BouncingBehavior;
  108914. })(BABYLON || (BABYLON = {}));
  108915. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  108916. var BABYLON;
  108917. (function (BABYLON) {
  108918. /**
  108919. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  108920. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  108921. */
  108922. var AutoRotationBehavior = /** @class */ (function () {
  108923. function AutoRotationBehavior() {
  108924. this._zoomStopsAnimation = false;
  108925. this._idleRotationSpeed = 0.05;
  108926. this._idleRotationWaitTime = 2000;
  108927. this._idleRotationSpinupTime = 2000;
  108928. this._isPointerDown = false;
  108929. this._lastFrameTime = null;
  108930. this._lastInteractionTime = -Infinity;
  108931. this._cameraRotationSpeed = 0;
  108932. this._lastFrameRadius = 0;
  108933. }
  108934. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  108935. /**
  108936. * Gets the name of the behavior.
  108937. */
  108938. get: function () {
  108939. return "AutoRotation";
  108940. },
  108941. enumerable: true,
  108942. configurable: true
  108943. });
  108944. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  108945. /**
  108946. * Gets the flag that indicates if user zooming should stop animation.
  108947. */
  108948. get: function () {
  108949. return this._zoomStopsAnimation;
  108950. },
  108951. /**
  108952. * Sets the flag that indicates if user zooming should stop animation.
  108953. */
  108954. set: function (flag) {
  108955. this._zoomStopsAnimation = flag;
  108956. },
  108957. enumerable: true,
  108958. configurable: true
  108959. });
  108960. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  108961. /**
  108962. * Gets the default speed at which the camera rotates around the model.
  108963. */
  108964. get: function () {
  108965. return this._idleRotationSpeed;
  108966. },
  108967. /**
  108968. * Sets the default speed at which the camera rotates around the model.
  108969. */
  108970. set: function (speed) {
  108971. this._idleRotationSpeed = speed;
  108972. },
  108973. enumerable: true,
  108974. configurable: true
  108975. });
  108976. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  108977. /**
  108978. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  108979. */
  108980. get: function () {
  108981. return this._idleRotationWaitTime;
  108982. },
  108983. /**
  108984. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  108985. */
  108986. set: function (time) {
  108987. this._idleRotationWaitTime = time;
  108988. },
  108989. enumerable: true,
  108990. configurable: true
  108991. });
  108992. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  108993. /**
  108994. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  108995. */
  108996. get: function () {
  108997. return this._idleRotationSpinupTime;
  108998. },
  108999. /**
  109000. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  109001. */
  109002. set: function (time) {
  109003. this._idleRotationSpinupTime = time;
  109004. },
  109005. enumerable: true,
  109006. configurable: true
  109007. });
  109008. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  109009. /**
  109010. * Gets a value indicating if the camera is currently rotating because of this behavior
  109011. */
  109012. get: function () {
  109013. return Math.abs(this._cameraRotationSpeed) > 0;
  109014. },
  109015. enumerable: true,
  109016. configurable: true
  109017. });
  109018. /**
  109019. * Initializes the behavior.
  109020. */
  109021. AutoRotationBehavior.prototype.init = function () {
  109022. // Do notihng
  109023. };
  109024. /**
  109025. * Attaches the behavior to its arc rotate camera.
  109026. * @param camera Defines the camera to attach the behavior to
  109027. */
  109028. AutoRotationBehavior.prototype.attach = function (camera) {
  109029. var _this = this;
  109030. this._attachedCamera = camera;
  109031. var scene = this._attachedCamera.getScene();
  109032. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  109033. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  109034. _this._isPointerDown = true;
  109035. return;
  109036. }
  109037. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  109038. _this._isPointerDown = false;
  109039. }
  109040. });
  109041. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  109042. var now = BABYLON.Tools.Now;
  109043. var dt = 0;
  109044. if (_this._lastFrameTime != null) {
  109045. dt = now - _this._lastFrameTime;
  109046. }
  109047. _this._lastFrameTime = now;
  109048. // Stop the animation if there is user interaction and the animation should stop for this interaction
  109049. _this._applyUserInteraction();
  109050. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  109051. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  109052. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  109053. // Step camera rotation by rotation speed
  109054. if (_this._attachedCamera) {
  109055. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  109056. }
  109057. });
  109058. };
  109059. /**
  109060. * Detaches the behavior from its current arc rotate camera.
  109061. */
  109062. AutoRotationBehavior.prototype.detach = function () {
  109063. if (!this._attachedCamera) {
  109064. return;
  109065. }
  109066. var scene = this._attachedCamera.getScene();
  109067. if (this._onPrePointerObservableObserver) {
  109068. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  109069. }
  109070. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  109071. this._attachedCamera = null;
  109072. };
  109073. /**
  109074. * Returns true if user is scrolling.
  109075. * @return true if user is scrolling.
  109076. */
  109077. AutoRotationBehavior.prototype._userIsZooming = function () {
  109078. if (!this._attachedCamera) {
  109079. return false;
  109080. }
  109081. return this._attachedCamera.inertialRadiusOffset !== 0;
  109082. };
  109083. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  109084. if (!this._attachedCamera) {
  109085. return false;
  109086. }
  109087. var zoomHasHitLimit = false;
  109088. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  109089. zoomHasHitLimit = true;
  109090. }
  109091. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  109092. this._lastFrameRadius = this._attachedCamera.radius;
  109093. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  109094. };
  109095. /**
  109096. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  109097. */
  109098. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  109099. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  109100. this._lastInteractionTime = BABYLON.Tools.Now;
  109101. }
  109102. };
  109103. // Tools
  109104. AutoRotationBehavior.prototype._userIsMoving = function () {
  109105. if (!this._attachedCamera) {
  109106. return false;
  109107. }
  109108. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  109109. this._attachedCamera.inertialBetaOffset !== 0 ||
  109110. this._attachedCamera.inertialRadiusOffset !== 0 ||
  109111. this._attachedCamera.inertialPanningX !== 0 ||
  109112. this._attachedCamera.inertialPanningY !== 0 ||
  109113. this._isPointerDown;
  109114. };
  109115. return AutoRotationBehavior;
  109116. }());
  109117. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  109118. })(BABYLON || (BABYLON = {}));
  109119. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  109120. var BABYLON;
  109121. (function (BABYLON) {
  109122. var NullEngineOptions = /** @class */ (function () {
  109123. function NullEngineOptions() {
  109124. this.renderWidth = 512;
  109125. this.renderHeight = 256;
  109126. this.textureSize = 512;
  109127. this.deterministicLockstep = false;
  109128. this.lockstepMaxSteps = 4;
  109129. }
  109130. return NullEngineOptions;
  109131. }());
  109132. BABYLON.NullEngineOptions = NullEngineOptions;
  109133. /**
  109134. * The null engine class provides support for headless version of babylon.js.
  109135. * This can be used in server side scenario or for testing purposes
  109136. */
  109137. var NullEngine = /** @class */ (function (_super) {
  109138. __extends(NullEngine, _super);
  109139. function NullEngine(options) {
  109140. if (options === void 0) { options = new NullEngineOptions(); }
  109141. var _this = _super.call(this, null) || this;
  109142. if (options.deterministicLockstep === undefined) {
  109143. options.deterministicLockstep = false;
  109144. }
  109145. if (options.lockstepMaxSteps === undefined) {
  109146. options.lockstepMaxSteps = 4;
  109147. }
  109148. _this._options = options;
  109149. // Init caps
  109150. // We consider we are on a webgl1 capable device
  109151. _this._caps = new BABYLON.EngineCapabilities();
  109152. _this._caps.maxTexturesImageUnits = 16;
  109153. _this._caps.maxVertexTextureImageUnits = 16;
  109154. _this._caps.maxTextureSize = 512;
  109155. _this._caps.maxCubemapTextureSize = 512;
  109156. _this._caps.maxRenderTextureSize = 512;
  109157. _this._caps.maxVertexAttribs = 16;
  109158. _this._caps.maxVaryingVectors = 16;
  109159. _this._caps.maxFragmentUniformVectors = 16;
  109160. _this._caps.maxVertexUniformVectors = 16;
  109161. // Extensions
  109162. _this._caps.standardDerivatives = false;
  109163. _this._caps.astc = null;
  109164. _this._caps.s3tc = null;
  109165. _this._caps.pvrtc = null;
  109166. _this._caps.etc1 = null;
  109167. _this._caps.etc2 = null;
  109168. _this._caps.textureAnisotropicFilterExtension = null;
  109169. _this._caps.maxAnisotropy = 0;
  109170. _this._caps.uintIndices = false;
  109171. _this._caps.fragmentDepthSupported = false;
  109172. _this._caps.highPrecisionShaderSupported = true;
  109173. _this._caps.colorBufferFloat = false;
  109174. _this._caps.textureFloat = false;
  109175. _this._caps.textureFloatLinearFiltering = false;
  109176. _this._caps.textureFloatRender = false;
  109177. _this._caps.textureHalfFloat = false;
  109178. _this._caps.textureHalfFloatLinearFiltering = false;
  109179. _this._caps.textureHalfFloatRender = false;
  109180. _this._caps.textureLOD = false;
  109181. _this._caps.drawBuffersExtension = false;
  109182. _this._caps.depthTextureExtension = false;
  109183. _this._caps.vertexArrayObject = false;
  109184. _this._caps.instancedArrays = false;
  109185. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  109186. // Wrappers
  109187. if (typeof URL === "undefined") {
  109188. URL = {
  109189. createObjectURL: function () { },
  109190. revokeObjectURL: function () { }
  109191. };
  109192. }
  109193. if (typeof Blob === "undefined") {
  109194. Blob = function () { };
  109195. }
  109196. return _this;
  109197. }
  109198. NullEngine.prototype.isDeterministicLockStep = function () {
  109199. return this._options.deterministicLockstep;
  109200. };
  109201. NullEngine.prototype.getLockstepMaxSteps = function () {
  109202. return this._options.lockstepMaxSteps;
  109203. };
  109204. NullEngine.prototype.getHardwareScalingLevel = function () {
  109205. return 1.0;
  109206. };
  109207. NullEngine.prototype.createVertexBuffer = function (vertices) {
  109208. return {
  109209. capacity: 0,
  109210. references: 1,
  109211. is32Bits: false
  109212. };
  109213. };
  109214. NullEngine.prototype.createIndexBuffer = function (indices) {
  109215. return {
  109216. capacity: 0,
  109217. references: 1,
  109218. is32Bits: false
  109219. };
  109220. };
  109221. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  109222. if (stencil === void 0) { stencil = false; }
  109223. };
  109224. NullEngine.prototype.getRenderWidth = function (useScreen) {
  109225. if (useScreen === void 0) { useScreen = false; }
  109226. if (!useScreen && this._currentRenderTarget) {
  109227. return this._currentRenderTarget.width;
  109228. }
  109229. return this._options.renderWidth;
  109230. };
  109231. NullEngine.prototype.getRenderHeight = function (useScreen) {
  109232. if (useScreen === void 0) { useScreen = false; }
  109233. if (!useScreen && this._currentRenderTarget) {
  109234. return this._currentRenderTarget.height;
  109235. }
  109236. return this._options.renderHeight;
  109237. };
  109238. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  109239. this._cachedViewport = viewport;
  109240. };
  109241. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  109242. return {
  109243. transformFeedback: null,
  109244. __SPECTOR_rebuildProgram: null
  109245. };
  109246. };
  109247. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  109248. return [];
  109249. };
  109250. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  109251. return [];
  109252. };
  109253. NullEngine.prototype.bindSamplers = function (effect) {
  109254. this._currentEffect = null;
  109255. };
  109256. NullEngine.prototype.enableEffect = function (effect) {
  109257. this._currentEffect = effect;
  109258. if (effect.onBind) {
  109259. effect.onBind(effect);
  109260. }
  109261. if (effect._onBindObservable) {
  109262. effect._onBindObservable.notifyObservers(effect);
  109263. }
  109264. };
  109265. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  109266. if (zOffset === void 0) { zOffset = 0; }
  109267. if (reverseSide === void 0) { reverseSide = false; }
  109268. };
  109269. NullEngine.prototype.setIntArray = function (uniform, array) {
  109270. };
  109271. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  109272. };
  109273. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  109274. };
  109275. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  109276. };
  109277. NullEngine.prototype.setFloatArray = function (uniform, array) {
  109278. };
  109279. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  109280. };
  109281. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  109282. };
  109283. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  109284. };
  109285. NullEngine.prototype.setArray = function (uniform, array) {
  109286. };
  109287. NullEngine.prototype.setArray2 = function (uniform, array) {
  109288. };
  109289. NullEngine.prototype.setArray3 = function (uniform, array) {
  109290. };
  109291. NullEngine.prototype.setArray4 = function (uniform, array) {
  109292. };
  109293. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  109294. };
  109295. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  109296. };
  109297. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  109298. };
  109299. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  109300. };
  109301. NullEngine.prototype.setFloat = function (uniform, value) {
  109302. };
  109303. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  109304. };
  109305. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  109306. };
  109307. NullEngine.prototype.setBool = function (uniform, bool) {
  109308. };
  109309. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  109310. };
  109311. NullEngine.prototype.setColor3 = function (uniform, color3) {
  109312. };
  109313. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  109314. };
  109315. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  109316. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  109317. if (this._alphaMode === mode) {
  109318. return;
  109319. }
  109320. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  109321. if (!noDepthWriteChange) {
  109322. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  109323. }
  109324. this._alphaMode = mode;
  109325. };
  109326. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  109327. };
  109328. NullEngine.prototype.wipeCaches = function (bruteForce) {
  109329. if (this.preventCacheWipeBetweenFrames) {
  109330. return;
  109331. }
  109332. this.resetTextureCache();
  109333. this._currentEffect = null;
  109334. if (bruteForce) {
  109335. this._currentProgram = null;
  109336. this._stencilState.reset();
  109337. this._depthCullingState.reset();
  109338. this._alphaState.reset();
  109339. }
  109340. this._cachedVertexBuffers = null;
  109341. this._cachedIndexBuffer = null;
  109342. this._cachedEffectForVertexBuffers = null;
  109343. };
  109344. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  109345. };
  109346. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  109347. };
  109348. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  109349. };
  109350. /** @hidden */
  109351. NullEngine.prototype._createTexture = function () {
  109352. return {};
  109353. };
  109354. /** @hidden */
  109355. NullEngine.prototype._releaseTexture = function (texture) {
  109356. };
  109357. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  109358. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109359. if (onLoad === void 0) { onLoad = null; }
  109360. if (onError === void 0) { onError = null; }
  109361. if (buffer === void 0) { buffer = null; }
  109362. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  109363. var url = String(urlArg);
  109364. texture.url = url;
  109365. texture.generateMipMaps = !noMipmap;
  109366. texture.samplingMode = samplingMode;
  109367. texture.invertY = invertY;
  109368. texture.baseWidth = this._options.textureSize;
  109369. texture.baseHeight = this._options.textureSize;
  109370. texture.width = this._options.textureSize;
  109371. texture.height = this._options.textureSize;
  109372. if (format) {
  109373. texture.format = format;
  109374. }
  109375. texture.isReady = true;
  109376. if (onLoad) {
  109377. onLoad();
  109378. }
  109379. this._internalTexturesCache.push(texture);
  109380. return texture;
  109381. };
  109382. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  109383. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  109384. if (options !== undefined && typeof options === "object") {
  109385. fullOptions.generateMipMaps = options.generateMipMaps;
  109386. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  109387. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  109388. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  109389. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  109390. }
  109391. else {
  109392. fullOptions.generateMipMaps = options;
  109393. fullOptions.generateDepthBuffer = true;
  109394. fullOptions.generateStencilBuffer = false;
  109395. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  109396. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  109397. }
  109398. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  109399. var width = size.width || size;
  109400. var height = size.height || size;
  109401. texture._depthStencilBuffer = {};
  109402. texture._framebuffer = {};
  109403. texture.baseWidth = width;
  109404. texture.baseHeight = height;
  109405. texture.width = width;
  109406. texture.height = height;
  109407. texture.isReady = true;
  109408. texture.samples = 1;
  109409. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  109410. texture.samplingMode = fullOptions.samplingMode;
  109411. texture.type = fullOptions.type;
  109412. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  109413. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  109414. this._internalTexturesCache.push(texture);
  109415. return texture;
  109416. };
  109417. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  109418. texture.samplingMode = samplingMode;
  109419. };
  109420. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  109421. if (this._currentRenderTarget) {
  109422. this.unBindFramebuffer(this._currentRenderTarget);
  109423. }
  109424. this._currentRenderTarget = texture;
  109425. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  109426. if (this._cachedViewport && !forceFullscreenViewport) {
  109427. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  109428. }
  109429. };
  109430. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  109431. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  109432. this._currentRenderTarget = null;
  109433. if (onBeforeUnbind) {
  109434. if (texture._MSAAFramebuffer) {
  109435. this._currentFramebuffer = texture._framebuffer;
  109436. }
  109437. onBeforeUnbind();
  109438. }
  109439. this._currentFramebuffer = null;
  109440. };
  109441. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  109442. var vbo = {
  109443. capacity: 1,
  109444. references: 1,
  109445. is32Bits: false
  109446. };
  109447. return vbo;
  109448. };
  109449. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  109450. if (premulAlpha === void 0) { premulAlpha = false; }
  109451. };
  109452. /**
  109453. * @hidden
  109454. * Get the current error code of the webGL context
  109455. * @returns the error code
  109456. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  109457. */
  109458. NullEngine.prototype.getError = function () {
  109459. return 0;
  109460. };
  109461. /** @hidden */
  109462. NullEngine.prototype._getUnpackAlignement = function () {
  109463. return 1;
  109464. };
  109465. /** @hidden */
  109466. NullEngine.prototype._unpackFlipY = function (value) {
  109467. };
  109468. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  109469. if (offset === void 0) { offset = 0; }
  109470. };
  109471. /**
  109472. * Updates a dynamic vertex buffer.
  109473. * @param vertexBuffer the vertex buffer to update
  109474. * @param data the data used to update the vertex buffer
  109475. * @param byteOffset the byte offset of the data (optional)
  109476. * @param byteLength the byte length of the data (optional)
  109477. */
  109478. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  109479. };
  109480. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  109481. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  109482. this._boundTexturesCache[this._activeChannel] = texture;
  109483. return true;
  109484. }
  109485. return false;
  109486. };
  109487. /** @hidden */
  109488. NullEngine.prototype._bindTexture = function (channel, texture) {
  109489. if (channel < 0) {
  109490. return;
  109491. }
  109492. this._bindTextureDirectly(0, texture);
  109493. };
  109494. /** @hidden */
  109495. NullEngine.prototype._releaseBuffer = function (buffer) {
  109496. buffer.references--;
  109497. if (buffer.references === 0) {
  109498. return true;
  109499. }
  109500. return false;
  109501. };
  109502. NullEngine.prototype.releaseEffects = function () {
  109503. };
  109504. NullEngine.prototype.displayLoadingUI = function () {
  109505. };
  109506. NullEngine.prototype.hideLoadingUI = function () {
  109507. };
  109508. /** @hidden */
  109509. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  109510. if (faceIndex === void 0) { faceIndex = 0; }
  109511. if (lod === void 0) { lod = 0; }
  109512. };
  109513. /** @hidden */
  109514. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  109515. if (faceIndex === void 0) { faceIndex = 0; }
  109516. if (lod === void 0) { lod = 0; }
  109517. };
  109518. /** @hidden */
  109519. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  109520. if (faceIndex === void 0) { faceIndex = 0; }
  109521. if (lod === void 0) { lod = 0; }
  109522. };
  109523. /** @hidden */
  109524. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  109525. if (faceIndex === void 0) { faceIndex = 0; }
  109526. if (lod === void 0) { lod = 0; }
  109527. };
  109528. return NullEngine;
  109529. }(BABYLON.Engine));
  109530. BABYLON.NullEngine = NullEngine;
  109531. })(BABYLON || (BABYLON = {}));
  109532. //# sourceMappingURL=babylon.nullEngine.js.map
  109533. var BABYLON;
  109534. (function (BABYLON) {
  109535. /**
  109536. * This class can be used to get instrumentation data from a Babylon engine
  109537. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  109538. */
  109539. var EngineInstrumentation = /** @class */ (function () {
  109540. /**
  109541. * Instantiates a new engine instrumentation.
  109542. * This class can be used to get instrumentation data from a Babylon engine
  109543. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  109544. * @param engine Defines the engine to instrument
  109545. */
  109546. function EngineInstrumentation(
  109547. /**
  109548. * Define the instrumented engine.
  109549. */
  109550. engine) {
  109551. this.engine = engine;
  109552. this._captureGPUFrameTime = false;
  109553. this._gpuFrameTime = new BABYLON.PerfCounter();
  109554. this._captureShaderCompilationTime = false;
  109555. this._shaderCompilationTime = new BABYLON.PerfCounter();
  109556. // Observers
  109557. this._onBeginFrameObserver = null;
  109558. this._onEndFrameObserver = null;
  109559. this._onBeforeShaderCompilationObserver = null;
  109560. this._onAfterShaderCompilationObserver = null;
  109561. }
  109562. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  109563. // Properties
  109564. /**
  109565. * Gets the perf counter used for GPU frame time
  109566. */
  109567. get: function () {
  109568. return this._gpuFrameTime;
  109569. },
  109570. enumerable: true,
  109571. configurable: true
  109572. });
  109573. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  109574. /**
  109575. * Gets the GPU frame time capture status
  109576. */
  109577. get: function () {
  109578. return this._captureGPUFrameTime;
  109579. },
  109580. /**
  109581. * Enable or disable the GPU frame time capture
  109582. */
  109583. set: function (value) {
  109584. var _this = this;
  109585. if (value === this._captureGPUFrameTime) {
  109586. return;
  109587. }
  109588. this._captureGPUFrameTime = value;
  109589. if (value) {
  109590. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  109591. if (!_this._gpuFrameTimeToken) {
  109592. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  109593. }
  109594. });
  109595. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  109596. if (!_this._gpuFrameTimeToken) {
  109597. return;
  109598. }
  109599. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  109600. if (time > -1) {
  109601. _this._gpuFrameTimeToken = null;
  109602. _this._gpuFrameTime.fetchNewFrame();
  109603. _this._gpuFrameTime.addCount(time, true);
  109604. }
  109605. });
  109606. }
  109607. else {
  109608. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  109609. this._onBeginFrameObserver = null;
  109610. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  109611. this._onEndFrameObserver = null;
  109612. }
  109613. },
  109614. enumerable: true,
  109615. configurable: true
  109616. });
  109617. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  109618. /**
  109619. * Gets the perf counter used for shader compilation time
  109620. */
  109621. get: function () {
  109622. return this._shaderCompilationTime;
  109623. },
  109624. enumerable: true,
  109625. configurable: true
  109626. });
  109627. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  109628. /**
  109629. * Gets the shader compilation time capture status
  109630. */
  109631. get: function () {
  109632. return this._captureShaderCompilationTime;
  109633. },
  109634. /**
  109635. * Enable or disable the shader compilation time capture
  109636. */
  109637. set: function (value) {
  109638. var _this = this;
  109639. if (value === this._captureShaderCompilationTime) {
  109640. return;
  109641. }
  109642. this._captureShaderCompilationTime = value;
  109643. if (value) {
  109644. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  109645. _this._shaderCompilationTime.fetchNewFrame();
  109646. _this._shaderCompilationTime.beginMonitoring();
  109647. });
  109648. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  109649. _this._shaderCompilationTime.endMonitoring();
  109650. });
  109651. }
  109652. else {
  109653. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  109654. this._onBeforeShaderCompilationObserver = null;
  109655. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  109656. this._onAfterShaderCompilationObserver = null;
  109657. }
  109658. },
  109659. enumerable: true,
  109660. configurable: true
  109661. });
  109662. /**
  109663. * Dispose and release associated resources.
  109664. */
  109665. EngineInstrumentation.prototype.dispose = function () {
  109666. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  109667. this._onBeginFrameObserver = null;
  109668. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  109669. this._onEndFrameObserver = null;
  109670. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  109671. this._onBeforeShaderCompilationObserver = null;
  109672. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  109673. this._onAfterShaderCompilationObserver = null;
  109674. this.engine = null;
  109675. };
  109676. return EngineInstrumentation;
  109677. }());
  109678. BABYLON.EngineInstrumentation = EngineInstrumentation;
  109679. })(BABYLON || (BABYLON = {}));
  109680. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  109681. var BABYLON;
  109682. (function (BABYLON) {
  109683. /**
  109684. * This class can be used to get instrumentation data from a Babylon engine
  109685. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  109686. */
  109687. var SceneInstrumentation = /** @class */ (function () {
  109688. /**
  109689. * Instantiates a new scene instrumentation.
  109690. * This class can be used to get instrumentation data from a Babylon engine
  109691. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  109692. * @param scene Defines the scene to instrument
  109693. */
  109694. function SceneInstrumentation(
  109695. /**
  109696. * Defines the scene to instrument
  109697. */
  109698. scene) {
  109699. var _this = this;
  109700. this.scene = scene;
  109701. this._captureActiveMeshesEvaluationTime = false;
  109702. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  109703. this._captureRenderTargetsRenderTime = false;
  109704. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  109705. this._captureFrameTime = false;
  109706. this._frameTime = new BABYLON.PerfCounter();
  109707. this._captureRenderTime = false;
  109708. this._renderTime = new BABYLON.PerfCounter();
  109709. this._captureInterFrameTime = false;
  109710. this._interFrameTime = new BABYLON.PerfCounter();
  109711. this._captureParticlesRenderTime = false;
  109712. this._particlesRenderTime = new BABYLON.PerfCounter();
  109713. this._captureSpritesRenderTime = false;
  109714. this._spritesRenderTime = new BABYLON.PerfCounter();
  109715. this._capturePhysicsTime = false;
  109716. this._physicsTime = new BABYLON.PerfCounter();
  109717. this._captureAnimationsTime = false;
  109718. this._animationsTime = new BABYLON.PerfCounter();
  109719. this._captureCameraRenderTime = false;
  109720. this._cameraRenderTime = new BABYLON.PerfCounter();
  109721. // Observers
  109722. this._onBeforeActiveMeshesEvaluationObserver = null;
  109723. this._onAfterActiveMeshesEvaluationObserver = null;
  109724. this._onBeforeRenderTargetsRenderObserver = null;
  109725. this._onAfterRenderTargetsRenderObserver = null;
  109726. this._onAfterRenderObserver = null;
  109727. this._onBeforeDrawPhaseObserver = null;
  109728. this._onAfterDrawPhaseObserver = null;
  109729. this._onBeforeAnimationsObserver = null;
  109730. this._onBeforeParticlesRenderingObserver = null;
  109731. this._onAfterParticlesRenderingObserver = null;
  109732. this._onBeforeSpritesRenderingObserver = null;
  109733. this._onAfterSpritesRenderingObserver = null;
  109734. this._onBeforePhysicsObserver = null;
  109735. this._onAfterPhysicsObserver = null;
  109736. this._onAfterAnimationsObserver = null;
  109737. this._onBeforeCameraRenderObserver = null;
  109738. this._onAfterCameraRenderObserver = null;
  109739. // Before render
  109740. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  109741. if (_this._captureActiveMeshesEvaluationTime) {
  109742. _this._activeMeshesEvaluationTime.fetchNewFrame();
  109743. }
  109744. if (_this._captureRenderTargetsRenderTime) {
  109745. _this._renderTargetsRenderTime.fetchNewFrame();
  109746. }
  109747. if (_this._captureFrameTime) {
  109748. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  109749. _this._frameTime.beginMonitoring();
  109750. }
  109751. if (_this._captureInterFrameTime) {
  109752. _this._interFrameTime.endMonitoring();
  109753. }
  109754. if (_this._captureParticlesRenderTime) {
  109755. _this._particlesRenderTime.fetchNewFrame();
  109756. }
  109757. if (_this._captureSpritesRenderTime) {
  109758. _this._spritesRenderTime.fetchNewFrame();
  109759. }
  109760. if (_this._captureAnimationsTime) {
  109761. _this._animationsTime.beginMonitoring();
  109762. }
  109763. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  109764. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  109765. });
  109766. // After render
  109767. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  109768. if (_this._captureFrameTime) {
  109769. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  109770. _this._frameTime.endMonitoring();
  109771. }
  109772. if (_this._captureRenderTime) {
  109773. _this._renderTime.endMonitoring(false);
  109774. }
  109775. if (_this._captureInterFrameTime) {
  109776. _this._interFrameTime.beginMonitoring();
  109777. }
  109778. });
  109779. }
  109780. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  109781. // Properties
  109782. /**
  109783. * Gets the perf counter used for active meshes evaluation time
  109784. */
  109785. get: function () {
  109786. return this._activeMeshesEvaluationTime;
  109787. },
  109788. enumerable: true,
  109789. configurable: true
  109790. });
  109791. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  109792. /**
  109793. * Gets the active meshes evaluation time capture status
  109794. */
  109795. get: function () {
  109796. return this._captureActiveMeshesEvaluationTime;
  109797. },
  109798. /**
  109799. * Enable or disable the active meshes evaluation time capture
  109800. */
  109801. set: function (value) {
  109802. var _this = this;
  109803. if (value === this._captureActiveMeshesEvaluationTime) {
  109804. return;
  109805. }
  109806. this._captureActiveMeshesEvaluationTime = value;
  109807. if (value) {
  109808. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  109809. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  109810. _this._activeMeshesEvaluationTime.beginMonitoring();
  109811. });
  109812. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  109813. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  109814. _this._activeMeshesEvaluationTime.endMonitoring();
  109815. });
  109816. }
  109817. else {
  109818. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  109819. this._onBeforeActiveMeshesEvaluationObserver = null;
  109820. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  109821. this._onAfterActiveMeshesEvaluationObserver = null;
  109822. }
  109823. },
  109824. enumerable: true,
  109825. configurable: true
  109826. });
  109827. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  109828. /**
  109829. * Gets the perf counter used for render targets render time
  109830. */
  109831. get: function () {
  109832. return this._renderTargetsRenderTime;
  109833. },
  109834. enumerable: true,
  109835. configurable: true
  109836. });
  109837. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  109838. /**
  109839. * Gets the render targets render time capture status
  109840. */
  109841. get: function () {
  109842. return this._captureRenderTargetsRenderTime;
  109843. },
  109844. /**
  109845. * Enable or disable the render targets render time capture
  109846. */
  109847. set: function (value) {
  109848. var _this = this;
  109849. if (value === this._captureRenderTargetsRenderTime) {
  109850. return;
  109851. }
  109852. this._captureRenderTargetsRenderTime = value;
  109853. if (value) {
  109854. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  109855. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  109856. _this._renderTargetsRenderTime.beginMonitoring();
  109857. });
  109858. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  109859. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  109860. _this._renderTargetsRenderTime.endMonitoring(false);
  109861. });
  109862. }
  109863. else {
  109864. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  109865. this._onBeforeRenderTargetsRenderObserver = null;
  109866. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  109867. this._onAfterRenderTargetsRenderObserver = null;
  109868. }
  109869. },
  109870. enumerable: true,
  109871. configurable: true
  109872. });
  109873. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  109874. /**
  109875. * Gets the perf counter used for particles render time
  109876. */
  109877. get: function () {
  109878. return this._particlesRenderTime;
  109879. },
  109880. enumerable: true,
  109881. configurable: true
  109882. });
  109883. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  109884. /**
  109885. * Gets the particles render time capture status
  109886. */
  109887. get: function () {
  109888. return this._captureParticlesRenderTime;
  109889. },
  109890. /**
  109891. * Enable or disable the particles render time capture
  109892. */
  109893. set: function (value) {
  109894. var _this = this;
  109895. if (value === this._captureParticlesRenderTime) {
  109896. return;
  109897. }
  109898. this._captureParticlesRenderTime = value;
  109899. if (value) {
  109900. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  109901. BABYLON.Tools.StartPerformanceCounter("Particles");
  109902. _this._particlesRenderTime.beginMonitoring();
  109903. });
  109904. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  109905. BABYLON.Tools.EndPerformanceCounter("Particles");
  109906. _this._particlesRenderTime.endMonitoring(false);
  109907. });
  109908. }
  109909. else {
  109910. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  109911. this._onBeforeParticlesRenderingObserver = null;
  109912. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  109913. this._onAfterParticlesRenderingObserver = null;
  109914. }
  109915. },
  109916. enumerable: true,
  109917. configurable: true
  109918. });
  109919. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  109920. /**
  109921. * Gets the perf counter used for sprites render time
  109922. */
  109923. get: function () {
  109924. return this._spritesRenderTime;
  109925. },
  109926. enumerable: true,
  109927. configurable: true
  109928. });
  109929. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  109930. /**
  109931. * Gets the sprites render time capture status
  109932. */
  109933. get: function () {
  109934. return this._captureSpritesRenderTime;
  109935. },
  109936. /**
  109937. * Enable or disable the sprites render time capture
  109938. */
  109939. set: function (value) {
  109940. var _this = this;
  109941. if (value === this._captureSpritesRenderTime) {
  109942. return;
  109943. }
  109944. this._captureSpritesRenderTime = value;
  109945. if (!this.scene.spriteManagers) {
  109946. return;
  109947. }
  109948. if (value) {
  109949. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  109950. BABYLON.Tools.StartPerformanceCounter("Sprites");
  109951. _this._spritesRenderTime.beginMonitoring();
  109952. });
  109953. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  109954. BABYLON.Tools.EndPerformanceCounter("Sprites");
  109955. _this._spritesRenderTime.endMonitoring(false);
  109956. });
  109957. }
  109958. else {
  109959. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  109960. this._onBeforeSpritesRenderingObserver = null;
  109961. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  109962. this._onAfterSpritesRenderingObserver = null;
  109963. }
  109964. },
  109965. enumerable: true,
  109966. configurable: true
  109967. });
  109968. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  109969. /**
  109970. * Gets the perf counter used for physics time
  109971. */
  109972. get: function () {
  109973. return this._physicsTime;
  109974. },
  109975. enumerable: true,
  109976. configurable: true
  109977. });
  109978. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  109979. /**
  109980. * Gets the physics time capture status
  109981. */
  109982. get: function () {
  109983. return this._capturePhysicsTime;
  109984. },
  109985. /**
  109986. * Enable or disable the physics time capture
  109987. */
  109988. set: function (value) {
  109989. var _this = this;
  109990. if (value === this._capturePhysicsTime) {
  109991. return;
  109992. }
  109993. if (!this.scene.onBeforePhysicsObservable) {
  109994. return;
  109995. }
  109996. this._capturePhysicsTime = value;
  109997. if (value) {
  109998. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  109999. BABYLON.Tools.StartPerformanceCounter("Physics");
  110000. _this._physicsTime.beginMonitoring();
  110001. });
  110002. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  110003. BABYLON.Tools.EndPerformanceCounter("Physics");
  110004. _this._physicsTime.endMonitoring();
  110005. });
  110006. }
  110007. else {
  110008. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  110009. this._onBeforePhysicsObserver = null;
  110010. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  110011. this._onAfterPhysicsObserver = null;
  110012. }
  110013. },
  110014. enumerable: true,
  110015. configurable: true
  110016. });
  110017. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  110018. /**
  110019. * Gets the perf counter used for animations time
  110020. */
  110021. get: function () {
  110022. return this._animationsTime;
  110023. },
  110024. enumerable: true,
  110025. configurable: true
  110026. });
  110027. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  110028. /**
  110029. * Gets the animations time capture status
  110030. */
  110031. get: function () {
  110032. return this._captureAnimationsTime;
  110033. },
  110034. /**
  110035. * Enable or disable the animations time capture
  110036. */
  110037. set: function (value) {
  110038. var _this = this;
  110039. if (value === this._captureAnimationsTime) {
  110040. return;
  110041. }
  110042. this._captureAnimationsTime = value;
  110043. if (value) {
  110044. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  110045. _this._animationsTime.endMonitoring();
  110046. });
  110047. }
  110048. else {
  110049. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  110050. this._onAfterAnimationsObserver = null;
  110051. }
  110052. },
  110053. enumerable: true,
  110054. configurable: true
  110055. });
  110056. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  110057. /**
  110058. * Gets the perf counter used for frame time capture
  110059. */
  110060. get: function () {
  110061. return this._frameTime;
  110062. },
  110063. enumerable: true,
  110064. configurable: true
  110065. });
  110066. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  110067. /**
  110068. * Gets the frame time capture status
  110069. */
  110070. get: function () {
  110071. return this._captureFrameTime;
  110072. },
  110073. /**
  110074. * Enable or disable the frame time capture
  110075. */
  110076. set: function (value) {
  110077. this._captureFrameTime = value;
  110078. },
  110079. enumerable: true,
  110080. configurable: true
  110081. });
  110082. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  110083. /**
  110084. * Gets the perf counter used for inter-frames time capture
  110085. */
  110086. get: function () {
  110087. return this._interFrameTime;
  110088. },
  110089. enumerable: true,
  110090. configurable: true
  110091. });
  110092. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  110093. /**
  110094. * Gets the inter-frames time capture status
  110095. */
  110096. get: function () {
  110097. return this._captureInterFrameTime;
  110098. },
  110099. /**
  110100. * Enable or disable the inter-frames time capture
  110101. */
  110102. set: function (value) {
  110103. this._captureInterFrameTime = value;
  110104. },
  110105. enumerable: true,
  110106. configurable: true
  110107. });
  110108. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  110109. /**
  110110. * Gets the perf counter used for render time capture
  110111. */
  110112. get: function () {
  110113. return this._renderTime;
  110114. },
  110115. enumerable: true,
  110116. configurable: true
  110117. });
  110118. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  110119. /**
  110120. * Gets the render time capture status
  110121. */
  110122. get: function () {
  110123. return this._captureRenderTime;
  110124. },
  110125. /**
  110126. * Enable or disable the render time capture
  110127. */
  110128. set: function (value) {
  110129. var _this = this;
  110130. if (value === this._captureRenderTime) {
  110131. return;
  110132. }
  110133. this._captureRenderTime = value;
  110134. if (value) {
  110135. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  110136. _this._renderTime.beginMonitoring();
  110137. BABYLON.Tools.StartPerformanceCounter("Main render");
  110138. });
  110139. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  110140. _this._renderTime.endMonitoring(false);
  110141. BABYLON.Tools.EndPerformanceCounter("Main render");
  110142. });
  110143. }
  110144. else {
  110145. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  110146. this._onBeforeDrawPhaseObserver = null;
  110147. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  110148. this._onAfterDrawPhaseObserver = null;
  110149. }
  110150. },
  110151. enumerable: true,
  110152. configurable: true
  110153. });
  110154. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  110155. /**
  110156. * Gets the perf counter used for camera render time capture
  110157. */
  110158. get: function () {
  110159. return this._cameraRenderTime;
  110160. },
  110161. enumerable: true,
  110162. configurable: true
  110163. });
  110164. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  110165. /**
  110166. * Gets the camera render time capture status
  110167. */
  110168. get: function () {
  110169. return this._captureCameraRenderTime;
  110170. },
  110171. /**
  110172. * Enable or disable the camera render time capture
  110173. */
  110174. set: function (value) {
  110175. var _this = this;
  110176. if (value === this._captureCameraRenderTime) {
  110177. return;
  110178. }
  110179. this._captureCameraRenderTime = value;
  110180. if (value) {
  110181. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  110182. _this._cameraRenderTime.beginMonitoring();
  110183. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  110184. });
  110185. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  110186. _this._cameraRenderTime.endMonitoring(false);
  110187. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  110188. });
  110189. }
  110190. else {
  110191. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  110192. this._onBeforeCameraRenderObserver = null;
  110193. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  110194. this._onAfterCameraRenderObserver = null;
  110195. }
  110196. },
  110197. enumerable: true,
  110198. configurable: true
  110199. });
  110200. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  110201. /**
  110202. * Gets the perf counter used for draw calls
  110203. */
  110204. get: function () {
  110205. return this.scene.getEngine()._drawCalls;
  110206. },
  110207. enumerable: true,
  110208. configurable: true
  110209. });
  110210. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  110211. /**
  110212. * Gets the perf counter used for texture collisions
  110213. */
  110214. get: function () {
  110215. return this.scene.getEngine()._textureCollisions;
  110216. },
  110217. enumerable: true,
  110218. configurable: true
  110219. });
  110220. /**
  110221. * Dispose and release associated resources.
  110222. */
  110223. SceneInstrumentation.prototype.dispose = function () {
  110224. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  110225. this._onAfterRenderObserver = null;
  110226. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  110227. this._onBeforeActiveMeshesEvaluationObserver = null;
  110228. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  110229. this._onAfterActiveMeshesEvaluationObserver = null;
  110230. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  110231. this._onBeforeRenderTargetsRenderObserver = null;
  110232. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  110233. this._onAfterRenderTargetsRenderObserver = null;
  110234. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  110235. this._onBeforeAnimationsObserver = null;
  110236. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  110237. this._onBeforeParticlesRenderingObserver = null;
  110238. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  110239. this._onAfterParticlesRenderingObserver = null;
  110240. if (this._onBeforeSpritesRenderingObserver) {
  110241. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  110242. this._onBeforeSpritesRenderingObserver = null;
  110243. }
  110244. if (this._onAfterSpritesRenderingObserver) {
  110245. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  110246. this._onAfterSpritesRenderingObserver = null;
  110247. }
  110248. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  110249. this._onBeforeDrawPhaseObserver = null;
  110250. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  110251. this._onAfterDrawPhaseObserver = null;
  110252. if (this._onBeforePhysicsObserver) {
  110253. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  110254. this._onBeforePhysicsObserver = null;
  110255. }
  110256. if (this._onAfterPhysicsObserver) {
  110257. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  110258. this._onAfterPhysicsObserver = null;
  110259. }
  110260. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  110261. this._onAfterAnimationsObserver = null;
  110262. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  110263. this._onBeforeCameraRenderObserver = null;
  110264. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  110265. this._onAfterCameraRenderObserver = null;
  110266. this.scene = null;
  110267. };
  110268. return SceneInstrumentation;
  110269. }());
  110270. BABYLON.SceneInstrumentation = SceneInstrumentation;
  110271. })(BABYLON || (BABYLON = {}));
  110272. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  110273. var BABYLON;
  110274. (function (BABYLON) {
  110275. /**
  110276. * @hidden
  110277. **/
  110278. var _TimeToken = /** @class */ (function () {
  110279. function _TimeToken() {
  110280. this._timeElapsedQueryEnded = false;
  110281. }
  110282. return _TimeToken;
  110283. }());
  110284. BABYLON._TimeToken = _TimeToken;
  110285. })(BABYLON || (BABYLON = {}));
  110286. //# sourceMappingURL=babylon.timeToken.js.map
  110287. var BABYLON;
  110288. (function (BABYLON) {
  110289. /**
  110290. * Background material defines definition.
  110291. * @hidden Mainly internal Use
  110292. */
  110293. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  110294. __extends(BackgroundMaterialDefines, _super);
  110295. /**
  110296. * Constructor of the defines.
  110297. */
  110298. function BackgroundMaterialDefines() {
  110299. var _this = _super.call(this) || this;
  110300. /**
  110301. * True if the diffuse texture is in use.
  110302. */
  110303. _this.DIFFUSE = false;
  110304. /**
  110305. * The direct UV channel to use.
  110306. */
  110307. _this.DIFFUSEDIRECTUV = 0;
  110308. /**
  110309. * True if the diffuse texture is in gamma space.
  110310. */
  110311. _this.GAMMADIFFUSE = false;
  110312. /**
  110313. * True if the diffuse texture has opacity in the alpha channel.
  110314. */
  110315. _this.DIFFUSEHASALPHA = false;
  110316. /**
  110317. * True if you want the material to fade to transparent at grazing angle.
  110318. */
  110319. _this.OPACITYFRESNEL = false;
  110320. /**
  110321. * True if an extra blur needs to be added in the reflection.
  110322. */
  110323. _this.REFLECTIONBLUR = false;
  110324. /**
  110325. * True if you want the material to fade to reflection at grazing angle.
  110326. */
  110327. _this.REFLECTIONFRESNEL = false;
  110328. /**
  110329. * True if you want the material to falloff as far as you move away from the scene center.
  110330. */
  110331. _this.REFLECTIONFALLOFF = false;
  110332. /**
  110333. * False if the current Webgl implementation does not support the texture lod extension.
  110334. */
  110335. _this.TEXTURELODSUPPORT = false;
  110336. /**
  110337. * True to ensure the data are premultiplied.
  110338. */
  110339. _this.PREMULTIPLYALPHA = false;
  110340. /**
  110341. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  110342. */
  110343. _this.USERGBCOLOR = false;
  110344. /**
  110345. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  110346. * stays aligned with the desired configuration.
  110347. */
  110348. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  110349. /**
  110350. * True to add noise in order to reduce the banding effect.
  110351. */
  110352. _this.NOISE = false;
  110353. /**
  110354. * is the reflection texture in BGR color scheme?
  110355. * Mainly used to solve a bug in ios10 video tag
  110356. */
  110357. _this.REFLECTIONBGR = false;
  110358. _this.IMAGEPROCESSING = false;
  110359. _this.VIGNETTE = false;
  110360. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  110361. _this.VIGNETTEBLENDMODEOPAQUE = false;
  110362. _this.TONEMAPPING = false;
  110363. _this.TONEMAPPING_ACES = false;
  110364. _this.CONTRAST = false;
  110365. _this.COLORCURVES = false;
  110366. _this.COLORGRADING = false;
  110367. _this.COLORGRADING3D = false;
  110368. _this.SAMPLER3DGREENDEPTH = false;
  110369. _this.SAMPLER3DBGRMAP = false;
  110370. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  110371. _this.EXPOSURE = false;
  110372. // Reflection.
  110373. _this.REFLECTION = false;
  110374. _this.REFLECTIONMAP_3D = false;
  110375. _this.REFLECTIONMAP_SPHERICAL = false;
  110376. _this.REFLECTIONMAP_PLANAR = false;
  110377. _this.REFLECTIONMAP_CUBIC = false;
  110378. _this.REFLECTIONMAP_PROJECTION = false;
  110379. _this.REFLECTIONMAP_SKYBOX = false;
  110380. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  110381. _this.REFLECTIONMAP_EXPLICIT = false;
  110382. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  110383. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  110384. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  110385. _this.INVERTCUBICMAP = false;
  110386. _this.REFLECTIONMAP_OPPOSITEZ = false;
  110387. _this.LODINREFLECTIONALPHA = false;
  110388. _this.GAMMAREFLECTION = false;
  110389. _this.RGBDREFLECTION = false;
  110390. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  110391. // Default BJS.
  110392. _this.MAINUV1 = false;
  110393. _this.MAINUV2 = false;
  110394. _this.UV1 = false;
  110395. _this.UV2 = false;
  110396. _this.CLIPPLANE = false;
  110397. _this.CLIPPLANE2 = false;
  110398. _this.CLIPPLANE3 = false;
  110399. _this.CLIPPLANE4 = false;
  110400. _this.POINTSIZE = false;
  110401. _this.FOG = false;
  110402. _this.NORMAL = false;
  110403. _this.NUM_BONE_INFLUENCERS = 0;
  110404. _this.BonesPerMesh = 0;
  110405. _this.INSTANCES = false;
  110406. _this.SHADOWFLOAT = false;
  110407. _this.rebuild();
  110408. return _this;
  110409. }
  110410. return BackgroundMaterialDefines;
  110411. }(BABYLON.MaterialDefines));
  110412. /**
  110413. * Background material used to create an efficient environement around your scene.
  110414. */
  110415. var BackgroundMaterial = /** @class */ (function (_super) {
  110416. __extends(BackgroundMaterial, _super);
  110417. /**
  110418. * Instantiates a Background Material in the given scene
  110419. * @param name The friendly name of the material
  110420. * @param scene The scene to add the material to
  110421. */
  110422. function BackgroundMaterial(name, scene) {
  110423. var _this = _super.call(this, name, scene) || this;
  110424. /**
  110425. * Key light Color (multiply against the environement texture)
  110426. */
  110427. _this.primaryColor = BABYLON.Color3.White();
  110428. _this._primaryColorShadowLevel = 0;
  110429. _this._primaryColorHighlightLevel = 0;
  110430. /**
  110431. * Reflection Texture used in the material.
  110432. * Should be author in a specific way for the best result (refer to the documentation).
  110433. */
  110434. _this.reflectionTexture = null;
  110435. /**
  110436. * Reflection Texture level of blur.
  110437. *
  110438. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  110439. * texture twice.
  110440. */
  110441. _this.reflectionBlur = 0;
  110442. /**
  110443. * Diffuse Texture used in the material.
  110444. * Should be author in a specific way for the best result (refer to the documentation).
  110445. */
  110446. _this.diffuseTexture = null;
  110447. _this._shadowLights = null;
  110448. /**
  110449. * Specify the list of lights casting shadow on the material.
  110450. * All scene shadow lights will be included if null.
  110451. */
  110452. _this.shadowLights = null;
  110453. /**
  110454. * Helps adjusting the shadow to a softer level if required.
  110455. * 0 means black shadows and 1 means no shadows.
  110456. */
  110457. _this.shadowLevel = 0;
  110458. /**
  110459. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  110460. * It is usually zero but might be interesting to modify according to your setup.
  110461. */
  110462. _this.sceneCenter = BABYLON.Vector3.Zero();
  110463. /**
  110464. * This helps specifying that the material is falling off to the sky box at grazing angle.
  110465. * This helps ensuring a nice transition when the camera goes under the ground.
  110466. */
  110467. _this.opacityFresnel = true;
  110468. /**
  110469. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  110470. * This helps adding a mirror texture on the ground.
  110471. */
  110472. _this.reflectionFresnel = false;
  110473. /**
  110474. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  110475. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  110476. */
  110477. _this.reflectionFalloffDistance = 0.0;
  110478. /**
  110479. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  110480. */
  110481. _this.reflectionAmount = 1.0;
  110482. /**
  110483. * This specifies the weight of the reflection at grazing angle.
  110484. */
  110485. _this.reflectionReflectance0 = 0.05;
  110486. /**
  110487. * This specifies the weight of the reflection at a perpendicular point of view.
  110488. */
  110489. _this.reflectionReflectance90 = 0.5;
  110490. /**
  110491. * Helps to directly use the maps channels instead of their level.
  110492. */
  110493. _this.useRGBColor = true;
  110494. /**
  110495. * This helps reducing the banding effect that could occur on the background.
  110496. */
  110497. _this.enableNoise = false;
  110498. _this._fovMultiplier = 1.0;
  110499. /**
  110500. * Enable the FOV adjustment feature controlled by fovMultiplier.
  110501. */
  110502. _this.useEquirectangularFOV = false;
  110503. _this._maxSimultaneousLights = 4;
  110504. /**
  110505. * Number of Simultaneous lights allowed on the material.
  110506. */
  110507. _this.maxSimultaneousLights = 4;
  110508. /**
  110509. * Keep track of the image processing observer to allow dispose and replace.
  110510. */
  110511. _this._imageProcessingObserver = null;
  110512. /**
  110513. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  110514. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  110515. */
  110516. _this.switchToBGR = false;
  110517. // Temp values kept as cache in the material.
  110518. _this._renderTargets = new BABYLON.SmartArray(16);
  110519. _this._reflectionControls = BABYLON.Vector4.Zero();
  110520. _this._white = BABYLON.Color3.White();
  110521. _this._primaryShadowColor = BABYLON.Color3.Black();
  110522. _this._primaryHighlightColor = BABYLON.Color3.Black();
  110523. // Setup the default processing configuration to the scene.
  110524. _this._attachImageProcessingConfiguration(null);
  110525. _this.getRenderTargetTextures = function () {
  110526. _this._renderTargets.reset();
  110527. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  110528. _this._renderTargets.push(_this._diffuseTexture);
  110529. }
  110530. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  110531. _this._renderTargets.push(_this._reflectionTexture);
  110532. }
  110533. return _this._renderTargets;
  110534. };
  110535. return _this;
  110536. }
  110537. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  110538. /**
  110539. * Experimental Internal Use Only.
  110540. *
  110541. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  110542. * This acts as a helper to set the primary color to a more "human friendly" value.
  110543. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  110544. * output color as close as possible from the chosen value.
  110545. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  110546. * part of lighting setup.)
  110547. */
  110548. get: function () {
  110549. return this.__perceptualColor;
  110550. },
  110551. set: function (value) {
  110552. this.__perceptualColor = value;
  110553. this._computePrimaryColorFromPerceptualColor();
  110554. this._markAllSubMeshesAsLightsDirty();
  110555. },
  110556. enumerable: true,
  110557. configurable: true
  110558. });
  110559. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  110560. /**
  110561. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  110562. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  110563. */
  110564. get: function () {
  110565. return this._primaryColorShadowLevel;
  110566. },
  110567. set: function (value) {
  110568. this._primaryColorShadowLevel = value;
  110569. this._computePrimaryColors();
  110570. this._markAllSubMeshesAsLightsDirty();
  110571. },
  110572. enumerable: true,
  110573. configurable: true
  110574. });
  110575. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  110576. /**
  110577. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  110578. * The primary color is used at the level chosen to define what the white area would look.
  110579. */
  110580. get: function () {
  110581. return this._primaryColorHighlightLevel;
  110582. },
  110583. set: function (value) {
  110584. this._primaryColorHighlightLevel = value;
  110585. this._computePrimaryColors();
  110586. this._markAllSubMeshesAsLightsDirty();
  110587. },
  110588. enumerable: true,
  110589. configurable: true
  110590. });
  110591. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  110592. /**
  110593. * Sets the reflection reflectance fresnel values according to the default standard
  110594. * empirically know to work well :-)
  110595. */
  110596. set: function (value) {
  110597. var reflectionWeight = value;
  110598. if (reflectionWeight < 0.5) {
  110599. reflectionWeight = reflectionWeight * 2.0;
  110600. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  110601. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  110602. }
  110603. else {
  110604. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  110605. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  110606. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  110607. }
  110608. },
  110609. enumerable: true,
  110610. configurable: true
  110611. });
  110612. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  110613. /**
  110614. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  110615. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  110616. * Recommended to be keep at 1.0 except for special cases.
  110617. */
  110618. get: function () {
  110619. return this._fovMultiplier;
  110620. },
  110621. set: function (value) {
  110622. if (isNaN(value)) {
  110623. value = 1.0;
  110624. }
  110625. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  110626. },
  110627. enumerable: true,
  110628. configurable: true
  110629. });
  110630. /**
  110631. * Attaches a new image processing configuration to the PBR Material.
  110632. * @param configuration (if null the scene configuration will be use)
  110633. */
  110634. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  110635. var _this = this;
  110636. if (configuration === this._imageProcessingConfiguration) {
  110637. return;
  110638. }
  110639. // Detaches observer.
  110640. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  110641. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  110642. }
  110643. // Pick the scene configuration if needed.
  110644. if (!configuration) {
  110645. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  110646. }
  110647. else {
  110648. this._imageProcessingConfiguration = configuration;
  110649. }
  110650. // Attaches observer.
  110651. if (this._imageProcessingConfiguration) {
  110652. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  110653. _this._computePrimaryColorFromPerceptualColor();
  110654. _this._markAllSubMeshesAsImageProcessingDirty();
  110655. });
  110656. }
  110657. };
  110658. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  110659. /**
  110660. * Gets the image processing configuration used either in this material.
  110661. */
  110662. get: function () {
  110663. return this._imageProcessingConfiguration;
  110664. },
  110665. /**
  110666. * Sets the Default image processing configuration used either in the this material.
  110667. *
  110668. * If sets to null, the scene one is in use.
  110669. */
  110670. set: function (value) {
  110671. this._attachImageProcessingConfiguration(value);
  110672. // Ensure the effect will be rebuilt.
  110673. this._markAllSubMeshesAsTexturesDirty();
  110674. },
  110675. enumerable: true,
  110676. configurable: true
  110677. });
  110678. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  110679. /**
  110680. * Gets wether the color curves effect is enabled.
  110681. */
  110682. get: function () {
  110683. return this.imageProcessingConfiguration.colorCurvesEnabled;
  110684. },
  110685. /**
  110686. * Sets wether the color curves effect is enabled.
  110687. */
  110688. set: function (value) {
  110689. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  110690. },
  110691. enumerable: true,
  110692. configurable: true
  110693. });
  110694. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  110695. /**
  110696. * Gets wether the color grading effect is enabled.
  110697. */
  110698. get: function () {
  110699. return this.imageProcessingConfiguration.colorGradingEnabled;
  110700. },
  110701. /**
  110702. * Gets wether the color grading effect is enabled.
  110703. */
  110704. set: function (value) {
  110705. this.imageProcessingConfiguration.colorGradingEnabled = value;
  110706. },
  110707. enumerable: true,
  110708. configurable: true
  110709. });
  110710. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  110711. /**
  110712. * Gets wether tonemapping is enabled or not.
  110713. */
  110714. get: function () {
  110715. return this._imageProcessingConfiguration.toneMappingEnabled;
  110716. },
  110717. /**
  110718. * Sets wether tonemapping is enabled or not
  110719. */
  110720. set: function (value) {
  110721. this._imageProcessingConfiguration.toneMappingEnabled = value;
  110722. },
  110723. enumerable: true,
  110724. configurable: true
  110725. });
  110726. ;
  110727. ;
  110728. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  110729. /**
  110730. * The camera exposure used on this material.
  110731. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  110732. * This corresponds to a photographic exposure.
  110733. */
  110734. get: function () {
  110735. return this._imageProcessingConfiguration.exposure;
  110736. },
  110737. /**
  110738. * The camera exposure used on this material.
  110739. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  110740. * This corresponds to a photographic exposure.
  110741. */
  110742. set: function (value) {
  110743. this._imageProcessingConfiguration.exposure = value;
  110744. },
  110745. enumerable: true,
  110746. configurable: true
  110747. });
  110748. ;
  110749. ;
  110750. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  110751. /**
  110752. * Gets The camera contrast used on this material.
  110753. */
  110754. get: function () {
  110755. return this._imageProcessingConfiguration.contrast;
  110756. },
  110757. /**
  110758. * Sets The camera contrast used on this material.
  110759. */
  110760. set: function (value) {
  110761. this._imageProcessingConfiguration.contrast = value;
  110762. },
  110763. enumerable: true,
  110764. configurable: true
  110765. });
  110766. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  110767. /**
  110768. * Gets the Color Grading 2D Lookup Texture.
  110769. */
  110770. get: function () {
  110771. return this._imageProcessingConfiguration.colorGradingTexture;
  110772. },
  110773. /**
  110774. * Sets the Color Grading 2D Lookup Texture.
  110775. */
  110776. set: function (value) {
  110777. this.imageProcessingConfiguration.colorGradingTexture = value;
  110778. },
  110779. enumerable: true,
  110780. configurable: true
  110781. });
  110782. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  110783. /**
  110784. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  110785. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  110786. * 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;
  110787. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  110788. */
  110789. get: function () {
  110790. return this.imageProcessingConfiguration.colorCurves;
  110791. },
  110792. /**
  110793. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  110794. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  110795. * 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;
  110796. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  110797. */
  110798. set: function (value) {
  110799. this.imageProcessingConfiguration.colorCurves = value;
  110800. },
  110801. enumerable: true,
  110802. configurable: true
  110803. });
  110804. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  110805. /**
  110806. * Gets a boolean indicating that current material needs to register RTT
  110807. */
  110808. get: function () {
  110809. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  110810. return true;
  110811. }
  110812. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  110813. return true;
  110814. }
  110815. return false;
  110816. },
  110817. enumerable: true,
  110818. configurable: true
  110819. });
  110820. /**
  110821. * The entire material has been created in order to prevent overdraw.
  110822. * @returns false
  110823. */
  110824. BackgroundMaterial.prototype.needAlphaTesting = function () {
  110825. return true;
  110826. };
  110827. /**
  110828. * The entire material has been created in order to prevent overdraw.
  110829. * @returns true if blending is enable
  110830. */
  110831. BackgroundMaterial.prototype.needAlphaBlending = function () {
  110832. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  110833. };
  110834. /**
  110835. * Checks wether the material is ready to be rendered for a given mesh.
  110836. * @param mesh The mesh to render
  110837. * @param subMesh The submesh to check against
  110838. * @param useInstances Specify wether or not the material is used with instances
  110839. * @returns true if all the dependencies are ready (Textures, Effects...)
  110840. */
  110841. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  110842. var _this = this;
  110843. if (useInstances === void 0) { useInstances = false; }
  110844. if (subMesh.effect && this.isFrozen) {
  110845. if (this._wasPreviouslyReady) {
  110846. return true;
  110847. }
  110848. }
  110849. if (!subMesh._materialDefines) {
  110850. subMesh._materialDefines = new BackgroundMaterialDefines();
  110851. }
  110852. var scene = this.getScene();
  110853. var defines = subMesh._materialDefines;
  110854. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  110855. if (defines._renderId === scene.getRenderId()) {
  110856. return true;
  110857. }
  110858. }
  110859. var engine = scene.getEngine();
  110860. // Lights
  110861. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  110862. defines._needNormals = true;
  110863. // Textures
  110864. if (defines._areTexturesDirty) {
  110865. defines._needUVs = false;
  110866. if (scene.texturesEnabled) {
  110867. if (scene.getEngine().getCaps().textureLOD) {
  110868. defines.TEXTURELODSUPPORT = true;
  110869. }
  110870. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  110871. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  110872. return false;
  110873. }
  110874. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  110875. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  110876. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  110877. defines.OPACITYFRESNEL = this._opacityFresnel;
  110878. }
  110879. else {
  110880. defines.DIFFUSE = false;
  110881. defines.DIFFUSEHASALPHA = false;
  110882. defines.GAMMADIFFUSE = false;
  110883. defines.OPACITYFRESNEL = false;
  110884. }
  110885. var reflectionTexture = this._reflectionTexture;
  110886. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  110887. if (!reflectionTexture.isReadyOrNotBlocking()) {
  110888. return false;
  110889. }
  110890. defines.REFLECTION = true;
  110891. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  110892. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  110893. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  110894. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  110895. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  110896. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  110897. defines.REFLECTIONBGR = this.switchToBGR;
  110898. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  110899. defines.INVERTCUBICMAP = true;
  110900. }
  110901. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  110902. switch (reflectionTexture.coordinatesMode) {
  110903. case BABYLON.Texture.EXPLICIT_MODE:
  110904. defines.REFLECTIONMAP_EXPLICIT = true;
  110905. break;
  110906. case BABYLON.Texture.PLANAR_MODE:
  110907. defines.REFLECTIONMAP_PLANAR = true;
  110908. break;
  110909. case BABYLON.Texture.PROJECTION_MODE:
  110910. defines.REFLECTIONMAP_PROJECTION = true;
  110911. break;
  110912. case BABYLON.Texture.SKYBOX_MODE:
  110913. defines.REFLECTIONMAP_SKYBOX = true;
  110914. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  110915. break;
  110916. case BABYLON.Texture.SPHERICAL_MODE:
  110917. defines.REFLECTIONMAP_SPHERICAL = true;
  110918. break;
  110919. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  110920. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  110921. break;
  110922. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  110923. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  110924. break;
  110925. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  110926. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  110927. break;
  110928. case BABYLON.Texture.CUBIC_MODE:
  110929. case BABYLON.Texture.INVCUBIC_MODE:
  110930. default:
  110931. defines.REFLECTIONMAP_CUBIC = true;
  110932. break;
  110933. }
  110934. if (this.reflectionFresnel) {
  110935. defines.REFLECTIONFRESNEL = true;
  110936. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  110937. this._reflectionControls.x = this.reflectionAmount;
  110938. this._reflectionControls.y = this.reflectionReflectance0;
  110939. this._reflectionControls.z = this.reflectionReflectance90;
  110940. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  110941. }
  110942. else {
  110943. defines.REFLECTIONFRESNEL = false;
  110944. defines.REFLECTIONFALLOFF = false;
  110945. }
  110946. }
  110947. else {
  110948. defines.REFLECTION = false;
  110949. defines.REFLECTIONFRESNEL = false;
  110950. defines.REFLECTIONFALLOFF = false;
  110951. defines.REFLECTIONBLUR = false;
  110952. defines.REFLECTIONMAP_3D = false;
  110953. defines.REFLECTIONMAP_SPHERICAL = false;
  110954. defines.REFLECTIONMAP_PLANAR = false;
  110955. defines.REFLECTIONMAP_CUBIC = false;
  110956. defines.REFLECTIONMAP_PROJECTION = false;
  110957. defines.REFLECTIONMAP_SKYBOX = false;
  110958. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  110959. defines.REFLECTIONMAP_EXPLICIT = false;
  110960. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  110961. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  110962. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  110963. defines.INVERTCUBICMAP = false;
  110964. defines.REFLECTIONMAP_OPPOSITEZ = false;
  110965. defines.LODINREFLECTIONALPHA = false;
  110966. defines.GAMMAREFLECTION = false;
  110967. defines.RGBDREFLECTION = false;
  110968. }
  110969. }
  110970. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  110971. defines.USERGBCOLOR = this._useRGBColor;
  110972. defines.NOISE = this._enableNoise;
  110973. }
  110974. if (defines._areLightsDirty) {
  110975. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  110976. }
  110977. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  110978. if (!this._imageProcessingConfiguration.isReady()) {
  110979. return false;
  110980. }
  110981. this._imageProcessingConfiguration.prepareDefines(defines);
  110982. }
  110983. // Misc.
  110984. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  110985. // Values that need to be evaluated on every frame
  110986. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  110987. // Attribs
  110988. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  110989. if (mesh) {
  110990. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  110991. mesh.createNormals(true);
  110992. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  110993. }
  110994. }
  110995. }
  110996. // Get correct effect
  110997. if (defines.isDirty) {
  110998. defines.markAsProcessed();
  110999. scene.resetCachedMaterial();
  111000. // Fallbacks
  111001. var fallbacks = new BABYLON.EffectFallbacks();
  111002. if (defines.FOG) {
  111003. fallbacks.addFallback(0, "FOG");
  111004. }
  111005. if (defines.POINTSIZE) {
  111006. fallbacks.addFallback(1, "POINTSIZE");
  111007. }
  111008. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  111009. if (defines.NUM_BONE_INFLUENCERS > 0) {
  111010. fallbacks.addCPUSkinningFallback(0, mesh);
  111011. }
  111012. //Attributes
  111013. var attribs = [BABYLON.VertexBuffer.PositionKind];
  111014. if (defines.NORMAL) {
  111015. attribs.push(BABYLON.VertexBuffer.NormalKind);
  111016. }
  111017. if (defines.UV1) {
  111018. attribs.push(BABYLON.VertexBuffer.UVKind);
  111019. }
  111020. if (defines.UV2) {
  111021. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  111022. }
  111023. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  111024. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  111025. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  111026. "vFogInfos", "vFogColor", "pointSize",
  111027. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  111028. "vPrimaryColor", "vPrimaryColorShadow",
  111029. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  111030. "shadowLevel", "alpha",
  111031. "vBackgroundCenter", "vReflectionControl",
  111032. "vDiffuseInfos", "diffuseMatrix",
  111033. ];
  111034. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  111035. var uniformBuffers = ["Material", "Scene"];
  111036. if (BABYLON.ImageProcessingConfiguration) {
  111037. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  111038. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  111039. }
  111040. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  111041. uniformsNames: uniforms,
  111042. uniformBuffersNames: uniformBuffers,
  111043. samplers: samplers,
  111044. defines: defines,
  111045. maxSimultaneousLights: this._maxSimultaneousLights
  111046. });
  111047. var onCompiled = function (effect) {
  111048. if (_this.onCompiled) {
  111049. _this.onCompiled(effect);
  111050. }
  111051. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  111052. };
  111053. var join = defines.toString();
  111054. subMesh.setEffect(scene.getEngine().createEffect("background", {
  111055. attributes: attribs,
  111056. uniformsNames: uniforms,
  111057. uniformBuffersNames: uniformBuffers,
  111058. samplers: samplers,
  111059. defines: join,
  111060. fallbacks: fallbacks,
  111061. onCompiled: onCompiled,
  111062. onError: this.onError,
  111063. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  111064. }, engine), defines);
  111065. this.buildUniformLayout();
  111066. }
  111067. if (!subMesh.effect || !subMesh.effect.isReady()) {
  111068. return false;
  111069. }
  111070. defines._renderId = scene.getRenderId();
  111071. this._wasPreviouslyReady = true;
  111072. return true;
  111073. };
  111074. /**
  111075. * Compute the primary color according to the chosen perceptual color.
  111076. */
  111077. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  111078. if (!this.__perceptualColor) {
  111079. return;
  111080. }
  111081. this._primaryColor.copyFrom(this.__perceptualColor);
  111082. // Revert gamma space.
  111083. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  111084. // Revert image processing configuration.
  111085. if (this._imageProcessingConfiguration) {
  111086. // Revert Exposure.
  111087. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  111088. }
  111089. this._computePrimaryColors();
  111090. };
  111091. /**
  111092. * Compute the highlights and shadow colors according to their chosen levels.
  111093. */
  111094. BackgroundMaterial.prototype._computePrimaryColors = function () {
  111095. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  111096. return;
  111097. }
  111098. // Find the highlight color based on the configuration.
  111099. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  111100. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  111101. // Find the shadow color based on the configuration.
  111102. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  111103. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  111104. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  111105. };
  111106. /**
  111107. * Build the uniform buffer used in the material.
  111108. */
  111109. BackgroundMaterial.prototype.buildUniformLayout = function () {
  111110. // Order is important !
  111111. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  111112. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  111113. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  111114. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  111115. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  111116. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  111117. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  111118. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  111119. this._uniformBuffer.addUniform("pointSize", 1);
  111120. this._uniformBuffer.addUniform("shadowLevel", 1);
  111121. this._uniformBuffer.addUniform("alpha", 1);
  111122. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  111123. this._uniformBuffer.addUniform("vReflectionControl", 4);
  111124. this._uniformBuffer.create();
  111125. };
  111126. /**
  111127. * Unbind the material.
  111128. */
  111129. BackgroundMaterial.prototype.unbind = function () {
  111130. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  111131. this._uniformBuffer.setTexture("diffuseSampler", null);
  111132. }
  111133. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  111134. this._uniformBuffer.setTexture("reflectionSampler", null);
  111135. }
  111136. _super.prototype.unbind.call(this);
  111137. };
  111138. /**
  111139. * Bind only the world matrix to the material.
  111140. * @param world The world matrix to bind.
  111141. */
  111142. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  111143. this._activeEffect.setMatrix("world", world);
  111144. };
  111145. /**
  111146. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  111147. * @param world The world matrix to bind.
  111148. * @param subMesh The submesh to bind for.
  111149. */
  111150. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  111151. var scene = this.getScene();
  111152. var defines = subMesh._materialDefines;
  111153. if (!defines) {
  111154. return;
  111155. }
  111156. var effect = subMesh.effect;
  111157. if (!effect) {
  111158. return;
  111159. }
  111160. this._activeEffect = effect;
  111161. // Matrices
  111162. this.bindOnlyWorldMatrix(world);
  111163. // Bones
  111164. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  111165. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  111166. if (mustRebind) {
  111167. this._uniformBuffer.bindToEffect(effect, "Material");
  111168. this.bindViewProjection(effect);
  111169. var reflectionTexture = this._reflectionTexture;
  111170. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  111171. // Texture uniforms
  111172. if (scene.texturesEnabled) {
  111173. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111174. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  111175. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  111176. }
  111177. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111178. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  111179. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  111180. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  111181. }
  111182. }
  111183. if (this.shadowLevel > 0) {
  111184. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  111185. }
  111186. this._uniformBuffer.updateFloat("alpha", this.alpha);
  111187. // Point size
  111188. if (this.pointsCloud) {
  111189. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  111190. }
  111191. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  111192. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  111193. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  111194. }
  111195. else {
  111196. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  111197. }
  111198. }
  111199. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  111200. // Textures
  111201. if (scene.texturesEnabled) {
  111202. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111203. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  111204. }
  111205. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111206. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  111207. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  111208. }
  111209. else if (!defines.REFLECTIONBLUR) {
  111210. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  111211. }
  111212. else {
  111213. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  111214. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  111215. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  111216. }
  111217. if (defines.REFLECTIONFRESNEL) {
  111218. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  111219. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  111220. }
  111221. }
  111222. }
  111223. // Clip plane
  111224. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  111225. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  111226. }
  111227. if (mustRebind || !this.isFrozen) {
  111228. if (scene.lightsEnabled) {
  111229. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  111230. }
  111231. // View
  111232. this.bindView(effect);
  111233. // Fog
  111234. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  111235. // image processing
  111236. if (this._imageProcessingConfiguration) {
  111237. this._imageProcessingConfiguration.bind(this._activeEffect);
  111238. }
  111239. }
  111240. this._uniformBuffer.update();
  111241. this._afterBind(mesh, this._activeEffect);
  111242. };
  111243. /**
  111244. * Dispose the material.
  111245. * @param forceDisposeEffect Force disposal of the associated effect.
  111246. * @param forceDisposeTextures Force disposal of the associated textures.
  111247. */
  111248. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  111249. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  111250. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  111251. if (forceDisposeTextures) {
  111252. if (this.diffuseTexture) {
  111253. this.diffuseTexture.dispose();
  111254. }
  111255. if (this.reflectionTexture) {
  111256. this.reflectionTexture.dispose();
  111257. }
  111258. }
  111259. this._renderTargets.dispose();
  111260. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  111261. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  111262. }
  111263. _super.prototype.dispose.call(this, forceDisposeEffect);
  111264. };
  111265. /**
  111266. * Clones the material.
  111267. * @param name The cloned name.
  111268. * @returns The cloned material.
  111269. */
  111270. BackgroundMaterial.prototype.clone = function (name) {
  111271. var _this = this;
  111272. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  111273. };
  111274. /**
  111275. * Serializes the current material to its JSON representation.
  111276. * @returns The JSON representation.
  111277. */
  111278. BackgroundMaterial.prototype.serialize = function () {
  111279. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  111280. serializationObject.customType = "BABYLON.BackgroundMaterial";
  111281. return serializationObject;
  111282. };
  111283. /**
  111284. * Gets the class name of the material
  111285. * @returns "BackgroundMaterial"
  111286. */
  111287. BackgroundMaterial.prototype.getClassName = function () {
  111288. return "BackgroundMaterial";
  111289. };
  111290. /**
  111291. * Parse a JSON input to create back a background material.
  111292. * @param source The JSON data to parse
  111293. * @param scene The scene to create the parsed material in
  111294. * @param rootUrl The root url of the assets the material depends upon
  111295. * @returns the instantiated BackgroundMaterial.
  111296. */
  111297. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  111298. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  111299. };
  111300. /**
  111301. * Standard reflectance value at parallel view angle.
  111302. */
  111303. BackgroundMaterial.StandardReflectance0 = 0.05;
  111304. /**
  111305. * Standard reflectance value at grazing angle.
  111306. */
  111307. BackgroundMaterial.StandardReflectance90 = 0.5;
  111308. __decorate([
  111309. BABYLON.serializeAsColor3()
  111310. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  111311. __decorate([
  111312. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  111313. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  111314. __decorate([
  111315. BABYLON.serializeAsColor3()
  111316. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  111317. __decorate([
  111318. BABYLON.serialize()
  111319. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  111320. __decorate([
  111321. BABYLON.serialize()
  111322. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  111323. __decorate([
  111324. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  111325. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  111326. __decorate([
  111327. BABYLON.serializeAsTexture()
  111328. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  111329. __decorate([
  111330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111331. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  111332. __decorate([
  111333. BABYLON.serialize()
  111334. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  111335. __decorate([
  111336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111337. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  111338. __decorate([
  111339. BABYLON.serializeAsTexture()
  111340. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  111341. __decorate([
  111342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111343. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  111344. __decorate([
  111345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111346. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  111347. __decorate([
  111348. BABYLON.serialize()
  111349. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  111350. __decorate([
  111351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111352. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  111353. __decorate([
  111354. BABYLON.serializeAsVector3()
  111355. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  111356. __decorate([
  111357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111358. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  111359. __decorate([
  111360. BABYLON.serialize()
  111361. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  111362. __decorate([
  111363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111364. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  111365. __decorate([
  111366. BABYLON.serialize()
  111367. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  111368. __decorate([
  111369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111370. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  111371. __decorate([
  111372. BABYLON.serialize()
  111373. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  111374. __decorate([
  111375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111376. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  111377. __decorate([
  111378. BABYLON.serialize()
  111379. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  111380. __decorate([
  111381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111382. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  111383. __decorate([
  111384. BABYLON.serialize()
  111385. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  111386. __decorate([
  111387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111388. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  111389. __decorate([
  111390. BABYLON.serialize()
  111391. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  111392. __decorate([
  111393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111394. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  111395. __decorate([
  111396. BABYLON.serialize()
  111397. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  111398. __decorate([
  111399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111400. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  111401. __decorate([
  111402. BABYLON.serialize()
  111403. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  111404. __decorate([
  111405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111406. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  111407. __decorate([
  111408. BABYLON.serialize()
  111409. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  111410. __decorate([
  111411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111412. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  111413. __decorate([
  111414. BABYLON.serializeAsImageProcessingConfiguration()
  111415. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  111416. return BackgroundMaterial;
  111417. }(BABYLON.PushMaterial));
  111418. BABYLON.BackgroundMaterial = BackgroundMaterial;
  111419. })(BABYLON || (BABYLON = {}));
  111420. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  111421. var __assign = (this && this.__assign) || function () {
  111422. __assign = Object.assign || function(t) {
  111423. for (var s, i = 1, n = arguments.length; i < n; i++) {
  111424. s = arguments[i];
  111425. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  111426. t[p] = s[p];
  111427. }
  111428. return t;
  111429. };
  111430. return __assign.apply(this, arguments);
  111431. };
  111432. var BABYLON;
  111433. (function (BABYLON) {
  111434. /**
  111435. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  111436. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  111437. * It also helps with the default setup of your imageProcessing configuration.
  111438. */
  111439. var EnvironmentHelper = /** @class */ (function () {
  111440. /**
  111441. * constructor
  111442. * @param options
  111443. * @param scene The scene to add the material to
  111444. */
  111445. function EnvironmentHelper(options, scene) {
  111446. var _this = this;
  111447. this._errorHandler = function (message, exception) {
  111448. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  111449. };
  111450. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  111451. this._scene = scene;
  111452. this.onErrorObservable = new BABYLON.Observable();
  111453. this._setupBackground();
  111454. this._setupImageProcessing();
  111455. }
  111456. /**
  111457. * Creates the default options for the helper.
  111458. */
  111459. EnvironmentHelper._getDefaultOptions = function () {
  111460. return {
  111461. createGround: true,
  111462. groundSize: 15,
  111463. groundTexture: this._groundTextureCDNUrl,
  111464. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  111465. groundOpacity: 0.9,
  111466. enableGroundShadow: true,
  111467. groundShadowLevel: 0.5,
  111468. enableGroundMirror: false,
  111469. groundMirrorSizeRatio: 0.3,
  111470. groundMirrorBlurKernel: 64,
  111471. groundMirrorAmount: 1,
  111472. groundMirrorFresnelWeight: 1,
  111473. groundMirrorFallOffDistance: 0,
  111474. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  111475. groundYBias: 0.00001,
  111476. createSkybox: true,
  111477. skyboxSize: 20,
  111478. skyboxTexture: this._skyboxTextureCDNUrl,
  111479. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  111480. backgroundYRotation: 0,
  111481. sizeAuto: true,
  111482. rootPosition: BABYLON.Vector3.Zero(),
  111483. setupImageProcessing: true,
  111484. environmentTexture: this._environmentTextureCDNUrl,
  111485. cameraExposure: 0.8,
  111486. cameraContrast: 1.2,
  111487. toneMappingEnabled: true,
  111488. };
  111489. };
  111490. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  111491. /**
  111492. * Gets the root mesh created by the helper.
  111493. */
  111494. get: function () {
  111495. return this._rootMesh;
  111496. },
  111497. enumerable: true,
  111498. configurable: true
  111499. });
  111500. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  111501. /**
  111502. * Gets the skybox created by the helper.
  111503. */
  111504. get: function () {
  111505. return this._skybox;
  111506. },
  111507. enumerable: true,
  111508. configurable: true
  111509. });
  111510. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  111511. /**
  111512. * Gets the skybox texture created by the helper.
  111513. */
  111514. get: function () {
  111515. return this._skyboxTexture;
  111516. },
  111517. enumerable: true,
  111518. configurable: true
  111519. });
  111520. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  111521. /**
  111522. * Gets the skybox material created by the helper.
  111523. */
  111524. get: function () {
  111525. return this._skyboxMaterial;
  111526. },
  111527. enumerable: true,
  111528. configurable: true
  111529. });
  111530. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  111531. /**
  111532. * Gets the ground mesh created by the helper.
  111533. */
  111534. get: function () {
  111535. return this._ground;
  111536. },
  111537. enumerable: true,
  111538. configurable: true
  111539. });
  111540. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  111541. /**
  111542. * Gets the ground texture created by the helper.
  111543. */
  111544. get: function () {
  111545. return this._groundTexture;
  111546. },
  111547. enumerable: true,
  111548. configurable: true
  111549. });
  111550. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  111551. /**
  111552. * Gets the ground mirror created by the helper.
  111553. */
  111554. get: function () {
  111555. return this._groundMirror;
  111556. },
  111557. enumerable: true,
  111558. configurable: true
  111559. });
  111560. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  111561. /**
  111562. * Gets the ground mirror render list to helps pushing the meshes
  111563. * you wish in the ground reflection.
  111564. */
  111565. get: function () {
  111566. if (this._groundMirror) {
  111567. return this._groundMirror.renderList;
  111568. }
  111569. return null;
  111570. },
  111571. enumerable: true,
  111572. configurable: true
  111573. });
  111574. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  111575. /**
  111576. * Gets the ground material created by the helper.
  111577. */
  111578. get: function () {
  111579. return this._groundMaterial;
  111580. },
  111581. enumerable: true,
  111582. configurable: true
  111583. });
  111584. /**
  111585. * Updates the background according to the new options
  111586. * @param options
  111587. */
  111588. EnvironmentHelper.prototype.updateOptions = function (options) {
  111589. var newOptions = __assign({}, this._options, options);
  111590. if (this._ground && !newOptions.createGround) {
  111591. this._ground.dispose();
  111592. this._ground = null;
  111593. }
  111594. if (this._groundMaterial && !newOptions.createGround) {
  111595. this._groundMaterial.dispose();
  111596. this._groundMaterial = null;
  111597. }
  111598. if (this._groundTexture) {
  111599. if (this._options.groundTexture != newOptions.groundTexture) {
  111600. this._groundTexture.dispose();
  111601. this._groundTexture = null;
  111602. }
  111603. }
  111604. if (this._skybox && !newOptions.createSkybox) {
  111605. this._skybox.dispose();
  111606. this._skybox = null;
  111607. }
  111608. if (this._skyboxMaterial && !newOptions.createSkybox) {
  111609. this._skyboxMaterial.dispose();
  111610. this._skyboxMaterial = null;
  111611. }
  111612. if (this._skyboxTexture) {
  111613. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  111614. this._skyboxTexture.dispose();
  111615. this._skyboxTexture = null;
  111616. }
  111617. }
  111618. if (this._groundMirror && !newOptions.enableGroundMirror) {
  111619. this._groundMirror.dispose();
  111620. this._groundMirror = null;
  111621. }
  111622. if (this._scene.environmentTexture) {
  111623. if (this._options.environmentTexture != newOptions.environmentTexture) {
  111624. this._scene.environmentTexture.dispose();
  111625. }
  111626. }
  111627. this._options = newOptions;
  111628. this._setupBackground();
  111629. this._setupImageProcessing();
  111630. };
  111631. /**
  111632. * Sets the primary color of all the available elements.
  111633. * @param color the main color to affect to the ground and the background
  111634. */
  111635. EnvironmentHelper.prototype.setMainColor = function (color) {
  111636. if (this.groundMaterial) {
  111637. this.groundMaterial.primaryColor = color;
  111638. }
  111639. if (this.skyboxMaterial) {
  111640. this.skyboxMaterial.primaryColor = color;
  111641. }
  111642. if (this.groundMirror) {
  111643. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  111644. }
  111645. };
  111646. /**
  111647. * Setup the image processing according to the specified options.
  111648. */
  111649. EnvironmentHelper.prototype._setupImageProcessing = function () {
  111650. if (this._options.setupImageProcessing) {
  111651. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  111652. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  111653. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  111654. this._setupEnvironmentTexture();
  111655. }
  111656. };
  111657. /**
  111658. * Setup the environment texture according to the specified options.
  111659. */
  111660. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  111661. if (this._scene.environmentTexture) {
  111662. return;
  111663. }
  111664. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  111665. this._scene.environmentTexture = this._options.environmentTexture;
  111666. return;
  111667. }
  111668. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  111669. this._scene.environmentTexture = environmentTexture;
  111670. };
  111671. /**
  111672. * Setup the background according to the specified options.
  111673. */
  111674. EnvironmentHelper.prototype._setupBackground = function () {
  111675. if (!this._rootMesh) {
  111676. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  111677. }
  111678. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  111679. var sceneSize = this._getSceneSize();
  111680. if (this._options.createGround) {
  111681. this._setupGround(sceneSize);
  111682. this._setupGroundMaterial();
  111683. this._setupGroundDiffuseTexture();
  111684. if (this._options.enableGroundMirror) {
  111685. this._setupGroundMirrorTexture(sceneSize);
  111686. }
  111687. this._setupMirrorInGroundMaterial();
  111688. }
  111689. if (this._options.createSkybox) {
  111690. this._setupSkybox(sceneSize);
  111691. this._setupSkyboxMaterial();
  111692. this._setupSkyboxReflectionTexture();
  111693. }
  111694. this._rootMesh.position.x = sceneSize.rootPosition.x;
  111695. this._rootMesh.position.z = sceneSize.rootPosition.z;
  111696. this._rootMesh.position.y = sceneSize.rootPosition.y;
  111697. };
  111698. /**
  111699. * Get the scene sizes according to the setup.
  111700. */
  111701. EnvironmentHelper.prototype._getSceneSize = function () {
  111702. var _this = this;
  111703. var groundSize = this._options.groundSize;
  111704. var skyboxSize = this._options.skyboxSize;
  111705. var rootPosition = this._options.rootPosition;
  111706. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  111707. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  111708. }
  111709. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  111710. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  111711. });
  111712. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  111713. if (this._options.sizeAuto) {
  111714. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  111715. this._scene.activeCamera.upperRadiusLimit) {
  111716. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  111717. skyboxSize = groundSize;
  111718. }
  111719. var sceneDiagonalLenght = sceneDiagonal.length();
  111720. if (sceneDiagonalLenght > groundSize) {
  111721. groundSize = sceneDiagonalLenght * 2;
  111722. skyboxSize = groundSize;
  111723. }
  111724. // 10 % bigger.
  111725. groundSize *= 1.1;
  111726. skyboxSize *= 1.5;
  111727. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  111728. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  111729. }
  111730. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  111731. };
  111732. /**
  111733. * Setup the ground according to the specified options.
  111734. */
  111735. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  111736. var _this = this;
  111737. if (!this._ground || this._ground.isDisposed()) {
  111738. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  111739. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  111740. this._ground.parent = this._rootMesh;
  111741. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  111742. }
  111743. this._ground.receiveShadows = this._options.enableGroundShadow;
  111744. };
  111745. /**
  111746. * Setup the ground material according to the specified options.
  111747. */
  111748. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  111749. if (!this._groundMaterial) {
  111750. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  111751. }
  111752. this._groundMaterial.alpha = this._options.groundOpacity;
  111753. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  111754. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  111755. this._groundMaterial.primaryColor = this._options.groundColor;
  111756. this._groundMaterial.useRGBColor = false;
  111757. this._groundMaterial.enableNoise = true;
  111758. if (this._ground) {
  111759. this._ground.material = this._groundMaterial;
  111760. }
  111761. };
  111762. /**
  111763. * Setup the ground diffuse texture according to the specified options.
  111764. */
  111765. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  111766. if (!this._groundMaterial) {
  111767. return;
  111768. }
  111769. if (this._groundTexture) {
  111770. return;
  111771. }
  111772. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  111773. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  111774. return;
  111775. }
  111776. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  111777. diffuseTexture.gammaSpace = false;
  111778. diffuseTexture.hasAlpha = true;
  111779. this._groundMaterial.diffuseTexture = diffuseTexture;
  111780. };
  111781. /**
  111782. * Setup the ground mirror texture according to the specified options.
  111783. */
  111784. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  111785. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111786. if (!this._groundMirror) {
  111787. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  111788. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  111789. this._groundMirror.anisotropicFilteringLevel = 1;
  111790. this._groundMirror.wrapU = wrapping;
  111791. this._groundMirror.wrapV = wrapping;
  111792. this._groundMirror.gammaSpace = false;
  111793. if (this._groundMirror.renderList) {
  111794. for (var i = 0; i < this._scene.meshes.length; i++) {
  111795. var mesh = this._scene.meshes[i];
  111796. if (mesh !== this._ground &&
  111797. mesh !== this._skybox &&
  111798. mesh !== this._rootMesh) {
  111799. this._groundMirror.renderList.push(mesh);
  111800. }
  111801. }
  111802. }
  111803. }
  111804. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  111805. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  111806. };
  111807. /**
  111808. * Setup the ground to receive the mirror texture.
  111809. */
  111810. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  111811. if (this._groundMaterial) {
  111812. this._groundMaterial.reflectionTexture = this._groundMirror;
  111813. this._groundMaterial.reflectionFresnel = true;
  111814. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  111815. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  111816. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  111817. }
  111818. };
  111819. /**
  111820. * Setup the skybox according to the specified options.
  111821. */
  111822. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  111823. var _this = this;
  111824. if (!this._skybox || this._skybox.isDisposed()) {
  111825. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  111826. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  111827. }
  111828. this._skybox.parent = this._rootMesh;
  111829. };
  111830. /**
  111831. * Setup the skybox material according to the specified options.
  111832. */
  111833. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  111834. if (!this._skybox) {
  111835. return;
  111836. }
  111837. if (!this._skyboxMaterial) {
  111838. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  111839. }
  111840. this._skyboxMaterial.useRGBColor = false;
  111841. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  111842. this._skyboxMaterial.enableNoise = true;
  111843. this._skybox.material = this._skyboxMaterial;
  111844. };
  111845. /**
  111846. * Setup the skybox reflection texture according to the specified options.
  111847. */
  111848. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  111849. if (!this._skyboxMaterial) {
  111850. return;
  111851. }
  111852. if (this._skyboxTexture) {
  111853. return;
  111854. }
  111855. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  111856. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  111857. return;
  111858. }
  111859. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  111860. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  111861. this._skyboxTexture.gammaSpace = false;
  111862. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  111863. };
  111864. /**
  111865. * Dispose all the elements created by the Helper.
  111866. */
  111867. EnvironmentHelper.prototype.dispose = function () {
  111868. if (this._groundMaterial) {
  111869. this._groundMaterial.dispose(true, true);
  111870. }
  111871. if (this._skyboxMaterial) {
  111872. this._skyboxMaterial.dispose(true, true);
  111873. }
  111874. this._rootMesh.dispose(false);
  111875. };
  111876. /**
  111877. * Default ground texture URL.
  111878. */
  111879. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  111880. /**
  111881. * Default skybox texture URL.
  111882. */
  111883. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  111884. /**
  111885. * Default environment texture URL.
  111886. */
  111887. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  111888. return EnvironmentHelper;
  111889. }());
  111890. BABYLON.EnvironmentHelper = EnvironmentHelper;
  111891. })(BABYLON || (BABYLON = {}));
  111892. //# sourceMappingURL=babylon.environmentHelper.js.map
  111893. var BABYLON;
  111894. (function (BABYLON) {
  111895. /** Internal class used to store shapes for emitters */
  111896. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  111897. function ParticleSystemSetEmitterCreationOptions() {
  111898. }
  111899. return ParticleSystemSetEmitterCreationOptions;
  111900. }());
  111901. /**
  111902. * Represents a set of particle systems working together to create a specific effect
  111903. */
  111904. var ParticleSystemSet = /** @class */ (function () {
  111905. function ParticleSystemSet() {
  111906. /**
  111907. * Gets the particle system list
  111908. */
  111909. this.systems = new Array();
  111910. }
  111911. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  111912. /**
  111913. * Gets the emitter node used with this set
  111914. */
  111915. get: function () {
  111916. return this._emitterNode;
  111917. },
  111918. enumerable: true,
  111919. configurable: true
  111920. });
  111921. /**
  111922. * Creates a new emitter mesh as a sphere
  111923. * @param options defines the options used to create the sphere
  111924. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  111925. * @param scene defines the hosting scene
  111926. */
  111927. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  111928. if (this._emitterNode) {
  111929. this._emitterNode.dispose();
  111930. }
  111931. this._emitterCreationOptions = {
  111932. kind: "Sphere",
  111933. options: options,
  111934. renderingGroupId: renderingGroupId
  111935. };
  111936. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  111937. emitterMesh.renderingGroupId = renderingGroupId;
  111938. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  111939. material.emissiveColor = options.color;
  111940. emitterMesh.material = material;
  111941. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111942. var system = _a[_i];
  111943. system.emitter = emitterMesh;
  111944. }
  111945. this._emitterNode = emitterMesh;
  111946. };
  111947. /**
  111948. * Starts all particle systems of the set
  111949. * @param emitter defines an optional mesh to use as emitter for the particle systems
  111950. */
  111951. ParticleSystemSet.prototype.start = function (emitter) {
  111952. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111953. var system = _a[_i];
  111954. if (emitter) {
  111955. system.emitter = emitter;
  111956. }
  111957. system.start();
  111958. }
  111959. };
  111960. /**
  111961. * Release all associated resources
  111962. */
  111963. ParticleSystemSet.prototype.dispose = function () {
  111964. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111965. var system = _a[_i];
  111966. system.dispose();
  111967. }
  111968. this.systems = [];
  111969. if (this._emitterNode) {
  111970. this._emitterNode.dispose();
  111971. this._emitterNode = null;
  111972. }
  111973. };
  111974. /**
  111975. * Serialize the set into a JSON compatible object
  111976. * @returns a JSON compatible representation of the set
  111977. */
  111978. ParticleSystemSet.prototype.serialize = function () {
  111979. var result = {};
  111980. result.systems = [];
  111981. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111982. var system = _a[_i];
  111983. result.systems.push(system.serialize());
  111984. }
  111985. if (this._emitterNode) {
  111986. result.emitter = this._emitterCreationOptions;
  111987. }
  111988. return result;
  111989. };
  111990. /**
  111991. * Parse a new ParticleSystemSet from a serialized source
  111992. * @param data defines a JSON compatible representation of the set
  111993. * @param scene defines the hosting scene
  111994. * @param gpu defines if we want GPU particles or CPU particles
  111995. * @returns a new ParticleSystemSet
  111996. */
  111997. ParticleSystemSet.Parse = function (data, scene, gpu) {
  111998. if (gpu === void 0) { gpu = false; }
  111999. var result = new ParticleSystemSet();
  112000. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  112001. scene = scene || BABYLON.Engine.LastCreatedScene;
  112002. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  112003. var system = _a[_i];
  112004. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  112005. }
  112006. if (data.emitter) {
  112007. var options = data.emitter.options;
  112008. switch (data.emitter.kind) {
  112009. case "Sphere":
  112010. result.setEmitterAsSphere({
  112011. diameter: options.diameter,
  112012. segments: options.segments,
  112013. color: BABYLON.Color3.FromArray(options.color)
  112014. }, data.emitter.renderingGroupId, scene);
  112015. break;
  112016. }
  112017. }
  112018. return result;
  112019. };
  112020. return ParticleSystemSet;
  112021. }());
  112022. BABYLON.ParticleSystemSet = ParticleSystemSet;
  112023. })(BABYLON || (BABYLON = {}));
  112024. //# sourceMappingURL=babylon.particleSystemSet.js.map
  112025. var BABYLON;
  112026. (function (BABYLON) {
  112027. /**
  112028. * This class is made for on one-liner static method to help creating particle system set.
  112029. */
  112030. var ParticleHelper = /** @class */ (function () {
  112031. function ParticleHelper() {
  112032. }
  112033. /**
  112034. * Create a default particle system that you can tweak
  112035. * @param emitter defines the emitter to use
  112036. * @param capacity defines the system capacity (default is 500 particles)
  112037. * @param scene defines the hosting scene
  112038. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  112039. * @returns the new Particle system
  112040. */
  112041. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  112042. if (capacity === void 0) { capacity = 500; }
  112043. if (useGPU === void 0) { useGPU = false; }
  112044. var system;
  112045. if (useGPU) {
  112046. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  112047. }
  112048. else {
  112049. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  112050. }
  112051. system.emitter = emitter;
  112052. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  112053. system.createConeEmitter(0.1, Math.PI / 4);
  112054. // Particle color
  112055. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  112056. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  112057. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  112058. // Particle Size
  112059. system.minSize = 0.1;
  112060. system.maxSize = 0.1;
  112061. // Emission speed
  112062. system.minEmitPower = 2;
  112063. system.maxEmitPower = 2;
  112064. // Update speed
  112065. system.updateSpeed = 1 / 60;
  112066. system.emitRate = 30;
  112067. return system;
  112068. };
  112069. /**
  112070. * This is the main static method (one-liner) of this helper to create different particle systems
  112071. * @param type This string represents the type to the particle system to create
  112072. * @param scene The scene where the particle system should live
  112073. * @param gpu If the system will use gpu
  112074. * @returns the ParticleSystemSet created
  112075. */
  112076. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  112077. if (gpu === void 0) { gpu = false; }
  112078. if (!scene) {
  112079. scene = BABYLON.Engine.LastCreatedScene;
  112080. ;
  112081. }
  112082. var token = {};
  112083. scene._addPendingData(token);
  112084. return new Promise(function (resolve, reject) {
  112085. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  112086. scene._removePendingData(token);
  112087. return reject("Particle system with GPU is not supported.");
  112088. }
  112089. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  112090. scene._removePendingData(token);
  112091. var newData = JSON.parse(data.toString());
  112092. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  112093. }, undefined, undefined, undefined, function (req, exception) {
  112094. scene._removePendingData(token);
  112095. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  112096. });
  112097. });
  112098. };
  112099. /**
  112100. * Static function used to export a particle system to a ParticleSystemSet variable.
  112101. * Please note that the emitter shape is not exported
  112102. * @param system defines the particle systems to export
  112103. */
  112104. ParticleHelper.ExportSet = function (systems) {
  112105. var set = new BABYLON.ParticleSystemSet();
  112106. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  112107. var system = systems_1[_i];
  112108. set.systems.push(system);
  112109. }
  112110. return set;
  112111. };
  112112. /**
  112113. * Gets or sets base Assets URL
  112114. */
  112115. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  112116. return ParticleHelper;
  112117. }());
  112118. BABYLON.ParticleHelper = ParticleHelper;
  112119. })(BABYLON || (BABYLON = {}));
  112120. //# sourceMappingURL=babylon.particleHelper.js.map
  112121. var BABYLON;
  112122. (function (BABYLON) {
  112123. /**
  112124. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  112125. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  112126. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  112127. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  112128. */
  112129. var VideoDome = /** @class */ (function (_super) {
  112130. __extends(VideoDome, _super);
  112131. /**
  112132. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  112133. * @param name Element's name, child elements will append suffixes for their own names.
  112134. * @param urlsOrVideo defines the url(s) or the video element to use
  112135. * @param options An object containing optional or exposed sub element properties
  112136. */
  112137. function VideoDome(name, urlsOrVideo, options, scene) {
  112138. var _this = _super.call(this, name, scene) || this;
  112139. _this._useDirectMapping = false;
  112140. // set defaults and manage values
  112141. name = name || "videoDome";
  112142. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  112143. options.clickToPlay = Boolean(options.clickToPlay);
  112144. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  112145. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  112146. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  112147. if (options.useDirectMapping === undefined) {
  112148. _this._useDirectMapping = true;
  112149. }
  112150. else {
  112151. _this._useDirectMapping = options.useDirectMapping;
  112152. }
  112153. _this._setReady(false);
  112154. // create
  112155. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  112156. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  112157. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  112158. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  112159. texture.onLoadObservable.addOnce(function () {
  112160. _this._setReady(true);
  112161. });
  112162. // configure material
  112163. material.useEquirectangularFOV = true;
  112164. material.fovMultiplier = 1.0;
  112165. material.opacityFresnel = false;
  112166. if (_this._useDirectMapping) {
  112167. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112168. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112169. material.diffuseTexture = texture;
  112170. }
  112171. else {
  112172. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  112173. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112174. material.reflectionTexture = texture;
  112175. }
  112176. // configure mesh
  112177. _this._mesh.material = material;
  112178. _this._mesh.parent = _this;
  112179. // optional configuration
  112180. if (options.clickToPlay) {
  112181. scene.onPointerUp = function () {
  112182. _this._videoTexture.video.play();
  112183. };
  112184. }
  112185. return _this;
  112186. }
  112187. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  112188. /**
  112189. * Gets the video texture being displayed on the sphere
  112190. */
  112191. get: function () {
  112192. return this._videoTexture;
  112193. },
  112194. enumerable: true,
  112195. configurable: true
  112196. });
  112197. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  112198. /**
  112199. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112200. * Also see the options.resolution property.
  112201. */
  112202. get: function () {
  112203. return this._material.fovMultiplier;
  112204. },
  112205. set: function (value) {
  112206. this._material.fovMultiplier = value;
  112207. },
  112208. enumerable: true,
  112209. configurable: true
  112210. });
  112211. /**
  112212. * Releases resources associated with this node.
  112213. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  112214. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  112215. */
  112216. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  112217. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  112218. this._videoTexture.dispose();
  112219. this._mesh.dispose();
  112220. this._material.dispose();
  112221. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  112222. };
  112223. return VideoDome;
  112224. }(BABYLON.TransformNode));
  112225. BABYLON.VideoDome = VideoDome;
  112226. })(BABYLON || (BABYLON = {}));
  112227. //# sourceMappingURL=babylon.videoDome.js.map
  112228. var BABYLON;
  112229. (function (BABYLON) {
  112230. /**
  112231. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  112232. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  112233. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  112234. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  112235. */
  112236. var PhotoDome = /** @class */ (function (_super) {
  112237. __extends(PhotoDome, _super);
  112238. /**
  112239. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  112240. * @param name Element's name, child elements will append suffixes for their own names.
  112241. * @param urlsOfPhoto defines the url of the photo to display
  112242. * @param options defines an object containing optional or exposed sub element properties
  112243. * @param onError defines a callback called when an error occured while loading the texture
  112244. */
  112245. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  112246. if (onError === void 0) { onError = null; }
  112247. var _this = _super.call(this, name, scene) || this;
  112248. _this._useDirectMapping = false;
  112249. /**
  112250. * Observable raised when an error occured while loading the 360 image
  112251. */
  112252. _this.onLoadErrorObservable = new BABYLON.Observable();
  112253. // set defaults and manage values
  112254. name = name || "photoDome";
  112255. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  112256. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  112257. if (options.useDirectMapping === undefined) {
  112258. _this._useDirectMapping = true;
  112259. }
  112260. else {
  112261. _this._useDirectMapping = options.useDirectMapping;
  112262. }
  112263. _this._setReady(false);
  112264. // create
  112265. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  112266. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  112267. // configure material
  112268. material.opacityFresnel = false;
  112269. material.useEquirectangularFOV = true;
  112270. material.fovMultiplier = 1.0;
  112271. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  112272. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  112273. if (onError) {
  112274. onError(message, exception);
  112275. }
  112276. });
  112277. _this.photoTexture.onLoadObservable.addOnce(function () {
  112278. _this._setReady(true);
  112279. });
  112280. // configure mesh
  112281. _this._mesh.material = material;
  112282. _this._mesh.parent = _this;
  112283. return _this;
  112284. }
  112285. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  112286. /**
  112287. * Gets or sets the texture being displayed on the sphere
  112288. */
  112289. get: function () {
  112290. return this._photoTexture;
  112291. },
  112292. set: function (value) {
  112293. if (this._photoTexture === value) {
  112294. return;
  112295. }
  112296. this._photoTexture = value;
  112297. if (this._useDirectMapping) {
  112298. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112299. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112300. this._material.diffuseTexture = this._photoTexture;
  112301. }
  112302. else {
  112303. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  112304. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112305. this._material.reflectionTexture = this._photoTexture;
  112306. }
  112307. },
  112308. enumerable: true,
  112309. configurable: true
  112310. });
  112311. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  112312. /**
  112313. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112314. * Also see the options.resolution property.
  112315. */
  112316. get: function () {
  112317. return this._material.fovMultiplier;
  112318. },
  112319. set: function (value) {
  112320. this._material.fovMultiplier = value;
  112321. },
  112322. enumerable: true,
  112323. configurable: true
  112324. });
  112325. /**
  112326. * Releases resources associated with this node.
  112327. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  112328. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  112329. */
  112330. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  112331. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  112332. this._photoTexture.dispose();
  112333. this._mesh.dispose();
  112334. this._material.dispose();
  112335. this.onLoadErrorObservable.clear();
  112336. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  112337. };
  112338. return PhotoDome;
  112339. }(BABYLON.TransformNode));
  112340. BABYLON.PhotoDome = PhotoDome;
  112341. })(BABYLON || (BABYLON = {}));
  112342. //# sourceMappingURL=babylon.photoDome.js.map
  112343. var BABYLON;
  112344. (function (BABYLON) {
  112345. BABYLON.Engine.prototype.createQuery = function () {
  112346. return this._gl.createQuery();
  112347. };
  112348. BABYLON.Engine.prototype.deleteQuery = function (query) {
  112349. this._gl.deleteQuery(query);
  112350. return this;
  112351. };
  112352. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  112353. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  112354. };
  112355. BABYLON.Engine.prototype.getQueryResult = function (query) {
  112356. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  112357. };
  112358. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  112359. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  112360. this._gl.beginQuery(glAlgorithm, query);
  112361. return this;
  112362. };
  112363. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  112364. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  112365. this._gl.endQuery(glAlgorithm);
  112366. return this;
  112367. };
  112368. BABYLON.Engine.prototype._createTimeQuery = function () {
  112369. var timerQuery = this.getCaps().timerQuery;
  112370. if (timerQuery.createQueryEXT) {
  112371. return timerQuery.createQueryEXT();
  112372. }
  112373. return this.createQuery();
  112374. };
  112375. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  112376. var timerQuery = this.getCaps().timerQuery;
  112377. if (timerQuery.deleteQueryEXT) {
  112378. timerQuery.deleteQueryEXT(query);
  112379. return;
  112380. }
  112381. this.deleteQuery(query);
  112382. };
  112383. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  112384. var timerQuery = this.getCaps().timerQuery;
  112385. if (timerQuery.getQueryObjectEXT) {
  112386. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  112387. }
  112388. return this.getQueryResult(query);
  112389. };
  112390. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  112391. var timerQuery = this.getCaps().timerQuery;
  112392. if (timerQuery.getQueryObjectEXT) {
  112393. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  112394. }
  112395. return this.isQueryResultAvailable(query);
  112396. };
  112397. BABYLON.Engine.prototype.startTimeQuery = function () {
  112398. var caps = this.getCaps();
  112399. var timerQuery = caps.timerQuery;
  112400. if (!timerQuery) {
  112401. return null;
  112402. }
  112403. var token = new BABYLON._TimeToken();
  112404. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  112405. if (caps.canUseTimestampForTimerQuery) {
  112406. token._startTimeQuery = this._createTimeQuery();
  112407. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  112408. }
  112409. else {
  112410. if (this._currentNonTimestampToken) {
  112411. return this._currentNonTimestampToken;
  112412. }
  112413. token._timeElapsedQuery = this._createTimeQuery();
  112414. if (timerQuery.beginQueryEXT) {
  112415. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  112416. }
  112417. else {
  112418. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  112419. }
  112420. this._currentNonTimestampToken = token;
  112421. }
  112422. return token;
  112423. };
  112424. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  112425. var caps = this.getCaps();
  112426. var timerQuery = caps.timerQuery;
  112427. if (!timerQuery || !token) {
  112428. return -1;
  112429. }
  112430. if (caps.canUseTimestampForTimerQuery) {
  112431. if (!token._startTimeQuery) {
  112432. return -1;
  112433. }
  112434. if (!token._endTimeQuery) {
  112435. token._endTimeQuery = this._createTimeQuery();
  112436. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  112437. }
  112438. }
  112439. else if (!token._timeElapsedQueryEnded) {
  112440. if (!token._timeElapsedQuery) {
  112441. return -1;
  112442. }
  112443. if (timerQuery.endQueryEXT) {
  112444. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  112445. }
  112446. else {
  112447. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  112448. }
  112449. token._timeElapsedQueryEnded = true;
  112450. }
  112451. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  112452. var available = false;
  112453. if (token._endTimeQuery) {
  112454. available = this._getTimeQueryAvailability(token._endTimeQuery);
  112455. }
  112456. else if (token._timeElapsedQuery) {
  112457. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  112458. }
  112459. if (available && !disjoint) {
  112460. var result = 0;
  112461. if (caps.canUseTimestampForTimerQuery) {
  112462. if (!token._startTimeQuery || !token._endTimeQuery) {
  112463. return -1;
  112464. }
  112465. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  112466. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  112467. result = timeEnd - timeStart;
  112468. this._deleteTimeQuery(token._startTimeQuery);
  112469. this._deleteTimeQuery(token._endTimeQuery);
  112470. token._startTimeQuery = null;
  112471. token._endTimeQuery = null;
  112472. }
  112473. else {
  112474. if (!token._timeElapsedQuery) {
  112475. return -1;
  112476. }
  112477. result = this._getTimeQueryResult(token._timeElapsedQuery);
  112478. this._deleteTimeQuery(token._timeElapsedQuery);
  112479. token._timeElapsedQuery = null;
  112480. token._timeElapsedQueryEnded = false;
  112481. this._currentNonTimestampToken = null;
  112482. }
  112483. return result;
  112484. }
  112485. return -1;
  112486. };
  112487. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  112488. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  112489. };
  112490. // We also need to update AbstractMesh as there is a portion of the code there
  112491. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  112492. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  112493. this._isOccluded = false;
  112494. return;
  112495. }
  112496. var engine = this.getEngine();
  112497. if (engine.webGLVersion < 2) {
  112498. this._isOccluded = false;
  112499. return;
  112500. }
  112501. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  112502. this._isOccluded = false;
  112503. return;
  112504. }
  112505. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  112506. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  112507. if (isOcclusionQueryAvailable) {
  112508. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  112509. this._isOcclusionQueryInProgress = false;
  112510. this._occlusionInternalRetryCounter = 0;
  112511. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  112512. }
  112513. else {
  112514. this._occlusionInternalRetryCounter++;
  112515. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  112516. this._isOcclusionQueryInProgress = false;
  112517. this._occlusionInternalRetryCounter = 0;
  112518. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  112519. // if strict continue the last state of the object.
  112520. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  112521. }
  112522. else {
  112523. return;
  112524. }
  112525. }
  112526. }
  112527. var scene = this.getScene();
  112528. if (scene.getBoundingBoxRenderer) {
  112529. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  112530. if (!this._occlusionQuery) {
  112531. this._occlusionQuery = engine.createQuery();
  112532. }
  112533. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  112534. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  112535. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  112536. this._isOcclusionQueryInProgress = true;
  112537. }
  112538. };
  112539. })(BABYLON || (BABYLON = {}));
  112540. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  112541. var BABYLON;
  112542. (function (BABYLON) {
  112543. /**
  112544. * Class used to generate noise procedural textures
  112545. */
  112546. var NoiseProceduralTexture = /** @class */ (function (_super) {
  112547. __extends(NoiseProceduralTexture, _super);
  112548. /**
  112549. * Creates a new NoiseProceduralTexture
  112550. * @param name defines the name fo the texture
  112551. * @param size defines the size of the texture (default is 256)
  112552. * @param scene defines the hosting scene
  112553. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  112554. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  112555. */
  112556. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  112557. if (size === void 0) { size = 256; }
  112558. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  112559. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  112560. _this._time = 0;
  112561. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  112562. _this.brightness = 0.2;
  112563. /** Defines the number of octaves to process */
  112564. _this.octaves = 3;
  112565. /** Defines the level of persistence (0.8 by default) */
  112566. _this.persistence = 0.8;
  112567. /** Gets or sets animation speed factor (default is 1) */
  112568. _this.animationSpeedFactor = 1;
  112569. _this._updateShaderUniforms();
  112570. return _this;
  112571. }
  112572. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  112573. var scene = this.getScene();
  112574. if (!scene) {
  112575. return;
  112576. }
  112577. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  112578. this.setFloat("brightness", this.brightness);
  112579. this.setFloat("persistence", this.persistence);
  112580. this.setFloat("timeScale", this._time);
  112581. };
  112582. NoiseProceduralTexture.prototype._getDefines = function () {
  112583. return "#define OCTAVES " + (this.octaves | 0);
  112584. };
  112585. /** Generate the current state of the procedural texture */
  112586. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  112587. this._updateShaderUniforms();
  112588. _super.prototype.render.call(this, useCameraPostProcess);
  112589. };
  112590. /**
  112591. * Serializes this noise procedural texture
  112592. * @returns a serialized noise procedural texture object
  112593. */
  112594. NoiseProceduralTexture.prototype.serialize = function () {
  112595. var serializationObject = {};
  112596. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  112597. serializationObject.brightness = this.brightness;
  112598. serializationObject.octaves = this.octaves;
  112599. serializationObject.persistence = this.persistence;
  112600. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  112601. serializationObject.size = this.getSize().width;
  112602. serializationObject.generateMipMaps = this._generateMipMaps;
  112603. return serializationObject;
  112604. };
  112605. /**
  112606. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  112607. * @param parsedTexture defines parsed texture data
  112608. * @param scene defines the current scene
  112609. * @param rootUrl defines the root URL containing noise procedural texture information
  112610. * @returns a parsed NoiseProceduralTexture
  112611. */
  112612. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  112613. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  112614. texture.brightness = parsedTexture.brightness;
  112615. texture.octaves = parsedTexture.octaves;
  112616. texture.persistence = parsedTexture.persistence;
  112617. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  112618. return texture;
  112619. };
  112620. return NoiseProceduralTexture;
  112621. }(BABYLON.ProceduralTexture));
  112622. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  112623. })(BABYLON || (BABYLON = {}));
  112624. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  112625. var __assign = (this && this.__assign) || function () {
  112626. __assign = Object.assign || function(t) {
  112627. for (var s, i = 1, n = arguments.length; i < n; i++) {
  112628. s = arguments[i];
  112629. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  112630. t[p] = s[p];
  112631. }
  112632. return t;
  112633. };
  112634. return __assign.apply(this, arguments);
  112635. };
  112636. var BABYLON;
  112637. (function (BABYLON) {
  112638. /**
  112639. * This can helps recording videos from BabylonJS.
  112640. * This is based on the available WebRTC functionalities of the browser.
  112641. *
  112642. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  112643. */
  112644. var VideoRecorder = /** @class */ (function () {
  112645. /**
  112646. * Create a new VideoCapture object which can help converting what you see in Babylon to
  112647. * a video file.
  112648. * @param engine Defines the BabylonJS Engine you wish to record
  112649. * @param options Defines options that can be used to customized the capture
  112650. */
  112651. function VideoRecorder(engine, options) {
  112652. if (options === void 0) { options = null; }
  112653. if (!VideoRecorder.IsSupported(engine)) {
  112654. throw "Your browser does not support recording so far.";
  112655. }
  112656. var canvas = engine.getRenderingCanvas();
  112657. if (!canvas) {
  112658. throw "The babylon engine must have a canvas to be recorded";
  112659. }
  112660. this._canvas = canvas;
  112661. this._canvas.isRecording = false;
  112662. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  112663. var stream = this._canvas.captureStream(this._options.fps);
  112664. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  112665. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  112666. this._mediaRecorder.onerror = this._handleError.bind(this);
  112667. this._mediaRecorder.onstop = this._handleStop.bind(this);
  112668. }
  112669. /**
  112670. * Returns wehther or not the VideoRecorder is available in your browser.
  112671. * @param engine Defines the Babylon Engine to check the support for
  112672. * @returns true if supported otherwise false
  112673. */
  112674. VideoRecorder.IsSupported = function (engine) {
  112675. var canvas = engine.getRenderingCanvas();
  112676. return (!!canvas && typeof canvas.captureStream === "function");
  112677. };
  112678. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  112679. /**
  112680. * True wether a recording is already in progress.
  112681. */
  112682. get: function () {
  112683. return !!this._canvas && this._canvas.isRecording;
  112684. },
  112685. enumerable: true,
  112686. configurable: true
  112687. });
  112688. /**
  112689. * Stops the current recording before the default capture timeout passed in the startRecording
  112690. * functions.
  112691. */
  112692. VideoRecorder.prototype.stopRecording = function () {
  112693. if (!this._canvas || !this._mediaRecorder) {
  112694. return;
  112695. }
  112696. if (!this.isRecording) {
  112697. return;
  112698. }
  112699. this._canvas.isRecording = false;
  112700. this._mediaRecorder.stop();
  112701. };
  112702. /**
  112703. * Starts recording the canvas for a max duration specified in parameters.
  112704. * @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.
  112705. * @param maxDuration Defines the maximum recording time in seconds.
  112706. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  112707. * @return a promise callback at the end of the recording with the video data in Blob.
  112708. */
  112709. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  112710. var _this = this;
  112711. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  112712. if (maxDuration === void 0) { maxDuration = 7; }
  112713. if (!this._canvas || !this._mediaRecorder) {
  112714. throw "Recorder has already been disposed";
  112715. }
  112716. if (this.isRecording) {
  112717. throw "Recording already in progress";
  112718. }
  112719. if (maxDuration > 0) {
  112720. setTimeout(function () {
  112721. _this.stopRecording();
  112722. }, maxDuration * 1000);
  112723. }
  112724. this._fileName = fileName;
  112725. this._recordedChunks = [];
  112726. this._resolve = null;
  112727. this._reject = null;
  112728. this._canvas.isRecording = true;
  112729. this._mediaRecorder.start(this._options.recordChunckSize);
  112730. return new Promise(function (resolve, reject) {
  112731. _this._resolve = resolve;
  112732. _this._reject = reject;
  112733. });
  112734. };
  112735. /**
  112736. * Releases internal resources used during the recording.
  112737. */
  112738. VideoRecorder.prototype.dispose = function () {
  112739. this._canvas = null;
  112740. this._mediaRecorder = null;
  112741. this._recordedChunks = [];
  112742. this._fileName = null;
  112743. this._resolve = null;
  112744. this._reject = null;
  112745. };
  112746. VideoRecorder.prototype._handleDataAvailable = function (event) {
  112747. if (event.data.size > 0) {
  112748. this._recordedChunks.push(event.data);
  112749. }
  112750. };
  112751. VideoRecorder.prototype._handleError = function (event) {
  112752. this.stopRecording();
  112753. if (this._reject) {
  112754. this._reject(event.error);
  112755. }
  112756. else {
  112757. throw new event.error;
  112758. }
  112759. };
  112760. VideoRecorder.prototype._handleStop = function () {
  112761. this.stopRecording();
  112762. var superBuffer = new Blob(this._recordedChunks);
  112763. if (this._resolve) {
  112764. this._resolve(superBuffer);
  112765. }
  112766. window.URL.createObjectURL(superBuffer);
  112767. if (this._fileName) {
  112768. BABYLON.Tools.Download(superBuffer, this._fileName);
  112769. }
  112770. };
  112771. VideoRecorder._defaultOptions = {
  112772. mimeType: "video/webm",
  112773. fps: 25,
  112774. recordChunckSize: 3000
  112775. };
  112776. return VideoRecorder;
  112777. }());
  112778. BABYLON.VideoRecorder = VideoRecorder;
  112779. })(BABYLON || (BABYLON = {}));
  112780. //# sourceMappingURL=babylon.videoRecorder.js.map
  112781. var BABYLON;
  112782. (function (BABYLON) {
  112783. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  112784. if (replace === void 0) { replace = false; }
  112785. // Dispose existing light in replace mode.
  112786. if (replace) {
  112787. if (this.lights) {
  112788. for (var i = 0; i < this.lights.length; i++) {
  112789. this.lights[i].dispose();
  112790. }
  112791. }
  112792. }
  112793. // Light
  112794. if (this.lights.length === 0) {
  112795. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  112796. }
  112797. };
  112798. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  112799. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  112800. if (replace === void 0) { replace = false; }
  112801. if (attachCameraControls === void 0) { attachCameraControls = false; }
  112802. // Dispose existing camera in replace mode.
  112803. if (replace) {
  112804. if (this.activeCamera) {
  112805. this.activeCamera.dispose();
  112806. this.activeCamera = null;
  112807. }
  112808. }
  112809. // Camera
  112810. if (!this.activeCamera) {
  112811. var worldExtends = this.getWorldExtends();
  112812. var worldSize = worldExtends.max.subtract(worldExtends.min);
  112813. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  112814. var camera;
  112815. var radius = worldSize.length() * 1.5;
  112816. // empty scene scenario!
  112817. if (!isFinite(radius)) {
  112818. radius = 1;
  112819. worldCenter.copyFromFloats(0, 0, 0);
  112820. }
  112821. if (createArcRotateCamera) {
  112822. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  112823. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  112824. arcRotateCamera.wheelPrecision = 100 / radius;
  112825. camera = arcRotateCamera;
  112826. }
  112827. else {
  112828. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  112829. freeCamera.setTarget(worldCenter);
  112830. camera = freeCamera;
  112831. }
  112832. camera.minZ = radius * 0.01;
  112833. camera.maxZ = radius * 1000;
  112834. camera.speed = radius * 0.2;
  112835. this.activeCamera = camera;
  112836. var canvas = this.getEngine().getRenderingCanvas();
  112837. if (attachCameraControls && canvas) {
  112838. camera.attachControl(canvas);
  112839. }
  112840. }
  112841. };
  112842. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  112843. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  112844. if (replace === void 0) { replace = false; }
  112845. if (attachCameraControls === void 0) { attachCameraControls = false; }
  112846. this.createDefaultLight(replace);
  112847. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  112848. };
  112849. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  112850. if (pbr === void 0) { pbr = false; }
  112851. if (scale === void 0) { scale = 1000; }
  112852. if (blur === void 0) { blur = 0; }
  112853. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  112854. if (!environmentTexture) {
  112855. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  112856. return null;
  112857. }
  112858. if (setGlobalEnvTexture) {
  112859. if (environmentTexture) {
  112860. this.environmentTexture = environmentTexture;
  112861. }
  112862. }
  112863. // Skybox
  112864. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  112865. if (pbr) {
  112866. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  112867. hdrSkyboxMaterial.backFaceCulling = false;
  112868. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  112869. if (hdrSkyboxMaterial.reflectionTexture) {
  112870. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  112871. }
  112872. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  112873. hdrSkyboxMaterial.disableLighting = true;
  112874. hdrSkyboxMaterial.twoSidedLighting = true;
  112875. hdrSkybox.infiniteDistance = true;
  112876. hdrSkybox.material = hdrSkyboxMaterial;
  112877. }
  112878. else {
  112879. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  112880. skyboxMaterial.backFaceCulling = false;
  112881. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  112882. if (skyboxMaterial.reflectionTexture) {
  112883. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  112884. }
  112885. skyboxMaterial.disableLighting = true;
  112886. hdrSkybox.infiniteDistance = true;
  112887. hdrSkybox.material = skyboxMaterial;
  112888. }
  112889. return hdrSkybox;
  112890. };
  112891. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  112892. if (BABYLON.EnvironmentHelper) {
  112893. return new BABYLON.EnvironmentHelper(options, this);
  112894. }
  112895. return null;
  112896. };
  112897. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  112898. if (webVROptions === void 0) { webVROptions = {}; }
  112899. return new BABYLON.VRExperienceHelper(this, webVROptions);
  112900. };
  112901. })(BABYLON || (BABYLON = {}));
  112902. //# sourceMappingURL=babylon.sceneHelpers.js.map
  112903. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  112904. 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};"};